Skip to main content

memstead_schema/
config.rs

1//! Mem configuration loading, validation, and top-level CRUD.
2//!
3//! Handles `.memstead/config.json` parsing, cross-field validation, and the
4//! `update_config_field` write helper. Projections/mediums, their
5//! validators, and the pre-rework migration have been dropped by the
6//! workspace rewrite — `projections` / `mediums`
7//! survive as unknown keys captured into `MemConfig.extra` so legacy
8//! configs still round-trip, but the engine does not interpret them.
9//!
10//! Port of @memstead/config (config-contract.js, index.js) and
11//! @agent-adapters/config-mcp (workspace.js).
12
13use std::collections::{BTreeMap, HashMap};
14use std::path::{Path, PathBuf};
15
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19/// The per-mem engine-internal directory under a folder mem's
20/// root — `<mem_root>/.memstead/` holds `config.json` and
21/// `changes.jsonl`. Defined here (rather than in `memstead-base`)
22/// because mem-config loading lives in this crate and `memstead-base`
23/// depends on it; `memstead-base` re-exports the constant for
24/// downstream consumers. Distinct from the workspace store directory
25/// (`memstead_base::WORKSPACE_STORE_DIR`) and from the in-zip member
26/// paths inside sealed archives ([`ARCHIVE_META_DIR`]), which are a
27/// separate on-disk format and never use this constant.
28pub const MEM_META_DIR: &str = ".memstead";
29
30// ---------------------------------------------------------------------------
31// Sealed-archive surface constants
32// ---------------------------------------------------------------------------
33//
34// A sealed archive is a zip whose engine-internal members live under one
35// meta directory: `.memstead/config.json` plus the embedded schema tree
36// `.memstead/schema/…` — the sole member layout. The file extension is
37// `.mem` — the sole spelling, read and written. Defined here because
38// this is the lowest crate every archive reader/writer (memstead-base,
39// memstead-git-branch, memstead-registry, memstead-wasm, the CLIs)
40// already depends on.
41
42/// In-zip meta directory of a sealed archive — the only spelling.
43pub const ARCHIVE_META_DIR: &str = ".memstead";
44/// Member path of the published config inside a sealed archive.
45pub const ARCHIVE_CONFIG_PATH: &str = ".memstead/config.json";
46/// Member-path prefix of the embedded schema tree (manifest at
47/// `<prefix>schema.yaml`, type files under `<prefix>types/`).
48pub const ARCHIVE_SCHEMA_PREFIX: &str = ".memstead/schema/";
49/// Member path of the optional authoring-provenance payload inside a
50/// sealed archive (see [`crate::archive_provenance`]). Additive: archives
51/// predating provenance omit it, and an engine that does not recognise it
52/// tolerates it as an unknown meta member.
53pub const ARCHIVE_PROVENANCE_PATH: &str = ".memstead/provenance.json";
54/// Member path of the optional engine-owned anchors sidecar inside a
55/// sealed archive (the E3a provenance-anchor payload). Additive: archives
56/// with no anchors omit it. Recognised as a first-class member so the
57/// canonical re-pack threads it through verbatim rather than
58/// silently stripping it (a recognised-but-malformed member is a typed
59/// validation failure, unlike unknown future meta members which stay
60/// tolerate-and-ignore).
61pub const ARCHIVE_ANCHORS_PATH: &str = ".memstead/anchors.json";
62/// File extension (without dot) of a sealed archive — the sole spelling.
63/// The one deliberately-distinct token in a project that is otherwise
64/// "memstead" everywhere — short, and derived from the project name.
65pub const ARCHIVE_EXTENSION: &str = "mem";
66
67// ---------------------------------------------------------------------------
68// Error types
69// ---------------------------------------------------------------------------
70
71#[derive(Debug, thiserror::Error)]
72pub enum ConfigError {
73    #[error("config file not found: {0}")]
74    NotFound(String),
75    #[error("invalid JSON in config file: {0}")]
76    InvalidJson(String),
77    #[error("config validation failed:\n{}", .0.iter().map(|e| format!("  - {e}")).collect::<Vec<_>>().join("\n"))]
78    ValidationFailed(Vec<String>),
79    #[error("{0}")]
80    Other(String),
81    #[error("io error: {0}")]
82    Io(#[from] std::io::Error),
83    #[error("json error: {0}")]
84    Json(#[from] serde_json::Error),
85}
86
87// ---------------------------------------------------------------------------
88// Config check result
89// ---------------------------------------------------------------------------
90
91/// Result of config validation — errors are fatal, warnings are informational.
92#[derive(Debug, Clone)]
93pub struct ConfigCheckResult {
94    pub valid: bool,
95    pub errors: Vec<String>,
96    pub warnings: Vec<String>,
97    /// Stable `UPPER_SNAKE_CASE` envelope code when the validator
98    /// detects a categorical failure that callers should branch on.
99    /// Currently set to `"LEGACY_FIELD_PRESENT"` when any entry in
100    /// `LEGACY_TOMBSTONE_KEYS` is present.
101    pub error_code: Option<String>,
102}
103
104// ---------------------------------------------------------------------------
105// Mem config types (deserialized from .memstead/config.json)
106// ---------------------------------------------------------------------------
107
108/// Role-based publish config.
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct RoleConfig {
111    pub include: Vec<String>,
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub exclude: Option<Vec<String>>,
114}
115
116/// Publish config.
117#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct PublishConfig {
119    pub roles: HashMap<String, RoleConfig>,
120}
121
122/// Community detection override.
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct CommunityOverride {
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub resolution: Option<f64>,
127    #[serde(skip_serializing_if = "Option::is_none")]
128    pub seed: Option<u32>,
129}
130
131/// One entry in `MemConfig.read_mems` — a read-only sealed mem
132/// archive attached to the primary mem as reference material.
133///
134/// The engine resolves each entry to a cache file: when `cache_key` is
135/// present, `<mem_cache_dir>/<name>-<cache_key>.mem` (content-addressed
136/// — see [`ReadMemSpec::cache_key`]); otherwise the legacy
137/// `<mem_cache_dir>/<name>.mem`.
138///
139/// Kept as a struct (rather than collapsing to a bare `ReadMemSource`)
140/// so forward-compatible fields can be added without another schema break.
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct ReadMemSpec {
143    pub source: ReadMemSource,
144    /// Content-address of the installed archive — a short hex digest of
145    /// the validator's canonical bytes. The install path writes the cache
146    /// file at `<cache>/<name>-<cache_key>.mem`, so two distinct archives
147    /// sharing an internal mem name land in distinct files (no collision)
148    /// and re-installing identical bytes resolves to the same file (dedup).
149    /// `None` for legacy registrations written before content-addressing;
150    /// the loader then falls back to the bare `<name>.mem` path.
151    #[serde(default, skip_serializing_if = "Option::is_none", rename = "cacheKey")]
152    pub cache_key: Option<String>,
153}
154
155/// How the app reconstitutes a read mem's cache file when missing.
156///
157/// The engine itself never fetches; `source` is metadata consumed by the
158/// app's installer. A `Registry` variant with scope/name identifiers
159/// will be added once the memstead.io registry ships.
160#[derive(Debug, Clone, Serialize, Deserialize)]
161#[serde(tag = "type", rename_all = "camelCase")]
162pub enum ReadMemSource {
163    /// User dropped an archive file onto the app. App cannot auto-reinstall —
164    /// it prompts the user to drop the original file again.
165    Local,
166    /// Fetched from an HTTPS URL (GitHub Releases, shared drive, any static
167    /// host). Engine-side no-op; the app's installer re-fetches on attach.
168    Url { url: String },
169    // `Registry` variant reserved for when the memstead.io registry ships.
170    // The exact shape (fields, id format like `@scope/name`) is designed
171    // then — declaring it up front without semantics would be
172    // speculative, and pre-1.0 adding a variant later is not a breaking
173    // change for anyone.
174}
175
176/// Reference to a schema by exact name and version — `name@x.y.z`.
177///
178/// Serializes/deserializes as a single string so mem configs read
179/// `{ "schema": "default@1.0.0" }` on disk. Range syntax (`^`, `~`,
180/// `latest`) is rejected — schema pinning is strict and explicit.
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct SchemaRef {
183    pub name: String,
184    pub version: semver::Version,
185}
186
187impl SchemaRef {
188    pub fn new(name: impl Into<String>, version: semver::Version) -> Self {
189        Self {
190            name: name.into(),
191            version,
192        }
193    }
194
195    pub fn as_display(&self) -> String {
196        format!("{}@{}", self.name, self.version)
197    }
198}
199
200impl std::fmt::Display for SchemaRef {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        write!(f, "{}@{}", self.name, self.version)
203    }
204}
205
206impl std::str::FromStr for SchemaRef {
207    type Err = String;
208
209    fn from_str(s: &str) -> Result<Self, Self::Err> {
210        let trimmed = s.trim();
211        if trimmed.is_empty() {
212            return Err("schema reference must not be empty (expected \"name@x.y.z\")".into());
213        }
214        let (name, version_str) = trimmed.split_once('@').ok_or_else(|| {
215            format!(
216                "schema reference '{trimmed}' must include an exact version — expected \"name@x.y.z\""
217            )
218        })?;
219        if name.is_empty() {
220            return Err("schema reference name must not be empty".into());
221        }
222        if version_str == "latest" {
223            return Err(format!(
224                "schema reference '{trimmed}' uses 'latest' — exact semver versions only"
225            ));
226        }
227        if version_str.starts_with(['^', '~', '>', '<', '=', '*']) {
228            return Err(format!(
229                "schema reference '{trimmed}' uses range syntax — exact semver only (e.g. 'default@1.0.0')"
230            ));
231        }
232        let version = semver::Version::parse(version_str).map_err(|e| {
233            format!("schema reference '{trimmed}' has invalid semver version '{version_str}': {e}")
234        })?;
235        Ok(Self {
236            name: name.to_string(),
237            version,
238        })
239    }
240}
241
242impl Serialize for SchemaRef {
243    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
244        serializer.serialize_str(&self.as_display())
245    }
246}
247
248impl<'de> Deserialize<'de> for SchemaRef {
249    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
250        let s = String::deserialize(deserializer)?;
251        s.parse::<SchemaRef>().map_err(serde::de::Error::custom)
252    }
253}
254
255// `MemSchemaPin` (the two-variant pin with a name-only fallback) was
256// retired here. Mem configs now declare a strict `<name>@<version>`
257// pin parsed directly through [`SchemaRef`]; bare-name pins are
258// rejected at config load.
259
260/// VCS layout for a writable mem — optional `{ gitdir, worktree }` pair
261/// in `.memstead/config.json`. When absent, the engine resolves the default:
262/// `.git/` at mem root with `.` as worktree.
263///
264/// Paths are relative to mem root and interpreted by `memstead-git-branch` —
265/// this crate just carries them through serde. Masterplan §3.4 is
266/// explicit that the primitive is a pair of paths; the two canonical
267/// idioms (isolated `{ ".git", "." }` and shared `{ "../.git", ".." }`)
268/// are idioms, not enum variants.
269#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
270#[serde(rename_all = "camelCase")]
271pub struct VcsConfig {
272    /// Path to the gitdir relative to mem root. Required when the
273    /// `vcs` block is present.
274    pub gitdir: String,
275    /// Path to the worktree relative to mem root. Optional within the
276    /// `vcs` block — defaults to `"."` (mem root) when omitted.
277    #[serde(default = "vcs_worktree_default")]
278    pub worktree: String,
279}
280
281fn vcs_worktree_default() -> String {
282    ".".to_string()
283}
284
285/// Tolerant deserializer for the `vcs` field: accepts the object form
286/// (`{ gitdir, worktree? }`) and returns `None` for any non-object value
287/// (string, number, boolean, null). A missing field is also `None`.
288///
289/// Motivation: an older macOS Mem-mode UI wrote `"vcs": "system"`
290/// (and similar sentinel strings) into `.memstead/config.json` files that
291/// now must continue to load without editing those files by hand.
292/// Strict validation of the object form — unknown keys, missing
293/// `gitdir`, etc. — still surfaces as a hard serde error.
294fn deserialize_vcs_tolerant<'de, D>(deserializer: D) -> Result<Option<VcsConfig>, D::Error>
295where
296    D: serde::Deserializer<'de>,
297{
298    let value = Option::<Value>::deserialize(deserializer)?;
299    match value {
300        None | Some(Value::Null) => Ok(None),
301        Some(Value::Object(_)) => {
302            let v = value.unwrap();
303            Ok(Some(
304                serde_json::from_value(v).map_err(serde::de::Error::custom)?,
305            ))
306        }
307        Some(_) => Ok(None),
308    }
309}
310
311/// The subject block of a mem — what it covers, by what method, and
312/// above all what was considered and deliberately left out. Exactly
313/// three members, by design: every additional slot invites the
314/// working-notes leakage this block exists to avoid, and three is what
315/// a recipient can actually read before deciding whether to trust the
316/// mem. Published verbatim in [`PublishedMemConfig`]; the engine never
317/// parses, links, or validates the prose.
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319#[serde(deny_unknown_fields, rename_all = "camelCase")]
320pub struct MemSubject {
321    /// What this mem covers.
322    pub scope: String,
323    /// How its content was arrived at.
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub method: Option<String>,
326    /// What was considered and deliberately left out — prose
327    /// statements, order preserved. May be empty.
328    #[serde(default)]
329    pub exclusions: Vec<String>,
330}
331
332/// Engine-owned version stamp of the last successful mutation on a
333/// mem — see [`MemConfig::mutation_stamp`]. Both values are recorded
334/// at mutation time: `engine_version` is the engine crate version the
335/// acting binary was built from, `schema` the resolved
336/// `<name>@<version>` the mutation validated against (the resolved
337/// schema, not merely the pin — mid-migration mems stamp the target
338/// they validated against).
339#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
340#[serde(deny_unknown_fields, rename_all = "camelCase")]
341pub struct MutationStamp {
342    /// Full build version of the binary that performed the last
343    /// mutation — `memstead-base`'s `build_info::full_version()`:
344    /// the crate semver, plus `+g<sha>[-dirty]` build metadata when
345    /// built inside a git checkout, so dev builds between releases
346    /// stamp distinguishably. Older stamps carry the plain semver
347    /// and compare against the full current value — firing the skew
348    /// hint on the first post-upgrade boot is desired, no migration.
349    pub engine_version: String,
350    /// Resolved schema `<name>@<version>` the last mutation validated
351    /// against.
352    pub schema: String,
353}
354
355/// Full mem configuration loaded from .memstead/config.json.
356#[derive(Debug, Clone, Serialize, Deserialize)]
357#[serde(rename_all = "camelCase")]
358pub struct MemConfig {
359    /// Optional mem name. The leaf folder name under
360    /// `__MEMSTEAD:mems/` (and the disk basename on the legacy disk
361    /// path) is authoritative; engine-written configs omit this
362    /// field. Tolerated on read for pre-cutover configs and for the
363    /// [`PublishedMemConfig`] conversion path that still requires
364    /// an explicit identity (the caller passes the name in when
365    /// projecting).
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub name: Option<String>,
368
369    /// Semver version of the mem content. Read at mem-archive export
370    /// time so the engine always knows the current version without manual
371    /// tracking. Parsed at config load — invalid version strings fail fast
372    /// with a source-attributed serde error rather than slipping through to
373    /// export (where the issue only surfaces when a downstream loader tries
374    /// to resolve a `semver::VersionReq` against the mem).
375    #[serde(skip_serializing_if = "Option::is_none")]
376    pub version: Option<semver::Version>,
377
378    /// One-line description of the mem, surfaced in mem-archive metadata
379    /// and UI.
380    #[serde(skip_serializing_if = "Option::is_none")]
381    pub description: Option<String>,
382
383    /// Human-readable display title. Display text, NOT identity: no
384    /// slug grammar, no uniqueness rule — the mem name stays the sole
385    /// handle everywhere (paths, grants, namespace patterns, cross-mem
386    /// references, archive filenames). Surfaces that print a mem
387    /// prefer this and fall back to the name. Published in
388    /// [`PublishedMemConfig`].
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub title: Option<String>,
391
392    /// The mem's subject — scope, method, deliberate exclusions.
393    /// Published verbatim; clears as a unit.
394    #[serde(default, skip_serializing_if = "Option::is_none")]
395    pub subject: Option<MemSubject>,
396
397    /// Optional author attribution, surfaced in mem-archive metadata.
398    #[serde(skip_serializing_if = "Option::is_none")]
399    pub authors: Option<Vec<String>>,
400
401    /// Declared process-mem pairing (agent-trust plan 14): the name
402    /// of the mem holding this mem's process tier (verification
403    /// targets, findings, inquiry entries). Declaration wins over the
404    /// binding-name derivation the brief renderer and the
405    /// open-questions health axis otherwise use; a declaration naming
406    /// an unmounted mem surfaces as a typed health finding, never a
407    /// silent fallback. Absent means "derive by convention" — the
408    /// pre-declaration behaviour, unchanged.
409    #[serde(default, skip_serializing_if = "Option::is_none")]
410    pub process_mem: Option<String>,
411
412    /// Schema this mem is pinned to. Exact `<name>@<version>` pin
413    /// only — bare-name forms are rejected at config load. Exactly one
414    /// schema per mem. The `Option` keeps serde tolerant so a missing
415    /// key surfaces as a structured error from `check_config` rather
416    /// than a deserialize panic; a `None` value is a validation error.
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub schema: Option<SchemaRef>,
419
420    /// Opaque string-map passed through by the engine. Agents and
421    /// plugin prompt renderers are free to invent their own keys; the
422    /// engine does not parse, validate, or interpret any value inside.
423    /// Stripped from `PublishedMemConfig` — guidance is workspace-
424    /// local authorship metadata, not part of the published identity.
425    ///
426    /// Pre-2026-04-24 this field was `Option<Value>`; the workspace
427    /// rewrite normalised it to a map so the shape on
428    /// the wire is stable and the engine's pass-through guarantee is
429    /// type-checked.
430    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
431    pub write_guidance: HashMap<String, Value>,
432    #[serde(skip_serializing_if = "Option::is_none")]
433    pub rules: Option<Value>,
434
435    #[serde(skip_serializing_if = "Option::is_none")]
436    pub publish: Option<PublishConfig>,
437    #[serde(skip_serializing_if = "Option::is_none")]
438    pub language: Option<String>,
439    /// Read-only sealed-archive mems attached to this mem as reference
440    /// material. Key is the mem name (matches the archive's
441    /// config name). Engine resolves each entry to
442    /// `<mem_cache_dir>/<name>.mem` at init time. An empty or omitted
443    /// map means no attached mems — a graph with no reference material.
444    ///
445    /// `BTreeMap` (not `HashMap`) so iteration and serialization order
446    /// are stable — reproducible log output and diff-friendly config on
447    /// disk. Explicit `rename = "readMems"` documents the on-disk name
448    /// at the field (the struct-level `rename_all = "camelCase"` already
449    /// handles it, but explicit rename is greppable from either side).
450    #[serde(
451        rename = "readMems",
452        default,
453        skip_serializing_if = "BTreeMap::is_empty"
454    )]
455    pub read_mems: BTreeMap<String, ReadMemSpec>,
456    #[serde(skip_serializing_if = "Option::is_none")]
457    pub community: Option<CommunityOverride>,
458
459    /// Optional VCS layout override. When absent, `memstead-git-branch` resolves
460    /// the default at init time: `.git/` at mem root with `.` as
461    /// worktree. When present, `gitdir` and `worktree` are paths
462    /// relative to the mem root. Stripped from `PublishedMemConfig`
463    /// — VCS layout is workspace-local mechanics, not part of the
464    /// published mem's identity.
465    ///
466    /// Deserialization is tolerant of legacy non-object values (e.g.
467    /// `"vcs": "system"` — the sentinel an older macOS Mem-mode
468    /// UI wrote): any non-object form deserializes to `None` and falls
469    /// back to the default-resolution path. The object form is validated
470    /// strictly.
471    #[serde(
472        default,
473        deserialize_with = "deserialize_vcs_tolerant",
474        skip_serializing_if = "Option::is_none"
475    )]
476    pub vcs: Option<VcsConfig>,
477
478    /// Tombstone marker written by `memstead mem unregister`. ISO-8601
479    /// UTC timestamp (`YYYY-MM-DDTHH:MM:SSZ`) recorded at the moment
480    /// the mem was unregistered while its storage was preserved.
481    /// When `memstead mem init <same-name>`
482    /// probes the storage and finds an `unregistered_at` value, it
483    /// treats the residue as deliberate operator state and defaults
484    /// to the `Reattach` recovery action (adopting the preserved
485    /// entities and clearing the tombstone). Absence (`None`) on
486    /// otherwise-present residue triggers `MEM_STORAGE_RESIDUE_DETECTED`
487    /// unless the caller passes an explicit `recovery` flag. Stripped
488    /// from `PublishedMemConfig` — tombstones are workspace-local
489    /// lifecycle state, not part of the published mem's identity.
490    #[serde(default, skip_serializing_if = "Option::is_none")]
491    pub unregistered_at: Option<String>,
492
493    /// Per-source "last successfully synced source state", written by
494    /// the ingest layer and surfaced verbatim on the workspace dump.
495    /// The engine never parses, validates, or interprets a value:
496    /// each token is opaque, its meaning owned by the medium-type
497    /// layer that produced it (git → commit id, graph → snapshot
498    /// token, filesystem → a small stat digest the plugin
499    /// JSON-stringifies). The key is likewise opaque — the binding
500    /// layer keys per `(binding, facet)` (conventionally
501    /// `"<binding-id>/<facet>#synced"`, D4), but the engine treats it as
502    /// an arbitrary string. This is the durable, shared baseline against which a
503    /// fresh ingest iteration diffs "what changed since last time";
504    /// it survives a skill-cache wipe and a machine change because it
505    /// lives in engine-held mem config, not ephemeral plugin cache.
506    ///
507    /// Stripped from `PublishedMemConfig` — sync state is
508    /// workspace-local ingest bookkeeping, not part of a published
509    /// mem's identity. `BTreeMap` (not `HashMap`) for stable
510    /// serialization order: diff-friendly config on disk and
511    /// reproducible dump output.
512    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
513    pub sync_state: BTreeMap<String, String>,
514
515    /// The mem's review mark: the last human-approved state, in the
516    /// backend-opaque cursor vocabulary `changes_since` consumes
517    /// (git-branch: commit SHA; folder: changelog RFC3339 timestamp).
518    /// Absent is a first-class state — a mem with no mark is ordinary,
519    /// never an error, and marks never gate writes. One mark per mem;
520    /// wire key `reviewMark` (camelCase per the config's convention).
521    ///
522    /// Stripped from `PublishedMemConfig` (allowlist projection) —
523    /// review state is workspace-collaboration bookkeeping, not part
524    /// of a published mem's identity.
525    #[serde(
526        default,
527        rename = "reviewMark",
528        skip_serializing_if = "Option::is_none"
529    )]
530    pub review_mark: Option<String>,
531
532    /// Engine-owned version stamp of the last successful mutation:
533    /// which engine version and which resolved schema performed it.
534    /// Written by the engine after a mutation and only when the values
535    /// changed (a binary upgrade or a schema repin), never by authors,
536    /// never on read-only loads — a boot writes nothing. Boot compares
537    /// the running binary against the stamp and surfaces a divergence
538    /// as the warn-tier `ENGINE_VERSION_SKEW` hint; absence of a stamp
539    /// is a first-class state (pre-stamp mems), never skew. The stamp
540    /// is the substrate any future migration machinery would consult —
541    /// deliberately built without that machinery.
542    ///
543    /// Stripped from `PublishedMemConfig` (allowlist projection) —
544    /// workspace-local engine bookkeeping, not published identity.
545    /// Wire key `mutationStamp` (camelCase per the config convention).
546    #[serde(
547        default,
548        rename = "mutationStamp",
549        skip_serializing_if = "Option::is_none"
550    )]
551    pub mutation_stamp: Option<MutationStamp>,
552
553    /// Extra fields not in the known set (captured for round-tripping).
554    ///
555    /// Historical tombstones:
556    /// - `defaultSchema` (pre-2026-04): legacy per-mem default type.
557    ///   Per-entity `type:` frontmatter is authoritative now.
558    /// - `types: [...]` (pre-schema-artifact, 2026-04): replaced by
559    ///   `schema: "<name>@<version>"`. Legacy entries are hard-rejected
560    ///   by `check_config`.
561    #[serde(flatten)]
562    pub extra: HashMap<String, Value>,
563}
564
565// ---------------------------------------------------------------------------
566// Published (archive) mem config
567// ---------------------------------------------------------------------------
568
569/// Strict-ingress shape of a mem config. This is the **only** metadata
570/// form that enters a `.mem` archive. `MemConfig` carries author-only
571/// fields (writeGuidance, rules, publish, readMems, language,
572/// community, defaultSchema, vcs, plus any key captured in
573/// `extra`) that never belong in a published archive;
574/// `published_config_from` projects `MemConfig` →
575/// `PublishedMemConfig`, dropping everything outside the whitelist.
576///
577/// `deny_unknown_fields` + no `serde(flatten)` on purpose: the validator
578/// re-parses this shape with the same struct as defense-in-depth, so any
579/// legacy author key smuggled into an archive surfaces as a rejection
580/// instead of a silently-tolerated payload.
581#[derive(Debug, Clone, Serialize, Deserialize)]
582#[serde(deny_unknown_fields, rename_all = "camelCase")]
583pub struct PublishedMemConfig {
584    pub format: u32,
585    pub name: String,
586    pub version: semver::Version,
587    #[serde(skip_serializing_if = "Option::is_none")]
588    pub description: Option<String>,
589    /// Human-readable display title (format ≥ 4). Display text, not
590    /// identity — a format-3 archive simply has none.
591    #[serde(default, skip_serializing_if = "Option::is_none")]
592    pub title: Option<String>,
593    /// The mem's subject block (format ≥ 4), published verbatim —
594    /// exclusions included and in order.
595    #[serde(default, skip_serializing_if = "Option::is_none")]
596    pub subject: Option<MemSubject>,
597    #[serde(skip_serializing_if = "Option::is_none")]
598    pub authors: Option<Vec<String>>,
599    pub schema: SchemaRef,
600}
601
602/// Archive format integer written to the archive config's `format`
603/// field. Bumped to `4` for the mem title + subject block (both
604/// optional — a format-3 archive simply has neither). Readers accept
605/// `3` and `4` via [`published_format_accepted`]; `format: 1` (V1) and
606/// `format: 2` (V2, top-level `schema/` tree) archives keep refusing
607/// cleanly.
608pub const PUBLISHED_MEM_FORMAT: u32 = 4;
609
610/// Does a reader updated for the current format accept an archive at
611/// `format`? Accepts the current integer and format 3 (the
612/// pre-title/subject shape — the two mems already published on the
613/// live registry stay installable without a re-publish). The single
614/// predicate every reader gate consults, so acceptance cannot drift
615/// per surface.
616pub fn published_format_accepted(format: u32) -> bool {
617    format == PUBLISHED_MEM_FORMAT || format == 3
618}
619
620/// Errors returned by `published_config_from`. Actionable messages —
621/// the caller (export pipeline, publish pipeline) surfaces these
622/// directly to the user without wrapping a raw serde error.
623#[derive(Debug, thiserror::Error)]
624pub enum PublishConversionError {
625    #[error("config.version is required for mem publish — set it in .memstead/config.json")]
626    MissingVersion,
627    #[error(
628        "config must declare `schema` (e.g. \"default@1.0.0\") — set it in .memstead/config.json"
629    )]
630    MissingSchema,
631    #[error(
632        "publish requires an explicit mem name — caller must pass the leaf folder name (Goal 3 of mem-repo-restructure dropped the in-config `name` requirement)"
633    )]
634    MissingName,
635}
636
637/// The whitelist projection. Everything author-only is discarded; only
638/// the fields that make sense outside the author's working directory
639/// ride into the archive. `format` is pinned at `PUBLISHED_MEM_FORMAT`.
640///
641/// `name` is supplied explicitly by the caller — the on-disk `name`
642/// field is optional and the engine no longer treats it as the
643/// mem-identity source. The published archive still needs an
644/// identity, so the publishing path passes the leaf folder name
645/// (`__MEMSTEAD:mems/<path>/<leaf>/config.json`'s `<leaf>`, or the
646/// disk basename on the legacy disk path) here. Falls back to the
647/// in-config `name` field when the caller passes an empty string and
648/// the config still carries a legacy `name` value (so pre-cutover
649/// archives published before the migration land cleanly).
650pub fn published_config_from(
651    config: &MemConfig,
652    name: &str,
653) -> Result<PublishedMemConfig, PublishConversionError> {
654    let version = config
655        .version
656        .clone()
657        .ok_or(PublishConversionError::MissingVersion)?;
658    let schema = config
659        .schema
660        .clone()
661        .ok_or(PublishConversionError::MissingSchema)?;
662    let resolved_name = if name.is_empty() {
663        config
664            .name
665            .clone()
666            .ok_or(PublishConversionError::MissingName)?
667    } else {
668        name.to_string()
669    };
670    Ok(PublishedMemConfig {
671        format: PUBLISHED_MEM_FORMAT,
672        name: resolved_name,
673        version,
674        description: config.description.clone(),
675        title: config.title.clone(),
676        subject: config.subject.clone(),
677        authors: config.authors.clone(),
678        schema,
679    })
680}
681
682// ---------------------------------------------------------------------------
683// Constants
684// ---------------------------------------------------------------------------
685
686const KNOWN_TOP_LEVEL_KEYS: &[&str] = &[
687    "version",
688    "description",
689    "title",
690    "subject",
691    "authors",
692    "schema",
693    "writeGuidance",
694    "rules",
695    "publish",
696    "language",
697    "readMems",
698    "community",
699    "vcs",
700    "syncState",
701];
702
703/// Keys that are explicitly rejected with a `LEGACY_FIELD_PRESENT`
704/// envelope when present in a config. The validator surfaces a hard
705/// error (not a soft "unknown key" warning) so agents that recreate
706/// the legacy shape from training-set examples see a structured
707/// rejection instead of silent acceptance with drift.
708///
709/// Each entry pairs the rejected key with an actionable error message.
710/// New tombstones land here when a top-level key migrates from
711/// "deprecated but tolerated" to "must not be re-authored". The table
712/// holds entries for `name` (the field is now path-derived) and
713/// `types: [...]` (the pre-existing tombstone, preserved verbatim).
714const LEGACY_TOMBSTONE_KEYS: &[(&str, &str)] = &[
715    (
716        "types",
717        "Legacy `types: [...]` field detected — replace with `schema: \"<name>@<version>\"` \
718         (e.g. `\"schema\": \"default@1.0.0\"`).",
719    ),
720    (
721        "name",
722        "Legacy `name` field detected — the mem leaf folder under `__MEMSTEAD:mems/` (or the \
723         disk basename on the legacy disk path) is path-derived under the unified layout; \
724         remove the field from `.memstead/config.json`.",
725    ),
726    (
727        "belongsTo",
728        "Legacy `belongsTo` field detected — cross-mem authorization moved to the \
729         workspace-level `[cross_mem_links]` section in `.memstead/workspace.toml`. Remove the \
730         field from `.memstead/config.json` and add an entry under `[cross_mem_links]` \
731         instead.",
732    ),
733];
734
735// ---------------------------------------------------------------------------
736// checkConfig — the main validator
737// ---------------------------------------------------------------------------
738
739/// Validate a raw config JSON value. Returns structured errors and warnings.
740pub fn check_config(config: &Value) -> ConfigCheckResult {
741    let mut errors = Vec::new();
742    let mut warnings = Vec::new();
743
744    let obj = match config.as_object() {
745        Some(o) => o,
746        None => {
747            errors.push("(root): config must be an object".to_string());
748            return ConfigCheckResult {
749                valid: false,
750                errors,
751                warnings,
752                error_code: None,
753            };
754        }
755    };
756
757    // 2. Legacy tombstones — keys that must not be re-authored. Each
758    //    hit produces a hard error and pins the `LEGACY_FIELD_PRESENT`
759    //    envelope code so callers branch on a stable identifier rather
760    //    than the human-readable error message. See
761    //    `LEGACY_TOMBSTONE_KEYS` for the reject list.
762    let mut legacy_field_hit = false;
763    for (key, message) in LEGACY_TOMBSTONE_KEYS {
764        if obj.contains_key(*key) {
765            errors.push((*message).to_string());
766            legacy_field_hit = true;
767        }
768    }
769
770    // 3. Schema field: exact `name@x.y.z` reference required. Bare-name
771    //    pins are rejected at parse time via SchemaRef::from_str.
772    match obj.get("schema") {
773        Some(Value::String(s)) => {
774            if let Err(e) = s.parse::<SchemaRef>() {
775                errors.push(format!("schema: {e}"));
776            }
777        }
778        Some(_) => errors.push(
779            "schema: must be a string of the form \"<name>@<x.y.z>\" \
780             (exact version pin, e.g. \"default@1.0.0\")"
781                .to_string(),
782        ),
783        None => errors.push(
784            "Config must declare `schema` — exact pin of the form \
785             \"<name>@<x.y.z>\" (e.g. \"default@1.0.0\")"
786                .to_string(),
787        ),
788    }
789
790    // 4. Read-mems map — source presence and shape.
791    //    Cache-file existence is checked at engine init (`Engine::init`
792    //    via `mem_cache`), not here, so isolated schema tests don't
793    //    need real archive fixture files. The cached archive's config is
794    //    authoritative for the version; no `version` or `path` is
795    //    recorded in the config entry.
796    if let Some(Value::Object(mems)) = obj.get("readMems") {
797        for (name, spec) in mems {
798            let entry_path = format!("readMems.{name}");
799
800            let spec_obj = match spec.as_object() {
801                Some(o) => o,
802                None => {
803                    errors.push(format!("{entry_path}: read-mem entry must be an object"));
804                    continue;
805                }
806            };
807
808            let source = match spec_obj.get("source").and_then(|v| v.as_object()) {
809                Some(s) => s,
810                None => {
811                    errors.push(format!(
812                        "{entry_path}.source: read-mem entry must declare a source \
813                         (e.g. {{\"type\": \"local\"}} or {{\"type\": \"url\", \"url\": \"…\"}})"
814                    ));
815                    continue;
816                }
817            };
818
819            match source.get("type").and_then(|v| v.as_str()) {
820                Some("local") => {}
821                Some("url") => match source.get("url").and_then(|v| v.as_str()) {
822                    Some(u) if !u.is_empty() => {}
823                    _ => errors.push(format!(
824                        "{entry_path}.source.url: url source must declare a non-empty 'url' string"
825                    )),
826                },
827                // `registry` type is reserved for future use but not
828                // accepted yet — fails here alongside any other unknown.
829                Some(other) => errors.push(format!(
830                    "{entry_path}.source.type: unknown source type '{other}' \
831                     (expected 'local' or 'url')"
832                )),
833                None => errors.push(format!(
834                    "{entry_path}.source.type: source must declare a 'type' \
835                     ('local' or 'url')"
836                )),
837            }
838        }
839    }
840
841    // 5. `belongsTo` is now a tombstone (see `LEGACY_TOMBSTONE_KEYS`).
842    //    Cross-mem authorization moved to the workspace-level
843    //    `[cross_mem_links]` section in `.memstead/workspace.toml`. Per-mem config
844    //    blobs that still carry the field are rejected with the
845    //    tombstone error above; no shape validation runs here.
846
847    // 7. Unknown key warnings. Tombstone keys are rejected above and
848    //    skipped here so callers don't see a redundant warning alongside
849    //    the hard error.
850    for key in obj.keys() {
851        if KNOWN_TOP_LEVEL_KEYS.contains(&key.as_str())
852            || LEGACY_TOMBSTONE_KEYS
853                .iter()
854                .any(|(k, _)| *k == key.as_str())
855        {
856            continue;
857        }
858        warnings.push(format!(
859            "Unknown config key '{key}' \u{2014} will be ignored"
860        ));
861    }
862
863    let error_code = if legacy_field_hit {
864        Some("LEGACY_FIELD_PRESENT".to_string())
865    } else {
866        None
867    };
868
869    ConfigCheckResult {
870        valid: errors.is_empty(),
871        errors,
872        warnings,
873        error_code,
874    }
875}
876
877// ---------------------------------------------------------------------------
878// Config loading
879// ---------------------------------------------------------------------------
880
881/// Load and parse a config from a mem directory.
882/// Reads `<mem_dir>/.memstead/config.json`.
883pub fn load_config(mem_dir: &Path) -> Result<(Value, PathBuf), ConfigError> {
884    let config_path = mem_dir.join(MEM_META_DIR).join("config.json");
885    let raw = std::fs::read_to_string(&config_path).map_err(|e| {
886        if e.kind() == std::io::ErrorKind::NotFound {
887            ConfigError::NotFound(config_path.display().to_string())
888        } else {
889            ConfigError::Io(e)
890        }
891    })?;
892    let parsed: Value = serde_json::from_str(&raw)
893        .map_err(|_| ConfigError::InvalidJson(config_path.display().to_string()))?;
894    Ok((parsed, config_path))
895}
896
897/// Parse a raw JSON value into a MemConfig.
898pub fn parse_mem_config(value: &Value) -> Result<MemConfig, ConfigError> {
899    serde_json::from_value(value.clone()).map_err(|e| ConfigError::Other(e.to_string()))
900}
901
902/// Load, validate, and parse a mem config from disk.
903pub fn load_and_validate(mem_dir: &Path) -> Result<MemConfig, ConfigError> {
904    let (raw, _path) = load_config(mem_dir)?;
905
906    let result = check_config(&raw);
907    if !result.valid {
908        return Err(ConfigError::ValidationFailed(result.errors));
909    }
910
911    parse_mem_config(&raw)
912}
913
914// ---------------------------------------------------------------------------
915// Config writing
916// ---------------------------------------------------------------------------
917
918/// Write a config JSON value to disk (pretty-printed with trailing newline).
919fn write_config(config_path: &Path, config: &Value) -> Result<(), ConfigError> {
920    let json = serde_json::to_string_pretty(config)? + "\n";
921    std::fs::write(config_path, json)?;
922    Ok(())
923}
924
925/// Validate and write a config to disk. Returns check result.
926fn commit_config(
927    config_path: &Path,
928    config: &Value,
929    dry_run: bool,
930) -> Result<ConfigCheckResult, ConfigError> {
931    let check = check_config(config);
932    if !check.valid {
933        return Ok(check);
934    }
935    if !dry_run {
936        write_config(config_path, config)?;
937    }
938    Ok(check)
939}
940
941// ---------------------------------------------------------------------------
942// Config CRUD operations
943// ---------------------------------------------------------------------------
944
945/// Allowed top-level fields for `update_config_field`. Mirrored by the
946/// macOS app's `WorkspaceService.allowedUpdateFields`. The
947/// workspace rewrite dropped `mediums` and
948/// `projections` here: the engine no longer recognises those blocks so
949/// they are not writable through the update surface either.
950const ALLOWED_UPDATE_FIELDS: &[&str] = &[
951    "version",
952    "description",
953    "authors",
954    "writeGuidance",
955    "rules",
956    "readMems",
957    "schema",
958    "language",
959    "publish",
960];
961
962const PROTECTED_FIELDS: &[&str] = &["name"];
963
964/// Update a top-level config field.
965pub fn update_config_field(
966    config_path: &Path,
967    config: &mut Value,
968    field: &str,
969    value: Value,
970    dry_run: bool,
971) -> Result<ConfigCheckResult, ConfigError> {
972    if PROTECTED_FIELDS.contains(&field) {
973        return Err(ConfigError::Other(format!("Field '{field}' is protected")));
974    }
975
976    let obj = config
977        .as_object_mut()
978        .ok_or_else(|| ConfigError::Other("config must be an object".into()))?;
979
980    if !ALLOWED_UPDATE_FIELDS.contains(&field) {
981        return Err(ConfigError::Other(format!(
982            "Field '{field}' is not a recognized config field. Allowed: {}",
983            ALLOWED_UPDATE_FIELDS.join(", ")
984        )));
985    }
986
987    obj.insert(field.to_string(), value);
988    commit_config(config_path, config, dry_run)
989}
990
991// ===========================================================================
992// Tests
993// ===========================================================================
994
995#[cfg(test)]
996mod tests {
997    use super::*;
998    use serde_json::json;
999
1000    // --- check_config tests ---
1001
1002    fn minimal_valid_config() -> Value {
1003        json!({
1004            "schema": "default@1.0.0"
1005        })
1006    }
1007
1008    #[test]
1009    fn check_valid_minimal_config() {
1010        let result = check_config(&minimal_valid_config());
1011        assert!(result.valid, "errors: {:?}", result.errors);
1012    }
1013
1014    /// The in-config `name` field is optional — configs without a
1015    /// `name` key are valid; the leaf folder name under
1016    /// `__MEMSTEAD:mems/` (or the disk basename on the legacy disk
1017    /// path) is the authoritative identifier instead.
1018    #[test]
1019    fn check_missing_name_now_valid() {
1020        let config = json!({"schema": "default@1.0.0"});
1021        let result = check_config(&config);
1022        assert!(result.valid, "errors: {:?}", result.errors);
1023    }
1024
1025    /// `parse_mem_config` produces a `MemConfig` whose `name` is
1026    /// `None` when the on-disk config omits the field. Pins the
1027    /// Goal 3 wire-shape contract.
1028    #[test]
1029    fn parse_mem_config_name_none_when_field_absent() {
1030        let config = json!({"schema": "default@1.0.0"});
1031        let parsed = parse_mem_config(&config).expect("name-less config parses");
1032        assert!(parsed.name.is_none());
1033    }
1034
1035    /// Round-trip: a `MemConfig` whose `name` is `None` serialises
1036    /// without the `name` key (skip-if-none on the serde attribute).
1037    /// Pins the on-disk minimisation contract.
1038    #[test]
1039    fn mem_config_omits_name_when_none_on_serialize() {
1040        let cfg = MemConfig {
1041            name: None,
1042            title: None,
1043            subject: None,
1044            version: None,
1045            description: None,
1046            authors: None,
1047            process_mem: None,
1048            schema: Some(SchemaRef::new("default", semver::Version::new(1, 0, 0))),
1049            write_guidance: Default::default(),
1050            rules: None,
1051            publish: None,
1052            language: None,
1053            read_mems: Default::default(),
1054            community: None,
1055            vcs: None,
1056            unregistered_at: None,
1057            sync_state: Default::default(),
1058            review_mark: None,
1059            mutation_stamp: None,
1060            extra: Default::default(),
1061        };
1062        let json = serde_json::to_string(&cfg).unwrap();
1063        assert!(
1064            !json.contains("\"name\""),
1065            "serialized config must omit `name` when None, got: {json}"
1066        );
1067    }
1068
1069    /// A stray `name` field is rejected with `LEGACY_FIELD_PRESENT`
1070    /// regardless of its value (empty or non-empty). Both empty and
1071    /// non-empty shapes collapse onto the legacy tombstone reject.
1072    #[test]
1073    fn check_legacy_name_field_rejected() {
1074        for value in [json!(""), json!("@test/mem")] {
1075            let config = json!({"name": value, "schema": "default@1.0.0"});
1076            let result = check_config(&config);
1077            assert!(!result.valid, "name={value}: expected reject");
1078            assert_eq!(
1079                result.error_code.as_deref(),
1080                Some("LEGACY_FIELD_PRESENT"),
1081                "name={value}: expected LEGACY_FIELD_PRESENT envelope"
1082            );
1083            assert!(
1084                result.errors.iter().any(|e| e.contains("Legacy `name`")),
1085                "name={value}: errors {:?}",
1086                result.errors
1087            );
1088        }
1089    }
1090
1091    #[test]
1092    fn check_missing_schema() {
1093        let config = json!({});
1094        let result = check_config(&config);
1095        assert!(!result.valid);
1096        assert!(result.errors.iter().any(|e| e.contains("`schema`")));
1097    }
1098
1099    #[test]
1100    fn check_legacy_types_array_rejected() {
1101        let config = json!({"types": ["spec"], "schema": "default@1.0.0"});
1102        let result = check_config(&config);
1103        assert!(!result.valid);
1104        assert!(result.errors.iter().any(|e| e.contains("Legacy `types:")));
1105        assert_eq!(
1106            result.error_code.as_deref(),
1107            Some("LEGACY_FIELD_PRESENT"),
1108            "expected LEGACY_FIELD_PRESENT envelope for legacy `types`"
1109        );
1110    }
1111
1112    #[test]
1113    fn check_schema_wrong_shape() {
1114        let config = json!({"schema": ["default@1.0.0"]});
1115        let result = check_config(&config);
1116        assert!(!result.valid);
1117    }
1118
1119    #[test]
1120    fn check_schema_bare_name_rejected() {
1121        // Bare-name pins are rejected at load — every mem config must
1122        // declare an exact `<name>@<version>` pin so cross-mem link
1123        // matching and archive identity are unambiguous.
1124        let config = json!({"schema": "default"});
1125        let result = check_config(&config);
1126        assert!(!result.valid, "expected bare-name pin to be rejected");
1127        assert!(
1128            result.errors.iter().any(|e| e.contains("schema")),
1129            "errors: {:?}",
1130            result.errors
1131        );
1132    }
1133
1134    #[test]
1135    fn check_schema_range_syntax_rejected() {
1136        for s in [
1137            "default@^1.0.0",
1138            "default@~1.0.0",
1139            "default@latest",
1140            "default@>=1.0.0",
1141        ] {
1142            let config = json!({"schema": s});
1143            let result = check_config(&config);
1144            assert!(!result.valid, "expected '{s}' to be rejected");
1145        }
1146    }
1147
1148    #[test]
1149    fn check_schema_valid_exact_pin() {
1150        let config = json!({"schema": "default@1.0.0"});
1151        let result = check_config(&config);
1152        assert!(result.valid, "errors: {:?}", result.errors);
1153    }
1154
1155    #[test]
1156    fn schema_pin_versioned_parses() {
1157        let pin: SchemaRef = "software@1.2.3".parse().unwrap();
1158        assert_eq!(pin.name, "software");
1159        assert_eq!(pin.version, semver::Version::new(1, 2, 3));
1160        assert_eq!(pin.as_display(), "software@1.2.3");
1161    }
1162
1163    #[test]
1164    fn schema_pin_bare_name_rejected() {
1165        // Bare-name pins are rejected at parse — agents must declare the
1166        // exact version. Bogus name shapes (uppercase, slash, empty) fall
1167        // through the same gate.
1168        for bad in ["software", "Default", "foo/bar", "", "  "] {
1169            assert!(
1170                bad.parse::<SchemaRef>().is_err(),
1171                "expected '{bad}' to be rejected"
1172            );
1173        }
1174    }
1175
1176    #[test]
1177    fn schema_pin_serde_round_trip() {
1178        let versioned: SchemaRef = serde_json::from_str(r#""software@1.0.0""#).unwrap();
1179        assert_eq!(versioned.as_display(), "software@1.0.0");
1180        let as_json = serde_json::to_string(&versioned).unwrap();
1181        assert_eq!(as_json, r#""software@1.0.0""#);
1182    }
1183
1184    #[test]
1185    fn publish_rejects_missing_schema() {
1186        // Archives record a concrete schema version; a config without a
1187        // `schema` field cannot be published.
1188        let json = json!({ "version": "1.0.0" });
1189        let config = parse_mem_config(&json).unwrap();
1190        let err = published_config_from(&config, "demo").unwrap_err();
1191        assert!(matches!(err, PublishConversionError::MissingSchema));
1192    }
1193
1194    #[test]
1195    fn publish_accepts_versioned_pin() {
1196        let json = json!({
1197            "version": "1.0.0",
1198            "schema": "software@2.3.4"
1199        });
1200        let config = parse_mem_config(&json).unwrap();
1201        let published = published_config_from(&config, "demo").expect("versioned pin publishes");
1202        assert_eq!(published.name, "demo");
1203        assert_eq!(published.schema.name, "software");
1204        assert_eq!(published.schema.version, semver::Version::new(2, 3, 4));
1205    }
1206
1207    #[test]
1208    fn check_legacy_default_schema_field_is_ignored() {
1209        // `defaultSchema` was an author-only tombstone field pre-2026-04.
1210        // It's captured into `extra` and surfaces as an unknown-field
1211        // warning without invalidating an otherwise well-formed config.
1212        let config = json!({
1213            "schema": "default@1.0.0",
1214            "defaultSchema": "spec"
1215        });
1216        let result = check_config(&config);
1217        assert!(result.valid, "errors: {:?}", result.errors);
1218    }
1219
1220    #[test]
1221    fn config_preserves_unknown_fields_on_roundtrip() {
1222        // Any unknown top-level field (legacy `defaultSchema`, future
1223        // fields, typos) is captured into `extra` and re-emitted
1224        // unchanged — guarantees no silent data loss on read-modify-write.
1225        let raw = json!({
1226            "schema": "default@1.0.0",
1227            "defaultSchema": "concept"
1228        });
1229        let cfg: MemConfig = serde_json::from_value(raw).expect("config deserialized");
1230        assert!(
1231            cfg.extra.contains_key("defaultSchema"),
1232            "legacy field should be preserved in extra: {:?}",
1233            cfg.extra
1234        );
1235
1236        let reserialized = serde_json::to_value(&cfg).expect("config reserialized");
1237        assert_eq!(
1238            reserialized.get("defaultSchema").and_then(|v| v.as_str()),
1239            Some("concept"),
1240            "round-trip should preserve the legacy field"
1241        );
1242    }
1243
1244    #[test]
1245    fn check_unknown_keys_warned() {
1246        let config = json!({
1247            "schema": "default@1.0.0",
1248            "unknownKey": "value"
1249        });
1250        let result = check_config(&config);
1251        assert!(result.valid);
1252        assert!(result.warnings.iter().any(|w| w.contains("unknownKey")));
1253    }
1254
1255    /// Tombstone keys produce a hard error, not a soft "unknown key"
1256    /// warning. The unknown-key sweep must skip them so callers see
1257    /// exactly one signal per legacy key.
1258    #[test]
1259    fn legacy_tombstone_does_not_double_warn() {
1260        let config = json!({ "name": "x", "schema": "default@1.0.0" });
1261        let result = check_config(&config);
1262        assert!(!result.valid);
1263        let unknown_warning = result
1264            .warnings
1265            .iter()
1266            .any(|w| w.contains("Unknown config key 'name'"));
1267        assert!(
1268            !unknown_warning,
1269            "legacy tombstone must not also surface as unknown-key warning: {:?}",
1270            result.warnings
1271        );
1272    }
1273
1274    // --- MemConfig slimdown ---
1275
1276    #[test]
1277    fn slim_config_with_only_retained_core_fields_loads() {
1278        // The post-slimdown engine reads a minimal config carrying only
1279        // the fields it actually uses. `schema`, `vcs`, `writeGuidance`
1280        // are the intent-level retained set; serde-required collection
1281        // defaults fill the rest. The mem leaf identity is path-derived
1282        // (Goal 3 of mem-repo-restructure) so the in-config `name`
1283        // field is now a tombstone (Goal 10). Cross-mem authorization
1284        // moved to `.memstead/workspace.toml`'s `[cross_mem_links]` section.
1285        let raw = json!({
1286            "schema": "default@1.0.0",
1287            "writeGuidance": {
1288                "style": "structured",
1289                "audience": "agent"
1290            },
1291            "vcs": { "gitdir": ".git", "worktree": "." }
1292        });
1293        let check = check_config(&raw);
1294        assert!(check.valid, "errors: {:?}", check.errors);
1295        let parsed = parse_mem_config(&raw).expect("slim config parses");
1296        assert!(parsed.name.is_none());
1297        assert_eq!(parsed.write_guidance.len(), 2);
1298        assert_eq!(
1299            parsed.write_guidance.get("style").and_then(|v| v.as_str()),
1300            Some("structured")
1301        );
1302        assert!(parsed.vcs.is_some());
1303        assert!(parsed.extra.is_empty());
1304    }
1305
1306    #[test]
1307    fn legacy_projections_block_lands_in_extra_without_error() {
1308        // Pre-rewrite configs carrying `projections` / `mediums` blocks
1309        // are no longer interpreted by the engine, but round-tripping
1310        // them must not fail — the blocks fall into `MemConfig.extra`
1311        // so read-modify-write preserves authorship. check_config emits
1312        // a "Unknown config key" warning per unrecognised top-level key.
1313        let raw = json!({
1314            "schema": "default@1.0.0",
1315            "mediums": {
1316                "codebase": {
1317                    "type": "codebase",
1318                    "scope": { "tree": [{ "path": "src/", "mode": "allow" }] }
1319                }
1320            },
1321            "projections": {
1322                "p1": {
1323                    "intent": "test",
1324                    "sources": [{ "medium_ref": "codebase" }],
1325                    "destination": { "medium_ref": "graph" }
1326                }
1327            }
1328        });
1329        let check = check_config(&raw);
1330        assert!(
1331            check.valid,
1332            "legacy projections/mediums must load without errors: {:?}",
1333            check.errors
1334        );
1335        let projection_warned = check.warnings.iter().any(|w| w.contains("projections"));
1336        let mediums_warned = check.warnings.iter().any(|w| w.contains("mediums"));
1337        assert!(
1338            projection_warned && mediums_warned,
1339            "unknown-key warnings expected for projections and mediums: {:?}",
1340            check.warnings
1341        );
1342
1343        let parsed = parse_mem_config(&raw).expect("legacy config parses");
1344        assert!(
1345            parsed.extra.contains_key("projections"),
1346            "legacy `projections` must land in extra: {:?}",
1347            parsed.extra.keys().collect::<Vec<_>>()
1348        );
1349        assert!(
1350            parsed.extra.contains_key("mediums"),
1351            "legacy `mediums` must land in extra: {:?}",
1352            parsed.extra.keys().collect::<Vec<_>>()
1353        );
1354    }
1355
1356    #[test]
1357    fn write_guidance_round_trips_as_string_map() {
1358        // `writeGuidance` is an opaque `HashMap<String, Value>` now.
1359        // Round-trip a map with string / array / object / number values
1360        // to confirm every JSON shape survives verbatim — the engine
1361        // must not interpret or normalise its contents.
1362        let raw = json!({
1363            "schema": "default@1.0.0",
1364            "writeGuidance": {
1365                "style": "structured",
1366                "patterns": ["extract", "summarise"],
1367                "nested": { "depth": 2, "flag": true },
1368                "count": 42
1369            }
1370        });
1371        let parsed = parse_mem_config(&raw).expect("config parses");
1372        assert_eq!(parsed.write_guidance.len(), 4);
1373        assert_eq!(
1374            parsed.write_guidance.get("style").and_then(|v| v.as_str()),
1375            Some("structured")
1376        );
1377        let wire = serde_json::to_value(&parsed).expect("reserialize");
1378        let guidance = wire
1379            .get("writeGuidance")
1380            .and_then(|v| v.as_object())
1381            .expect("writeGuidance present in wire form");
1382        assert_eq!(guidance.len(), 4);
1383        assert_eq!(
1384            guidance.get("style").and_then(|v| v.as_str()),
1385            Some("structured")
1386        );
1387        assert_eq!(
1388            guidance
1389                .get("patterns")
1390                .and_then(|v| v.as_array())
1391                .map(|a| a.len()),
1392            Some(2)
1393        );
1394        assert_eq!(
1395            guidance
1396                .get("nested")
1397                .and_then(|v| v.get("depth"))
1398                .and_then(|v| v.as_u64()),
1399            Some(2)
1400        );
1401    }
1402
1403    #[test]
1404    fn write_guidance_empty_map_omits_from_wire() {
1405        // `skip_serializing_if = "HashMap::is_empty"` keeps an unset
1406        // writeGuidance off the wire entirely so existing minimal
1407        // configs don't gain an empty `{}` after a round-trip.
1408        let parsed: MemConfig = serde_json::from_value(minimal_valid_config()).unwrap();
1409        assert!(parsed.write_guidance.is_empty());
1410        let wire = serde_json::to_value(&parsed).unwrap();
1411        assert!(
1412            wire.get("writeGuidance").is_none(),
1413            "empty writeGuidance must be omitted from the wire: {wire}"
1414        );
1415    }
1416
1417    #[test]
1418    fn published_config_strips_extra_and_write_guidance() {
1419        // `PublishedMemConfig` uses `deny_unknown_fields` with a
1420        // fixed whitelist — the catchall `extra` and the pass-through
1421        // `writeGuidance` both fall off the projection. This guards
1422        // against a future reviewer adding either to the whitelist by
1423        // mistake.
1424        let mut extra = HashMap::new();
1425        extra.insert(
1426            "projections".to_string(),
1427            json!({ "p1": { "intent": "x" } }),
1428        );
1429        let mut guidance = HashMap::new();
1430        guidance.insert("style".to_string(), json!("structured"));
1431        let mut sync_state = BTreeMap::new();
1432        sync_state.insert(
1433            "engine-graph/source-files".to_string(),
1434            "deadbeef".to_string(),
1435        );
1436        let cfg = MemConfig {
1437            name: Some("demo".to_string()),
1438            title: None,
1439            subject: None,
1440            version: Some(semver::Version::new(0, 1, 0)),
1441            description: None,
1442            authors: None,
1443            process_mem: None,
1444            schema: Some("default@1.0.0".parse().unwrap()),
1445            write_guidance: guidance,
1446            rules: None,
1447            publish: None,
1448            language: None,
1449            read_mems: BTreeMap::new(),
1450            community: None,
1451            vcs: None,
1452            unregistered_at: None,
1453            sync_state,
1454            review_mark: None,
1455            mutation_stamp: None,
1456            extra,
1457        };
1458        let published = published_config_from(&cfg, "").expect("publish projection");
1459        let wire = serde_json::to_value(&published).expect("serialize");
1460        assert!(
1461            wire.get("projections").is_none(),
1462            "extra must not leak into published wire: {wire}"
1463        );
1464        assert!(
1465            wire.get("writeGuidance").is_none(),
1466            "writeGuidance must not leak into published wire: {wire}"
1467        );
1468        assert!(
1469            wire.get("syncState").is_none(),
1470            "syncState must not leak into published wire: {wire}"
1471        );
1472    }
1473
1474    // --- legacy tombstones — kept to lock behaviour after slimdown ---
1475
1476    // --- migration tests ---
1477
1478    // --- flatten tests ---
1479
1480    // --- shadow detection tests ---
1481
1482    // --- CRUD dry run tests ---
1483
1484    #[test]
1485    fn update_config_field_protected() {
1486        let tmp = tempfile::tempdir().unwrap();
1487        let config_path = tmp.path().join("config.json");
1488
1489        let mut config = minimal_valid_config();
1490        let err =
1491            update_config_field(&config_path, &mut config, "name", json!("new"), true).unwrap_err();
1492        assert!(err.to_string().contains("protected"));
1493    }
1494
1495    #[test]
1496    fn update_config_field_unknown() {
1497        let tmp = tempfile::tempdir().unwrap();
1498        let config_path = tmp.path().join("config.json");
1499
1500        let mut config = minimal_valid_config();
1501        let err = update_config_field(&config_path, &mut config, "banana", json!("yellow"), true)
1502            .unwrap_err();
1503        assert!(err.to_string().contains("not a recognized"));
1504    }
1505
1506    #[test]
1507    fn update_config_field_allowed() {
1508        let tmp = tempfile::tempdir().unwrap();
1509        let config_path = tmp.path().join("config.json");
1510
1511        let mut config = minimal_valid_config();
1512        let result =
1513            update_config_field(&config_path, &mut config, "language", json!("en"), true).unwrap();
1514        assert!(result.valid, "errors: {:?}", result.errors);
1515        assert_eq!(config["language"], "en");
1516    }
1517
1518    // --- is_encompassed_by tests ---
1519
1520    // --- Graph medium scope validation ---
1521
1522    // --- version parsing (semver) ---
1523
1524    #[test]
1525    fn parse_accepts_valid_semver_version() {
1526        let cfg = json!({
1527            "schema": "default@1.0.0",
1528            "version": "1.2.3-beta.4"
1529        });
1530        let parsed = parse_mem_config(&cfg).expect("valid semver should parse");
1531        let v = parsed.version.expect("version present");
1532        assert_eq!(v.major, 1);
1533        assert_eq!(v.minor, 2);
1534        assert_eq!(v.patch, 3);
1535        assert!(!v.pre.is_empty());
1536    }
1537
1538    #[test]
1539    fn parse_rejects_invalid_semver_version() {
1540        // "1.2" is not valid semver — must be MAJOR.MINOR.PATCH.
1541        let cfg = json!({
1542            "schema": "default@1.0.0",
1543            "version": "1.2"
1544        });
1545        let err = parse_mem_config(&cfg).expect_err("invalid semver must fail at parse");
1546        let msg = format!("{err}");
1547        assert!(
1548            msg.contains("version"),
1549            "error should mention version: {msg}"
1550        );
1551    }
1552
1553    #[test]
1554    fn parse_rejects_non_semver_garbage_version() {
1555        let cfg = json!({
1556            "schema": "default@1.0.0",
1557            "version": "potato"
1558        });
1559        let err = parse_mem_config(&cfg).expect_err("garbage must fail at parse");
1560        let msg = format!("{err}");
1561        assert!(
1562            msg.contains("version"),
1563            "error should mention version: {msg}"
1564        );
1565    }
1566
1567    // --- readMems: `{ source: { type, … } }` entries — no path or
1568    //     version fields (the cached archive's config is authoritative) ---
1569
1570    #[test]
1571    fn parse_accepts_read_mems_with_local_source() {
1572        let cfg = json!({
1573            "schema": "default@1.0.0",
1574            "readMems": {
1575                "internal-notes": { "source": { "type": "local" } }
1576            }
1577        });
1578        let check = check_config(&cfg);
1579        assert!(check.valid, "errors: {:?}", check.errors);
1580        let parsed = parse_mem_config(&cfg).expect("valid readMems must parse");
1581        let spec = parsed
1582            .read_mems
1583            .get("internal-notes")
1584            .expect("entry present");
1585        assert!(matches!(spec.source, ReadMemSource::Local));
1586    }
1587
1588    #[test]
1589    fn parse_accepts_read_mems_with_url_source() {
1590        let cfg = json!({
1591            "schema": "default@1.0.0",
1592            "readMems": {
1593                "aws-patterns": {
1594                    "source": {
1595                        "type": "url",
1596                        "url": "https://example.com/aws-patterns.mem"
1597                    }
1598                }
1599            }
1600        });
1601        let check = check_config(&cfg);
1602        assert!(check.valid, "errors: {:?}", check.errors);
1603        let parsed = parse_mem_config(&cfg).expect("valid readMems must parse");
1604        let spec = parsed.read_mems.get("aws-patterns").expect("entry present");
1605        match &spec.source {
1606            ReadMemSource::Url { url } => {
1607                assert_eq!(url, "https://example.com/aws-patterns.mem")
1608            }
1609            _ => panic!("expected Url source, got {:?}", spec.source),
1610        }
1611    }
1612
1613    #[test]
1614    fn parse_accepts_empty_read_mems_map() {
1615        let cfg = json!({
1616            "schema": "default@1.0.0",
1617            "readMems": {}
1618        });
1619        let parsed = parse_mem_config(&cfg).expect("empty readMems must parse");
1620        assert!(parsed.read_mems.is_empty());
1621    }
1622
1623    #[test]
1624    fn parse_accepts_omitted_read_mems() {
1625        let cfg = json!({
1626            "schema": "default@1.0.0"
1627        });
1628        let parsed = parse_mem_config(&cfg).expect("omitted readMems must parse");
1629        assert!(parsed.read_mems.is_empty());
1630    }
1631
1632    #[test]
1633    fn check_rejects_read_mem_without_source() {
1634        let cfg = json!({
1635            "schema": "default@1.0.0",
1636            "readMems": { "p": {} }
1637        });
1638        let check = check_config(&cfg);
1639        assert!(!check.valid);
1640        assert!(
1641            check.errors.iter().any(|e| e.contains("source")),
1642            "errors: {:?}",
1643            check.errors
1644        );
1645    }
1646
1647    #[test]
1648    fn check_rejects_read_mem_with_unknown_source_type() {
1649        let cfg = json!({
1650            "schema": "default@1.0.0",
1651            "readMems": {
1652                "p": { "source": { "type": "ftp", "url": "ftp://..." } }
1653            }
1654        });
1655        let check = check_config(&cfg);
1656        assert!(!check.valid);
1657        assert!(
1658            check
1659                .errors
1660                .iter()
1661                .any(|e| e.contains("unknown source type")),
1662            "errors: {:?}",
1663            check.errors
1664        );
1665    }
1666
1667    #[test]
1668    fn check_rejects_url_source_with_empty_url() {
1669        let cfg = json!({
1670            "schema": "default@1.0.0",
1671            "readMems": {
1672                "p": { "source": { "type": "url", "url": "" } }
1673            }
1674        });
1675        let check = check_config(&cfg);
1676        assert!(!check.valid);
1677        assert!(
1678            check.errors.iter().any(|e| e.contains("url source")),
1679            "errors: {:?}",
1680            check.errors
1681        );
1682    }
1683
1684    #[test]
1685    fn check_rejects_registry_source_type_reserved_for_phase_d() {
1686        let cfg = json!({
1687            "schema": "default@1.0.0",
1688            "readMems": {
1689                "p": { "source": { "type": "registry" } }
1690            }
1691        });
1692        let check = check_config(&cfg);
1693        // `registry` is a reserved future source type but is not yet
1694        // accepted by the schema — validation must reject it until the
1695        // registry ships.
1696        assert!(!check.valid);
1697        assert!(
1698            check
1699                .errors
1700                .iter()
1701                .any(|e| e.contains("unknown source type")),
1702            "errors: {:?}",
1703            check.errors
1704        );
1705    }
1706
1707    /// Guards the `BTreeMap` choice: serialized read_mems must come out
1708    /// in key-sorted order regardless of insertion order, so config files
1709    /// on disk and log output are reproducible. A future "optimisation"
1710    /// that reintroduces `HashMap` would break this.
1711    #[test]
1712    fn read_mems_serialization_order_is_key_sorted() {
1713        let cfg = json!({
1714            "schema": "default@1.0.0",
1715            "readMems": {
1716                "zebra": { "source": { "type": "local" } },
1717                "alpha": { "source": { "type": "local" } },
1718                "mango": { "source": { "type": "local" } }
1719            }
1720        });
1721        let parsed = parse_mem_config(&cfg).expect("valid config must parse");
1722        let reserialized = serde_json::to_string(&parsed).expect("serialization must succeed");
1723        let alpha = reserialized.find("alpha").expect("alpha present");
1724        let mango = reserialized.find("mango").expect("mango present");
1725        let zebra = reserialized.find("zebra").expect("zebra present");
1726        assert!(
1727            alpha < mango && mango < zebra,
1728            "expected alpha < mango < zebra, got: {reserialized}"
1729        );
1730    }
1731
1732    // ----- vcs field -----
1733
1734    #[test]
1735    fn vcs_config_round_trips_through_serde_with_both_fields() {
1736        let cfg = json!({
1737            "schema": "default@1.0.0",
1738            "vcs": { "gitdir": "../.git", "worktree": ".." }
1739        });
1740        let parsed = parse_mem_config(&cfg).expect("valid config must parse");
1741        let vcs = parsed.vcs.as_ref().expect("vcs must be Some");
1742        assert_eq!(vcs.gitdir, "../.git");
1743        assert_eq!(vcs.worktree, "..");
1744
1745        // Round-trip.
1746        let reserialized = serde_json::to_value(&parsed).unwrap();
1747        let round = parse_mem_config(&reserialized).expect("round-trip parse");
1748        assert_eq!(round.vcs.as_ref().unwrap().gitdir, "../.git");
1749        assert_eq!(round.vcs.as_ref().unwrap().worktree, "..");
1750    }
1751
1752    #[test]
1753    fn vcs_config_worktree_defaults_to_dot_when_omitted() {
1754        let cfg = json!({
1755            "schema": "default@1.0.0",
1756            "vcs": { "gitdir": ".git" }
1757        });
1758        let parsed = parse_mem_config(&cfg).expect("valid config must parse");
1759        let vcs = parsed.vcs.as_ref().expect("vcs must be Some");
1760        assert_eq!(vcs.gitdir, ".git");
1761        assert_eq!(vcs.worktree, ".", "worktree must default to \".\"");
1762    }
1763
1764    #[test]
1765    fn vcs_config_absent_is_none() {
1766        let cfg = json!({ "schema": "default@1.0.0"  });
1767        let parsed = parse_mem_config(&cfg).expect("valid config must parse");
1768        assert!(parsed.vcs.is_none(), "missing vcs must deserialize to None");
1769    }
1770
1771    #[test]
1772    fn vcs_field_tolerates_legacy_string_value() {
1773        // Legacy macOS-app sentinel. The tolerant deserializer must keep
1774        // the config loadable (returning None) without touching the
1775        // user's file by hand.
1776        let cfg = json!({
1777            "schema": "default@1.0.0",
1778            "vcs": "system"
1779        });
1780        let parsed = parse_mem_config(&cfg).expect("legacy vcs string must parse");
1781        assert!(
1782            parsed.vcs.is_none(),
1783            "legacy string must deserialize to None"
1784        );
1785    }
1786
1787    #[test]
1788    fn published_config_strips_vcs() {
1789        // `published_config_from` must drop the `vcs` block — VCS layout
1790        // is workspace-local mechanics, never part of the published
1791        // mem's identity. This is guaranteed by the whitelist
1792        // projection: `PublishedMemConfig` has no `vcs` field, so a
1793        // MemConfig carrying `vcs: Some(...)` projects to a
1794        // PublishedMemConfig with no `vcs` on the wire.
1795        let mut cfg = MemConfig {
1796            name: Some("demo".to_string()),
1797            title: None,
1798            subject: None,
1799            version: Some(semver::Version::new(0, 1, 0)),
1800            description: None,
1801            authors: None,
1802            process_mem: None,
1803            schema: Some("default@1.0.0".parse().unwrap()),
1804            write_guidance: HashMap::new(),
1805            rules: None,
1806            publish: None,
1807            language: None,
1808            read_mems: BTreeMap::new(),
1809            community: None,
1810            vcs: None,
1811            unregistered_at: None,
1812            sync_state: BTreeMap::new(),
1813            review_mark: None,
1814            mutation_stamp: None,
1815            extra: HashMap::new(),
1816        };
1817        cfg.vcs = Some(VcsConfig {
1818            gitdir: ".git".to_string(),
1819            worktree: ".".to_string(),
1820        });
1821        let published = published_config_from(&cfg, "").expect("valid projection");
1822        let wire = serde_json::to_value(&published).expect("serialize");
1823        assert!(
1824            wire.get("vcs").is_none(),
1825            "published wire form must not carry vcs: got {wire}"
1826        );
1827    }
1828
1829    // ----- belongsTo legacy tombstone -----
1830
1831    /// `belongsTo` is now a tombstone — cross-mem authorization
1832    /// migrated to the workspace-level `[cross_mem_links]` section in
1833    /// `.memstead/workspace.toml`. A per-mem config blob carrying `belongsTo` is
1834    /// rejected with `LEGACY_FIELD_PRESENT`.
1835    #[test]
1836    fn belongs_to_field_is_legacy_tombstone() {
1837        let cfg = json!({
1838            "schema": "default@1.0.0",
1839            "belongsTo": ["main"]
1840        });
1841        let result = check_config(&cfg);
1842        assert!(!result.valid, "belongsTo presence must fail validation");
1843        assert_eq!(result.error_code.as_deref(), Some("LEGACY_FIELD_PRESENT"));
1844        assert!(
1845            result
1846                .errors
1847                .iter()
1848                .any(|e| e.contains("belongsTo") && e.contains("cross_mem_links")),
1849            "tombstone error must name the field and the replacement section: {:?}",
1850            result.errors
1851        );
1852    }
1853}