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 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/// Member path of the optional sealed check records inside a sealed
63/// archive: per entity the latest check record per kind, so an archive
64/// mount answers check state from the archive itself. Additive: a mem
65/// with no check record omits it, an engine that does not recognise it
66/// tolerates it as an unknown meta member, and the published format
67/// number is unchanged. Recognised as a strict member on engines that
68/// know it (a malformed member is a typed validation failure), the way
69/// the anchors member is.
70pub const ARCHIVE_CHECKS_PATH: &str = ".memstead/checks.json";
71/// File extension (without dot) of a sealed archive — the sole spelling.
72/// The one deliberately-distinct token in a project that is otherwise
73/// "memstead" everywhere — short, and derived from the project name.
74pub const ARCHIVE_EXTENSION: &str = "mem";
75
76// ---------------------------------------------------------------------------
77// Error types
78// ---------------------------------------------------------------------------
79
80#[derive(Debug, thiserror::Error)]
81pub enum ConfigError {
82 #[error("config file not found: {0}")]
83 NotFound(String),
84 #[error("invalid JSON in config file: {0}")]
85 InvalidJson(String),
86 #[error("config validation failed:\n{}", .0.iter().map(|e| format!(" - {e}")).collect::<Vec<_>>().join("\n"))]
87 ValidationFailed(Vec<String>),
88 #[error("{0}")]
89 Other(String),
90 #[error("io error: {0}")]
91 Io(#[from] std::io::Error),
92 #[error("json error: {0}")]
93 Json(#[from] serde_json::Error),
94}
95
96// ---------------------------------------------------------------------------
97// Config check result
98// ---------------------------------------------------------------------------
99
100/// Result of config validation — errors are fatal, warnings are informational.
101#[derive(Debug, Clone)]
102pub struct ConfigCheckResult {
103 pub valid: bool,
104 pub errors: Vec<String>,
105 pub warnings: Vec<String>,
106 /// Stable `UPPER_SNAKE_CASE` envelope code when the validator
107 /// detects a categorical failure that callers should branch on.
108 /// Currently set to `"LEGACY_FIELD_PRESENT"` when any entry in
109 /// `LEGACY_TOMBSTONE_KEYS` is present.
110 pub error_code: Option<String>,
111}
112
113// ---------------------------------------------------------------------------
114// Mem config types (deserialized from .memstead/config.json)
115// ---------------------------------------------------------------------------
116
117/// Role-based publish config.
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct RoleConfig {
120 pub include: Vec<String>,
121 #[serde(skip_serializing_if = "Option::is_none")]
122 pub exclude: Option<Vec<String>>,
123}
124
125/// Publish config.
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct PublishConfig {
128 pub roles: HashMap<String, RoleConfig>,
129}
130
131/// Community detection override.
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct CommunityOverride {
134 #[serde(skip_serializing_if = "Option::is_none")]
135 pub resolution: Option<f64>,
136 #[serde(skip_serializing_if = "Option::is_none")]
137 pub seed: Option<u32>,
138}
139
140/// One entry in the legacy `MemConfig.read_mems` map — a read-only
141/// sealed mem archive that a pre-2026-08 install attached to a host
142/// mem. Retained only for the one-way boot migration into the mount
143/// roster; no live path writes one.
144///
145/// The engine resolves each entry to a cache file: when `cache_key` is
146/// present, `<mem_cache_dir>/<name>-<cache_key>.mem` (content-addressed
147/// — see [`ReadMemSpec::cache_key`]); otherwise the legacy
148/// `<mem_cache_dir>/<name>.mem`.
149///
150/// Kept as a struct (rather than collapsing to a bare `ReadMemSource`)
151/// so forward-compatible fields can be added without another schema break.
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct ReadMemSpec {
154 pub source: ReadMemSource,
155 /// Content-address of the installed archive — a short hex digest of
156 /// the validator's canonical bytes. The install path writes the cache
157 /// file at `<cache>/<name>-<cache_key>.mem`, so two distinct archives
158 /// sharing an internal mem name land in distinct files (no collision)
159 /// and re-installing identical bytes resolves to the same file (dedup).
160 /// `None` for legacy registrations written before content-addressing;
161 /// the loader then falls back to the bare `<name>.mem` path.
162 #[serde(default, skip_serializing_if = "Option::is_none", rename = "cacheKey")]
163 pub cache_key: Option<String>,
164}
165
166/// How the app reconstitutes a read mem's cache file when missing.
167///
168/// The engine itself never fetches; `source` is metadata consumed by the
169/// app's installer. A `Registry` variant with scope/name identifiers
170/// will be added once registry-sourced read mems are designed.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172#[serde(tag = "type", rename_all = "camelCase")]
173pub enum ReadMemSource {
174 /// User dropped an archive file onto the app. App cannot auto-reinstall —
175 /// it prompts the user to drop the original file again.
176 Local,
177 /// Fetched from an HTTPS URL (GitHub Releases, shared drive, any static
178 /// host). Engine-side no-op; the app's installer re-fetches on attach.
179 Url { url: String },
180 // `Registry` variant reserved for registry-sourced read mems.
181 // The exact shape (fields, id format like `@scope/name`) is designed
182 // then — declaring it up front without semantics would be
183 // speculative, and pre-1.0 adding a variant later is not a breaking
184 // change for anyone.
185}
186
187/// Reference to a schema by exact name and version — `name@x.y.z`.
188///
189/// Serializes/deserializes as a single string so mem configs read
190/// `{ "schema": "default@1.0.0" }` on disk. Range syntax (`^`, `~`,
191/// `latest`) is rejected — schema pinning is strict and explicit.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct SchemaRef {
194 pub name: String,
195 pub version: semver::Version,
196}
197
198impl SchemaRef {
199 pub fn new(name: impl Into<String>, version: semver::Version) -> Self {
200 Self {
201 name: name.into(),
202 version,
203 }
204 }
205
206 pub fn as_display(&self) -> String {
207 format!("{}@{}", self.name, self.version)
208 }
209}
210
211impl std::fmt::Display for SchemaRef {
212 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213 write!(f, "{}@{}", self.name, self.version)
214 }
215}
216
217impl std::str::FromStr for SchemaRef {
218 type Err = String;
219
220 fn from_str(s: &str) -> Result<Self, Self::Err> {
221 let trimmed = s.trim();
222 if trimmed.is_empty() {
223 return Err("schema reference must not be empty (expected \"name@x.y.z\")".into());
224 }
225 let (name, version_str) = trimmed.split_once('@').ok_or_else(|| {
226 format!(
227 "schema reference '{trimmed}' must include an exact version — expected \"name@x.y.z\""
228 )
229 })?;
230 if name.is_empty() {
231 return Err("schema reference name must not be empty".into());
232 }
233 if version_str == "latest" {
234 return Err(format!(
235 "schema reference '{trimmed}' uses 'latest' — exact semver versions only"
236 ));
237 }
238 if version_str.starts_with(['^', '~', '>', '<', '=', '*']) {
239 return Err(format!(
240 "schema reference '{trimmed}' uses range syntax — exact semver only (e.g. 'default@1.0.0')"
241 ));
242 }
243 let version = semver::Version::parse(version_str).map_err(|e| {
244 format!("schema reference '{trimmed}' has invalid semver version '{version_str}': {e}")
245 })?;
246 Ok(Self {
247 name: name.to_string(),
248 version,
249 })
250 }
251}
252
253impl Serialize for SchemaRef {
254 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
255 serializer.serialize_str(&self.as_display())
256 }
257}
258
259impl<'de> Deserialize<'de> for SchemaRef {
260 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
261 let s = String::deserialize(deserializer)?;
262 s.parse::<SchemaRef>().map_err(serde::de::Error::custom)
263 }
264}
265
266// `MemSchemaPin` (the two-variant pin with a name-only fallback) was
267// retired here. Mem configs now declare a strict `<name>@<version>`
268// pin parsed directly through [`SchemaRef`]; bare-name pins are
269// rejected at config load.
270
271/// VCS layout for a writable mem — optional `{ gitdir, worktree }` pair
272/// in `.memstead/config.json`. When absent, the engine resolves the default:
273/// `.git/` at mem root with `.` as worktree.
274///
275/// Paths are relative to mem root and interpreted by `memstead-git-branch` —
276/// this crate just carries them through serde. Masterplan §3.4 is
277/// explicit that the primitive is a pair of paths; the two canonical
278/// idioms (isolated `{ ".git", "." }` and shared `{ "../.git", ".." }`)
279/// are idioms, not enum variants.
280#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
281#[serde(rename_all = "camelCase")]
282pub struct VcsConfig {
283 /// Path to the gitdir relative to mem root. Required when the
284 /// `vcs` block is present.
285 pub gitdir: String,
286 /// Path to the worktree relative to mem root. Optional within the
287 /// `vcs` block — defaults to `"."` (mem root) when omitted.
288 #[serde(default = "vcs_worktree_default")]
289 pub worktree: String,
290}
291
292fn vcs_worktree_default() -> String {
293 ".".to_string()
294}
295
296/// Tolerant deserializer for the `vcs` field: accepts the object form
297/// (`{ gitdir, worktree? }`) and returns `None` for any non-object value
298/// (string, number, boolean, null). A missing field is also `None`.
299///
300/// Motivation: an older macOS Mem-mode UI wrote `"vcs": "system"`
301/// (and similar sentinel strings) into `.memstead/config.json` files that
302/// now must continue to load without editing those files by hand.
303/// Strict validation of the object form — unknown keys, missing
304/// `gitdir`, etc. — still surfaces as a hard serde error.
305fn deserialize_vcs_tolerant<'de, D>(deserializer: D) -> Result<Option<VcsConfig>, D::Error>
306where
307 D: serde::Deserializer<'de>,
308{
309 let value = Option::<Value>::deserialize(deserializer)?;
310 match value {
311 None | Some(Value::Null) => Ok(None),
312 Some(Value::Object(_)) => {
313 let v = value.unwrap();
314 Ok(Some(
315 serde_json::from_value(v).map_err(serde::de::Error::custom)?,
316 ))
317 }
318 Some(_) => Ok(None),
319 }
320}
321
322/// The subject block of a mem — what it covers, by what method, and
323/// above all what was considered and deliberately left out. Exactly
324/// three members, by design: every additional slot invites the
325/// working-notes leakage this block exists to avoid, and three is what
326/// a recipient can actually read before deciding whether to trust the
327/// mem. Published verbatim in [`PublishedMemConfig`]; the engine never
328/// parses, links, or validates the prose.
329#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
330#[serde(deny_unknown_fields, rename_all = "camelCase")]
331pub struct MemSubject {
332 /// What this mem covers.
333 pub scope: String,
334 /// How its content was arrived at.
335 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub method: Option<String>,
337 /// What was considered and deliberately left out — prose
338 /// statements, order preserved. May be empty.
339 #[serde(default)]
340 pub exclusions: Vec<String>,
341}
342
343/// Engine-owned version stamp of the last successful mutation on a
344/// mem — see [`MemConfig::mutation_stamp`]. Both values are recorded
345/// at mutation time: `engine_version` is the engine crate version the
346/// acting binary was built from, `schema` the resolved
347/// `<name>@<version>` the mutation validated against (the resolved
348/// schema, not merely the pin — mid-migration mems stamp the target
349/// they validated against).
350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
351#[serde(deny_unknown_fields, rename_all = "camelCase")]
352pub struct MutationStamp {
353 /// Full build version of the binary that performed the last
354 /// mutation — `memstead-base`'s `build_info::full_version()`:
355 /// the crate semver, plus `+g<sha>[-dirty]` build metadata when
356 /// built inside a git checkout, so dev builds between releases
357 /// stamp distinguishably. Older stamps carry the plain semver
358 /// and compare against the full current value — firing the skew
359 /// hint on the first post-upgrade boot is desired, no migration.
360 pub engine_version: String,
361 /// Resolved schema `<name>@<version>` the last mutation validated
362 /// against.
363 pub schema: String,
364}
365
366/// Where a forked mem came from, see [`MemConfig::forked_from`]. The
367/// ancestor never moves: `sha` is the source branch's commit the fork's
368/// branch was created at, `mem` the source mem's name, and `remote` the
369/// mem-repo remote the source was fetched from when the fork was not
370/// local (`None` for a fork of a mounted mem). `base` is the fork's own
371/// first commit: the one the fork makes on its branch right above the
372/// ancestor to carry its own name in its sidecars and self-links. A
373/// comparison between the fork and its source stands on `base`, never
374/// on `sha`, because the retarget is the fork's identity and not a
375/// change to review; [`Self::base_sha`] reads it with the fallback for
376/// a fork recorded before the field existed. Author-only: the
377/// published archive config never carries it, so an archive can never
378/// claim a lineage.
379#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
380#[serde(deny_unknown_fields, rename_all = "camelCase")]
381pub struct ForkedFrom {
382 /// The source mem's name.
383 pub mem: String,
384 /// The 40-hex commit sha on the source branch the fork started at.
385 pub sha: String,
386 /// The mem-repo remote the source branch and config were fetched
387 /// from; absent for a local fork.
388 #[serde(default, skip_serializing_if = "Option::is_none")]
389 pub remote: Option<String>,
390 /// The 40-hex sha of the fork's retarget commit, the first commit
391 /// on the fork's branch above `sha`. Absent on a fork made before
392 /// the fork commit existed; such a fork is read as based on `sha`.
393 #[serde(default, skip_serializing_if = "Option::is_none")]
394 pub base: Option<String>,
395}
396
397impl ForkedFrom {
398 /// The commit a comparison against the source starts from: the
399 /// fork's retarget commit when one was recorded, the ancestor
400 /// otherwise (a fork made before the fork commit existed carries
401 /// no `base` and its branch starts at the ancestor itself).
402 pub fn base_sha(&self) -> &str {
403 self.base.as_deref().unwrap_or(&self.sha)
404 }
405}
406
407/// Full mem configuration loaded from .memstead/config.json.
408#[derive(Debug, Clone, Serialize, Deserialize)]
409#[serde(rename_all = "camelCase")]
410pub struct MemConfig {
411 /// Workspace mem-config format version. Absent means version 1 — the
412 /// healthy common case; real mems carry no key — and an unknown value
413 /// REFUSES at parse, matching every sibling store (the binding record,
414 /// `WorkspaceConfig`, the anchors sidecar). Until 2026-08-28 this field
415 /// was not modeled at all, so serde silently dropped whatever value a
416 /// config carried and `"format": 99` verified clean. Distinct from
417 /// [`PUBLISHED_MEM_FORMAT`], the sealed-archive config's own version
418 /// line with its own gate. Read through [`Self::format_version`].
419 #[serde(
420 default,
421 deserialize_with = "de_mem_config_format",
422 skip_serializing_if = "Option::is_none"
423 )]
424 pub format: Option<u32>,
425
426 /// Optional mem name. The leaf folder name under
427 /// `__MEMSTEAD:mems/` (and the disk basename on the legacy disk
428 /// path) is authoritative; engine-written configs omit this
429 /// field. Tolerated on read for pre-cutover configs and for the
430 /// [`PublishedMemConfig`] conversion path that still requires
431 /// an explicit identity (the caller passes the name in when
432 /// projecting).
433 #[serde(default, skip_serializing_if = "Option::is_none")]
434 pub name: Option<String>,
435
436 /// Semver version of the mem content. Read at mem-archive export
437 /// time so the engine always knows the current version without manual
438 /// tracking. Parsed at config load — invalid version strings fail fast
439 /// with a source-attributed serde error rather than slipping through to
440 /// export (where the issue only surfaces when a downstream loader tries
441 /// to resolve a `semver::VersionReq` against the mem).
442 #[serde(skip_serializing_if = "Option::is_none")]
443 pub version: Option<semver::Version>,
444
445 /// One-line description of the mem, surfaced in mem-archive metadata
446 /// and UI.
447 #[serde(skip_serializing_if = "Option::is_none")]
448 pub description: Option<String>,
449
450 /// Human-readable display title. Display text, NOT identity: no
451 /// slug grammar, no uniqueness rule — the mem name stays the sole
452 /// handle everywhere (paths, grants, namespace patterns, cross-mem
453 /// references, archive filenames). Surfaces that print a mem
454 /// prefer this and fall back to the name. Published in
455 /// [`PublishedMemConfig`].
456 #[serde(default, skip_serializing_if = "Option::is_none")]
457 pub title: Option<String>,
458
459 /// The mem's subject — scope, method, deliberate exclusions.
460 /// Published verbatim; clears as a unit.
461 #[serde(default, skip_serializing_if = "Option::is_none")]
462 pub subject: Option<MemSubject>,
463
464 /// Optional author attribution, surfaced in mem-archive metadata.
465 #[serde(skip_serializing_if = "Option::is_none")]
466 pub authors: Option<Vec<String>>,
467
468 /// Declared process-mem pairing: the name
469 /// of the mem holding this mem's process tier (verification
470 /// targets, findings, inquiry entries). Declaration wins over the
471 /// binding-name derivation the brief renderer and the
472 /// open-questions health axis otherwise use; a declaration naming
473 /// an unmounted mem surfaces as a typed health finding, never a
474 /// silent fallback. Absent means "derive by convention" — the
475 /// pre-declaration behaviour, unchanged.
476 #[serde(default, skip_serializing_if = "Option::is_none")]
477 pub process_mem: Option<String>,
478
479 /// Schema this mem is pinned to. Exact `<name>@<version>` pin
480 /// only — bare-name forms are rejected at config load. Exactly one
481 /// schema per mem. The `Option` keeps serde tolerant so a missing
482 /// key surfaces as a structured error from `check_config` rather
483 /// than a deserialize panic; a `None` value is a validation error.
484 #[serde(skip_serializing_if = "Option::is_none")]
485 pub schema: Option<SchemaRef>,
486
487 /// Opaque string-map passed through by the engine. Agents and
488 /// plugin prompt renderers are free to invent their own keys; the
489 /// engine does not parse, validate, or interpret any value inside.
490 /// Stripped from `PublishedMemConfig` — guidance is workspace-
491 /// local authorship metadata, not part of the published identity.
492 ///
493 /// Pre-2026-04-24 this field was `Option<Value>`; the workspace
494 /// rewrite normalised it to a map so the shape on
495 /// the wire is stable and the engine's pass-through guarantee is
496 /// type-checked.
497 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
498 pub write_guidance: HashMap<String, Value>,
499 #[serde(skip_serializing_if = "Option::is_none")]
500 pub rules: Option<Value>,
501
502 #[serde(skip_serializing_if = "Option::is_none")]
503 pub publish: Option<PublishConfig>,
504 #[serde(skip_serializing_if = "Option::is_none")]
505 pub language: Option<String>,
506 /// **Legacy since 2026-08.** A read-only sealed-archive mem attaches
507 /// to the WORKSPACE mount roster (`.memstead/state/mounts.json`), not
508 /// to a host mem's config. Nothing writes this field any more; it
509 /// survives on the struct so the one-way boot migration
510 /// (`migrate_legacy_read_mems`) can recognise a pre-cutover
511 /// registration, turn it into a mount, and strip the key. An empty or
512 /// omitted map is the healthy state.
513 ///
514 /// Key is the mem name (matching the archive's config name).
515 ///
516 /// `BTreeMap` (not `HashMap`) so iteration and serialization order
517 /// are stable — reproducible log output and diff-friendly config on
518 /// disk. Explicit `rename = "readMems"` documents the on-disk name
519 /// at the field (the struct-level `rename_all = "camelCase"` already
520 /// handles it, but explicit rename is greppable from either side).
521 #[serde(
522 rename = "readMems",
523 default,
524 skip_serializing_if = "BTreeMap::is_empty"
525 )]
526 pub read_mems: BTreeMap<String, ReadMemSpec>,
527 #[serde(skip_serializing_if = "Option::is_none")]
528 pub community: Option<CommunityOverride>,
529
530 /// Optional VCS layout override. When absent, `memstead-git-branch` resolves
531 /// the default at init time: `.git/` at mem root with `.` as
532 /// worktree. When present, `gitdir` and `worktree` are paths
533 /// relative to the mem root. Stripped from `PublishedMemConfig`
534 /// — VCS layout is workspace-local mechanics, not part of the
535 /// published mem's identity.
536 ///
537 /// Deserialization is tolerant of legacy non-object values (e.g.
538 /// `"vcs": "system"` — the sentinel an older macOS Mem-mode
539 /// UI wrote): any non-object form deserializes to `None` and falls
540 /// back to the default-resolution path. The object form is validated
541 /// strictly.
542 #[serde(
543 default,
544 deserialize_with = "deserialize_vcs_tolerant",
545 skip_serializing_if = "Option::is_none"
546 )]
547 pub vcs: Option<VcsConfig>,
548
549 /// Tombstone marker written by `memstead mem unregister`. ISO-8601
550 /// UTC timestamp (`YYYY-MM-DDTHH:MM:SSZ`) recorded at the moment
551 /// the mem was unregistered while its storage was preserved.
552 /// When `memstead mem init <same-name>`
553 /// probes the storage and finds an `unregistered_at` value, it
554 /// treats the residue as deliberate operator state and defaults
555 /// to the `Reattach` recovery action (adopting the preserved
556 /// entities and clearing the tombstone). Absence (`None`) on
557 /// otherwise-present residue triggers `MEM_STORAGE_RESIDUE_DETECTED`
558 /// unless the caller passes an explicit `recovery` flag. Stripped
559 /// from `PublishedMemConfig` — tombstones are workspace-local
560 /// lifecycle state, not part of the published mem's identity.
561 #[serde(default, skip_serializing_if = "Option::is_none")]
562 pub unregistered_at: Option<String>,
563
564 /// Set by a mem rename while it runs: the name the mem is being
565 /// renamed from. A rename that was cut off after its storage moved is
566 /// resumed only on a mem that carries its own old name here, so a
567 /// rename onto an unrelated live mem is never mistaken for one. The
568 /// rename clears it when it completes. Workspace-local lifecycle
569 /// state, like the tombstone above.
570 #[serde(default, skip_serializing_if = "Option::is_none")]
571 pub renaming_from: Option<String>,
572
573 /// Per-source "last successfully synced source state", written by
574 /// the ingest layer and surfaced verbatim on the workspace dump.
575 /// The engine never parses, validates, or interprets a value:
576 /// each token is opaque, its meaning owned by the medium-type
577 /// layer that produced it (git → commit id, graph → snapshot
578 /// token, filesystem → a small stat digest the plugin
579 /// JSON-stringifies). The key is likewise opaque — the binding
580 /// layer keys per `(binding, facet)` (conventionally
581 /// `"<binding-id>/<facet>#synced"`), but the engine treats it as
582 /// an arbitrary string. This is the durable, shared baseline against which a
583 /// fresh ingest iteration diffs "what changed since last time";
584 /// it survives a skill-cache wipe and a machine change because it
585 /// lives in engine-held mem config, not ephemeral plugin cache.
586 ///
587 /// Stripped from `PublishedMemConfig` — sync state is
588 /// workspace-local ingest bookkeeping, not part of a published
589 /// mem's identity. `BTreeMap` (not `HashMap`) for stable
590 /// serialization order: diff-friendly config on disk and
591 /// reproducible dump output.
592 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
593 pub sync_state: BTreeMap<String, String>,
594
595 /// The mem's review mark: the last human-approved state, in the
596 /// backend-opaque cursor vocabulary `changes_since` consumes
597 /// (git-branch: commit SHA; folder: changelog RFC3339 timestamp).
598 /// Absent is a first-class state — a mem with no mark is ordinary,
599 /// never an error, and marks never gate writes. One mark per mem;
600 /// wire key `reviewMark` (camelCase per the config's convention).
601 ///
602 /// Stripped from `PublishedMemConfig` (allowlist projection) —
603 /// review state is workspace-collaboration bookkeeping, not part
604 /// of a published mem's identity.
605 #[serde(
606 default,
607 rename = "reviewMark",
608 skip_serializing_if = "Option::is_none"
609 )]
610 pub review_mark: Option<String>,
611
612 /// Engine-owned version stamp of the last successful mutation:
613 /// which engine version and which resolved schema performed it.
614 /// Written by the engine after a mutation and only when the values
615 /// changed (a binary upgrade or a schema repin), never by authors,
616 /// never on read-only loads — a boot writes nothing. Boot compares
617 /// the running binary against the stamp and surfaces a divergence
618 /// as the warn-tier `ENGINE_VERSION_SKEW` hint; absence of a stamp
619 /// is a first-class state (pre-stamp mems), never skew. The stamp
620 /// is the substrate any future migration machinery would consult —
621 /// deliberately built without that machinery.
622 ///
623 /// Stripped from `PublishedMemConfig` (allowlist projection) —
624 /// workspace-local engine bookkeeping, not published identity.
625 /// Wire key `mutationStamp` (camelCase per the config convention).
626 #[serde(
627 default,
628 rename = "mutationStamp",
629 skip_serializing_if = "Option::is_none"
630 )]
631 pub mutation_stamp: Option<MutationStamp>,
632
633 /// The recorded ancestor of a mem created by `memstead mem fork`:
634 /// the source mem, the commit its branch started at, the remote
635 /// when one was used, and the fork's own first commit (`base`).
636 /// Written once at fork time and never moved (the review mark is
637 /// the moving cursor; the ancestor is not).
638 /// Absent on every mem that was not forked. Wire key `forkedFrom`.
639 ///
640 /// Stripped from `PublishedMemConfig` (allowlist projection), whose
641 /// deny-unknown-fields shape refuses the key outright. An engine
642 /// that predates the field reads the config unchanged: the key
643 /// lands in the flattened `extra` map and is written back verbatim.
644 #[serde(
645 default,
646 rename = "forkedFrom",
647 skip_serializing_if = "Option::is_none"
648 )]
649 pub forked_from: Option<ForkedFrom>,
650
651 /// Extra fields not in the known set (captured for round-tripping).
652 ///
653 /// Historical tombstones:
654 /// - `defaultSchema` (pre-2026-04): legacy per-mem default type.
655 /// Per-entity `type:` frontmatter is authoritative now.
656 /// - `types: [...]` (pre-schema-artifact, 2026-04): replaced by
657 /// `schema: "<name>@<version>"`. Legacy entries are hard-rejected
658 /// by `check_config`.
659 #[serde(flatten)]
660 pub extra: HashMap<String, Value>,
661}
662
663// ---------------------------------------------------------------------------
664// Published (archive) mem config
665// ---------------------------------------------------------------------------
666
667/// Strict-ingress shape of a mem config. This is the **only** metadata
668/// form that enters a `.mem` archive. `MemConfig` carries author-only
669/// fields (writeGuidance, rules, publish, readMems, language,
670/// community, defaultSchema, vcs, plus any key captured in
671/// `extra`) that never belong in a published archive;
672/// `published_config_from` projects `MemConfig` →
673/// `PublishedMemConfig`, dropping everything outside the whitelist.
674///
675/// `deny_unknown_fields` + no `serde(flatten)` on purpose: the validator
676/// re-parses this shape with the same struct as defense-in-depth, so any
677/// legacy author key smuggled into an archive surfaces as a rejection
678/// instead of a silently-tolerated payload.
679#[derive(Debug, Clone, Serialize, Deserialize)]
680#[serde(deny_unknown_fields, rename_all = "camelCase")]
681pub struct PublishedMemConfig {
682 pub format: u32,
683 pub name: String,
684 pub version: semver::Version,
685 #[serde(skip_serializing_if = "Option::is_none")]
686 pub description: Option<String>,
687 /// Human-readable display title (format ≥ 4). Display text, not
688 /// identity — a format-3 archive simply has none.
689 #[serde(default, skip_serializing_if = "Option::is_none")]
690 pub title: Option<String>,
691 /// The mem's subject block (format ≥ 4), published verbatim —
692 /// exclusions included and in order.
693 #[serde(default, skip_serializing_if = "Option::is_none")]
694 pub subject: Option<MemSubject>,
695 #[serde(skip_serializing_if = "Option::is_none")]
696 pub authors: Option<Vec<String>>,
697 pub schema: SchemaRef,
698}
699
700/// Archive format integer written to the archive config's `format`
701/// field. Bumped to `4` for the mem title + subject block (both
702/// optional — a format-3 archive simply has neither). Readers accept
703/// `3` and `4` via [`published_format_accepted`]; `format: 1` (V1) and
704/// `format: 2` (V2, top-level `schema/` tree) archives keep refusing
705/// cleanly.
706pub const PUBLISHED_MEM_FORMAT: u32 = 4;
707
708/// The workspace mem config's format version (`<mem>/.memstead/config.json`).
709/// One accepted value; an absent key means exactly this version, and any
710/// other value refuses at parse ([`de_mem_config_format`]).
711pub const MEM_CONFIG_FORMAT: u32 = 1;
712
713/// Deserialize the workspace mem config's `format` key: absent stays `None`
714/// (meaning [`MEM_CONFIG_FORMAT`]), the current version parses, anything
715/// else refuses loudly — a config a future engine may mean differently must
716/// never be silently read as today's shape.
717fn de_mem_config_format<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
718where
719 D: serde::Deserializer<'de>,
720{
721 let value = Option::<u32>::deserialize(deserializer)?;
722 match value {
723 None | Some(MEM_CONFIG_FORMAT) => Ok(value),
724 // A mounted read-mem's cached config is the published shape and
725 // parses through this same struct, so the published versions this
726 // engine reads are accepted here too (their own gate ran at
727 // archive validation).
728 Some(found) if published_format_accepted(found) => Ok(value),
729 Some(found) => Err(serde::de::Error::custom(format!(
730 "unsupported mem config format {found}: this engine reads format \
731 {MEM_CONFIG_FORMAT} (an absent key means the same); a higher value \
732 was written by a newer engine — upgrade before loading this mem"
733 ))),
734 }
735}
736
737impl MemConfig {
738 /// The effective config format version: the declared value, or
739 /// [`MEM_CONFIG_FORMAT`] when the key is absent.
740 pub fn format_version(&self) -> u32 {
741 self.format.unwrap_or(MEM_CONFIG_FORMAT)
742 }
743}
744
745/// Every archive format a current reader accepts, newest first: the
746/// current integer plus format 3 (the pre-title/subject shape — the two
747/// mems already published on the live registry stay installable without
748/// a re-publish). `format: 1` (V1) and `format: 2` (V2, top-level
749/// `schema/` tree) keep refusing cleanly.
750///
751/// A list rather than a predicate body because the accepted set is a
752/// fact worth reading directly, not only a branch to evaluate.
753pub const PUBLISHED_MEM_FORMATS_ACCEPTED: &[u32] = &[PUBLISHED_MEM_FORMAT, 3];
754
755/// Does a reader updated for the current format accept an archive at
756/// `format`? The single predicate every reader gate consults —
757/// validation (`validator::config::parse_config_bytes`) and byte
758/// hydration (`Engine::from_archive_bytes`) alike — so acceptance
759/// cannot drift between them.
760pub fn published_format_accepted(format: u32) -> bool {
761 PUBLISHED_MEM_FORMATS_ACCEPTED.contains(&format)
762}
763
764/// Errors returned by `published_config_from`. Actionable messages —
765/// the caller (export pipeline, publish pipeline) surfaces these
766/// directly to the user without wrapping a raw serde error.
767#[derive(Debug, thiserror::Error)]
768pub enum PublishConversionError {
769 #[error("config.version is required for mem publish — set it in .memstead/config.json")]
770 MissingVersion,
771 #[error(
772 "config must declare `schema` (e.g. \"default@1.0.0\") — set it in .memstead/config.json"
773 )]
774 MissingSchema,
775 #[error(
776 "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)"
777 )]
778 MissingName,
779}
780
781/// The whitelist projection. Everything author-only is discarded; only
782/// the fields that make sense outside the author's working directory
783/// ride into the archive. `format` is pinned at `PUBLISHED_MEM_FORMAT`.
784///
785/// `name` is supplied explicitly by the caller — the on-disk `name`
786/// field is optional and the engine no longer treats it as the
787/// mem-identity source. The published archive still needs an
788/// identity, so the publishing path passes the leaf folder name
789/// (`__MEMSTEAD:mems/<path>/<leaf>/config.json`'s `<leaf>`, or the
790/// disk basename on the legacy disk path) here. Falls back to the
791/// in-config `name` field when the caller passes an empty string and
792/// the config still carries a legacy `name` value (so pre-cutover
793/// archives published before the migration land cleanly).
794pub fn published_config_from(
795 config: &MemConfig,
796 name: &str,
797) -> Result<PublishedMemConfig, PublishConversionError> {
798 let version = config
799 .version
800 .clone()
801 .ok_or(PublishConversionError::MissingVersion)?;
802 let schema = config
803 .schema
804 .clone()
805 .ok_or(PublishConversionError::MissingSchema)?;
806 let resolved_name = if name.is_empty() {
807 config
808 .name
809 .clone()
810 .ok_or(PublishConversionError::MissingName)?
811 } else {
812 name.to_string()
813 };
814 Ok(PublishedMemConfig {
815 format: PUBLISHED_MEM_FORMAT,
816 name: resolved_name,
817 version,
818 description: config.description.clone(),
819 title: config.title.clone(),
820 subject: config.subject.clone(),
821 authors: config.authors.clone(),
822 schema,
823 })
824}
825
826// ---------------------------------------------------------------------------
827// Constants
828// ---------------------------------------------------------------------------
829
830const KNOWN_TOP_LEVEL_KEYS: &[&str] = &[
831 "version",
832 "description",
833 "title",
834 "subject",
835 "authors",
836 "schema",
837 "writeGuidance",
838 "rules",
839 "publish",
840 "language",
841 "readMems",
842 "community",
843 "vcs",
844 "syncState",
845 // Engine-owned or lifecycle keys the struct models: the validator
846 // must not call them unknown ("will be ignored") when the engine
847 // reads every one of them.
848 "format",
849 "processMem",
850 "unregisteredAt",
851 "reviewMark",
852 "mutationStamp",
853 "forkedFrom",
854 "renamingFrom",
855];
856
857/// Keys that are explicitly rejected with a `LEGACY_FIELD_PRESENT`
858/// envelope when present in a config. The validator surfaces a hard
859/// error (not a soft "unknown key" warning) so agents that recreate
860/// the legacy shape from training-set examples see a structured
861/// rejection instead of silent acceptance with drift.
862///
863/// Each entry pairs the rejected key with an actionable error message.
864/// New tombstones land here when a top-level key migrates from
865/// "deprecated but tolerated" to "must not be re-authored". The table
866/// holds entries for `name` (the field is now path-derived),
867/// `types: [...]` (the pre-existing tombstone, preserved verbatim),
868/// `belongsTo` (cross-mem authorization moved to the workspace file),
869/// and `deps` (cross-mem attachments moved to the mount roster).
870const LEGACY_TOMBSTONE_KEYS: &[(&str, &str)] = &[
871 (
872 "types",
873 "Legacy `types: [...]` field detected — replace with `schema: \"<name>@<version>\"` \
874 (e.g. `\"schema\": \"default@1.0.0\"`).",
875 ),
876 (
877 "name",
878 "Legacy `name` field detected — the mem leaf folder under `__MEMSTEAD:mems/` (or the \
879 disk basename on the legacy disk path) is path-derived under the unified layout; \
880 remove the field from `.memstead/config.json`.",
881 ),
882 (
883 "deps",
884 "Legacy `deps` field detected — a cross-mem attachment is a mount now, not a config \
885 list. Remove the field from `.memstead/config.json` and run `memstead install \
886 <scope>/<name>` so the attachment lands in \
887 `.memstead/state/mounts.json`, where the engine reads it.",
888 ),
889 (
890 "belongsTo",
891 "Legacy `belongsTo` field detected — cross-mem authorization moved to the \
892 workspace-level `[cross_mem_links]` section in `.memstead/workspace.toml`. Remove the \
893 field from `.memstead/config.json` and add an entry under `[cross_mem_links]` \
894 instead.",
895 ),
896];
897
898// ---------------------------------------------------------------------------
899// checkConfig — the main validator
900// ---------------------------------------------------------------------------
901
902/// Validate a raw config JSON value. Returns structured errors and warnings.
903pub fn check_config(config: &Value) -> ConfigCheckResult {
904 let mut errors = Vec::new();
905 let mut warnings = Vec::new();
906
907 let obj = match config.as_object() {
908 Some(o) => o,
909 None => {
910 errors.push("(root): config must be an object".to_string());
911 return ConfigCheckResult {
912 valid: false,
913 errors,
914 warnings,
915 error_code: None,
916 };
917 }
918 };
919
920 // 2. Legacy tombstones — keys that must not be re-authored. Each
921 // hit produces a hard error and pins the `LEGACY_FIELD_PRESENT`
922 // envelope code so callers branch on a stable identifier rather
923 // than the human-readable error message. See
924 // `LEGACY_TOMBSTONE_KEYS` for the reject list.
925 let mut legacy_field_hit = false;
926 for (key, message) in LEGACY_TOMBSTONE_KEYS {
927 if obj.contains_key(*key) {
928 errors.push((*message).to_string());
929 legacy_field_hit = true;
930 }
931 }
932
933 // 2b. Format version: absent means MEM_CONFIG_FORMAT; the current
934 // version passes; anything else is a hard error — the same verdict
935 // the parse-time gate renders, carried here so the validation
936 // surface (CLI check output) names it too.
937 match obj.get("format") {
938 None => {}
939 Some(v) if v.as_u64() == Some(u64::from(MEM_CONFIG_FORMAT)) => {}
940 Some(v)
941 if v.as_u64()
942 .and_then(|n| u32::try_from(n).ok())
943 .is_some_and(published_format_accepted) => {}
944 Some(v) => errors.push(format!(
945 "format: unsupported mem config format {v}: this engine reads format \
946 {MEM_CONFIG_FORMAT} (an absent key means the same); a higher value was \
947 written by a newer engine — upgrade before loading this mem"
948 )),
949 }
950
951 // 3. Schema field: exact `name@x.y.z` reference required. Bare-name
952 // pins are rejected at parse time via SchemaRef::from_str.
953 match obj.get("schema") {
954 Some(Value::String(s)) => {
955 if let Err(e) = s.parse::<SchemaRef>() {
956 errors.push(format!("schema: {e}"));
957 }
958 }
959 Some(_) => errors.push(
960 "schema: must be a string of the form \"<name>@<x.y.z>\" \
961 (exact version pin, e.g. \"default@1.0.0\")"
962 .to_string(),
963 ),
964 None => errors.push(
965 "Config must declare `schema` — exact pin of the form \
966 \"<name>@<x.y.z>\" (e.g. \"default@1.0.0\")"
967 .to_string(),
968 ),
969 }
970
971 // 4. Read-mems map — source presence and shape.
972 // Cache-file existence is checked at engine init (`Engine::init`
973 // via `mem_cache`), not here, so isolated schema tests don't
974 // need real archive fixture files. The cached archive's config is
975 // authoritative for the version; no `version` or `path` is
976 // recorded in the config entry.
977 if let Some(Value::Object(mems)) = obj.get("readMems") {
978 for (name, spec) in mems {
979 let entry_path = format!("readMems.{name}");
980
981 let spec_obj = match spec.as_object() {
982 Some(o) => o,
983 None => {
984 errors.push(format!("{entry_path}: read-mem entry must be an object"));
985 continue;
986 }
987 };
988
989 let source = match spec_obj.get("source").and_then(|v| v.as_object()) {
990 Some(s) => s,
991 None => {
992 errors.push(format!(
993 "{entry_path}.source: read-mem entry must declare a source \
994 (e.g. {{\"type\": \"local\"}} or {{\"type\": \"url\", \"url\": \"…\"}})"
995 ));
996 continue;
997 }
998 };
999
1000 match source.get("type").and_then(|v| v.as_str()) {
1001 Some("local") => {}
1002 Some("url") => match source.get("url").and_then(|v| v.as_str()) {
1003 Some(u) if !u.is_empty() => {}
1004 _ => errors.push(format!(
1005 "{entry_path}.source.url: url source must declare a non-empty 'url' string"
1006 )),
1007 },
1008 // `registry` type is reserved for future use but not
1009 // accepted yet — fails here alongside any other unknown.
1010 Some(other) => errors.push(format!(
1011 "{entry_path}.source.type: unknown source type '{other}' \
1012 (expected 'local' or 'url')"
1013 )),
1014 None => errors.push(format!(
1015 "{entry_path}.source.type: source must declare a 'type' \
1016 ('local' or 'url')"
1017 )),
1018 }
1019 }
1020 }
1021
1022 // 5. `belongsTo` is now a tombstone (see `LEGACY_TOMBSTONE_KEYS`).
1023 // Cross-mem authorization moved to the workspace-level
1024 // `[cross_mem_links]` section in `.memstead/workspace.toml`. Per-mem config
1025 // blobs that still carry the field are rejected with the
1026 // tombstone error above; no shape validation runs here.
1027
1028 // 7. Unknown key warnings. Tombstone keys are rejected above and
1029 // skipped here so callers don't see a redundant warning alongside
1030 // the hard error.
1031 for key in obj.keys() {
1032 if KNOWN_TOP_LEVEL_KEYS.contains(&key.as_str())
1033 || LEGACY_TOMBSTONE_KEYS
1034 .iter()
1035 .any(|(k, _)| *k == key.as_str())
1036 {
1037 continue;
1038 }
1039 warnings.push(format!(
1040 "Unknown config key '{key}' \u{2014} will be ignored"
1041 ));
1042 }
1043
1044 let error_code = if legacy_field_hit {
1045 Some("LEGACY_FIELD_PRESENT".to_string())
1046 } else {
1047 None
1048 };
1049
1050 ConfigCheckResult {
1051 valid: errors.is_empty(),
1052 errors,
1053 warnings,
1054 error_code,
1055 }
1056}
1057
1058// ---------------------------------------------------------------------------
1059// Config loading
1060// ---------------------------------------------------------------------------
1061
1062/// Load and parse a config from a mem directory.
1063/// Reads `<mem_dir>/.memstead/config.json`.
1064pub fn load_config(mem_dir: &Path) -> Result<(Value, PathBuf), ConfigError> {
1065 let config_path = mem_dir.join(MEM_META_DIR).join("config.json");
1066 let raw = std::fs::read_to_string(&config_path).map_err(|e| {
1067 if e.kind() == std::io::ErrorKind::NotFound {
1068 ConfigError::NotFound(config_path.display().to_string())
1069 } else {
1070 ConfigError::Io(e)
1071 }
1072 })?;
1073 let parsed: Value = serde_json::from_str(&raw)
1074 .map_err(|_| ConfigError::InvalidJson(config_path.display().to_string()))?;
1075 Ok((parsed, config_path))
1076}
1077
1078/// Parse a raw JSON value into a MemConfig.
1079pub fn parse_mem_config(value: &Value) -> Result<MemConfig, ConfigError> {
1080 serde_json::from_value(value.clone()).map_err(|e| ConfigError::Other(e.to_string()))
1081}
1082
1083/// Load, validate, and parse a mem config from disk.
1084pub fn load_and_validate(mem_dir: &Path) -> Result<MemConfig, ConfigError> {
1085 let (raw, _path) = load_config(mem_dir)?;
1086
1087 let result = check_config(&raw);
1088 if !result.valid {
1089 return Err(ConfigError::ValidationFailed(result.errors));
1090 }
1091
1092 parse_mem_config(&raw)
1093}
1094
1095// ---------------------------------------------------------------------------
1096// Config writing
1097// ---------------------------------------------------------------------------
1098
1099/// Write a config JSON value to disk (pretty-printed with trailing newline).
1100fn write_config(config_path: &Path, config: &Value) -> Result<(), ConfigError> {
1101 let json = serde_json::to_string_pretty(config)? + "\n";
1102 std::fs::write(config_path, json)?;
1103 Ok(())
1104}
1105
1106/// Validate and write a config to disk. Returns check result.
1107fn commit_config(
1108 config_path: &Path,
1109 config: &Value,
1110 dry_run: bool,
1111) -> Result<ConfigCheckResult, ConfigError> {
1112 let check = check_config(config);
1113 if !check.valid {
1114 return Ok(check);
1115 }
1116 if !dry_run {
1117 write_config(config_path, config)?;
1118 }
1119 Ok(check)
1120}
1121
1122// ---------------------------------------------------------------------------
1123// Config CRUD operations
1124// ---------------------------------------------------------------------------
1125
1126/// Allowed top-level fields for `update_config_field`. The
1127/// workspace rewrite dropped `mediums` and
1128/// `projections` here: the engine no longer recognises those blocks so
1129/// they are not writable through the update surface either.
1130const ALLOWED_UPDATE_FIELDS: &[&str] = &[
1131 "version",
1132 "description",
1133 "authors",
1134 "writeGuidance",
1135 "rules",
1136 "readMems",
1137 "schema",
1138 "language",
1139 "publish",
1140];
1141
1142const PROTECTED_FIELDS: &[&str] = &["name"];
1143
1144/// Update a top-level config field.
1145pub fn update_config_field(
1146 config_path: &Path,
1147 config: &mut Value,
1148 field: &str,
1149 value: Value,
1150 dry_run: bool,
1151) -> Result<ConfigCheckResult, ConfigError> {
1152 if PROTECTED_FIELDS.contains(&field) {
1153 return Err(ConfigError::Other(format!("Field '{field}' is protected")));
1154 }
1155
1156 let obj = config
1157 .as_object_mut()
1158 .ok_or_else(|| ConfigError::Other("config must be an object".into()))?;
1159
1160 if !ALLOWED_UPDATE_FIELDS.contains(&field) {
1161 return Err(ConfigError::Other(format!(
1162 "Field '{field}' is not a recognized config field. Allowed: {}",
1163 ALLOWED_UPDATE_FIELDS.join(", ")
1164 )));
1165 }
1166
1167 obj.insert(field.to_string(), value);
1168 commit_config(config_path, config, dry_run)
1169}
1170
1171// ===========================================================================
1172// Tests
1173// ===========================================================================
1174
1175#[cfg(test)]
1176mod tests;