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 /// Per-source "last successfully synced source state", written by
565 /// the ingest layer and surfaced verbatim on the workspace dump.
566 /// The engine never parses, validates, or interprets a value:
567 /// each token is opaque, its meaning owned by the medium-type
568 /// layer that produced it (git → commit id, graph → snapshot
569 /// token, filesystem → a small stat digest the plugin
570 /// JSON-stringifies). The key is likewise opaque — the binding
571 /// layer keys per `(binding, facet)` (conventionally
572 /// `"<binding-id>/<facet>#synced"`, D4), but the engine treats it as
573 /// an arbitrary string. This is the durable, shared baseline against which a
574 /// fresh ingest iteration diffs "what changed since last time";
575 /// it survives a skill-cache wipe and a machine change because it
576 /// lives in engine-held mem config, not ephemeral plugin cache.
577 ///
578 /// Stripped from `PublishedMemConfig` — sync state is
579 /// workspace-local ingest bookkeeping, not part of a published
580 /// mem's identity. `BTreeMap` (not `HashMap`) for stable
581 /// serialization order: diff-friendly config on disk and
582 /// reproducible dump output.
583 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
584 pub sync_state: BTreeMap<String, String>,
585
586 /// The mem's review mark: the last human-approved state, in the
587 /// backend-opaque cursor vocabulary `changes_since` consumes
588 /// (git-branch: commit SHA; folder: changelog RFC3339 timestamp).
589 /// Absent is a first-class state — a mem with no mark is ordinary,
590 /// never an error, and marks never gate writes. One mark per mem;
591 /// wire key `reviewMark` (camelCase per the config's convention).
592 ///
593 /// Stripped from `PublishedMemConfig` (allowlist projection) —
594 /// review state is workspace-collaboration bookkeeping, not part
595 /// of a published mem's identity.
596 #[serde(
597 default,
598 rename = "reviewMark",
599 skip_serializing_if = "Option::is_none"
600 )]
601 pub review_mark: Option<String>,
602
603 /// Engine-owned version stamp of the last successful mutation:
604 /// which engine version and which resolved schema performed it.
605 /// Written by the engine after a mutation and only when the values
606 /// changed (a binary upgrade or a schema repin), never by authors,
607 /// never on read-only loads — a boot writes nothing. Boot compares
608 /// the running binary against the stamp and surfaces a divergence
609 /// as the warn-tier `ENGINE_VERSION_SKEW` hint; absence of a stamp
610 /// is a first-class state (pre-stamp mems), never skew. The stamp
611 /// is the substrate any future migration machinery would consult —
612 /// deliberately built without that machinery.
613 ///
614 /// Stripped from `PublishedMemConfig` (allowlist projection) —
615 /// workspace-local engine bookkeeping, not published identity.
616 /// Wire key `mutationStamp` (camelCase per the config convention).
617 #[serde(
618 default,
619 rename = "mutationStamp",
620 skip_serializing_if = "Option::is_none"
621 )]
622 pub mutation_stamp: Option<MutationStamp>,
623
624 /// The recorded ancestor of a mem created by `memstead mem fork`:
625 /// the source mem, the commit its branch started at, the remote
626 /// when one was used, and the fork's own first commit (`base`).
627 /// Written once at fork time and never moved (the review mark is
628 /// the moving cursor; the ancestor is not).
629 /// Absent on every mem that was not forked. Wire key `forkedFrom`.
630 ///
631 /// Stripped from `PublishedMemConfig` (allowlist projection), whose
632 /// deny-unknown-fields shape refuses the key outright. An engine
633 /// that predates the field reads the config unchanged: the key
634 /// lands in the flattened `extra` map and is written back verbatim.
635 #[serde(
636 default,
637 rename = "forkedFrom",
638 skip_serializing_if = "Option::is_none"
639 )]
640 pub forked_from: Option<ForkedFrom>,
641
642 /// Extra fields not in the known set (captured for round-tripping).
643 ///
644 /// Historical tombstones:
645 /// - `defaultSchema` (pre-2026-04): legacy per-mem default type.
646 /// Per-entity `type:` frontmatter is authoritative now.
647 /// - `types: [...]` (pre-schema-artifact, 2026-04): replaced by
648 /// `schema: "<name>@<version>"`. Legacy entries are hard-rejected
649 /// by `check_config`.
650 #[serde(flatten)]
651 pub extra: HashMap<String, Value>,
652}
653
654// ---------------------------------------------------------------------------
655// Published (archive) mem config
656// ---------------------------------------------------------------------------
657
658/// Strict-ingress shape of a mem config. This is the **only** metadata
659/// form that enters a `.mem` archive. `MemConfig` carries author-only
660/// fields (writeGuidance, rules, publish, readMems, language,
661/// community, defaultSchema, vcs, plus any key captured in
662/// `extra`) that never belong in a published archive;
663/// `published_config_from` projects `MemConfig` →
664/// `PublishedMemConfig`, dropping everything outside the whitelist.
665///
666/// `deny_unknown_fields` + no `serde(flatten)` on purpose: the validator
667/// re-parses this shape with the same struct as defense-in-depth, so any
668/// legacy author key smuggled into an archive surfaces as a rejection
669/// instead of a silently-tolerated payload.
670#[derive(Debug, Clone, Serialize, Deserialize)]
671#[serde(deny_unknown_fields, rename_all = "camelCase")]
672pub struct PublishedMemConfig {
673 pub format: u32,
674 pub name: String,
675 pub version: semver::Version,
676 #[serde(skip_serializing_if = "Option::is_none")]
677 pub description: Option<String>,
678 /// Human-readable display title (format ≥ 4). Display text, not
679 /// identity — a format-3 archive simply has none.
680 #[serde(default, skip_serializing_if = "Option::is_none")]
681 pub title: Option<String>,
682 /// The mem's subject block (format ≥ 4), published verbatim —
683 /// exclusions included and in order.
684 #[serde(default, skip_serializing_if = "Option::is_none")]
685 pub subject: Option<MemSubject>,
686 #[serde(skip_serializing_if = "Option::is_none")]
687 pub authors: Option<Vec<String>>,
688 pub schema: SchemaRef,
689}
690
691/// Archive format integer written to the archive config's `format`
692/// field. Bumped to `4` for the mem title + subject block (both
693/// optional — a format-3 archive simply has neither). Readers accept
694/// `3` and `4` via [`published_format_accepted`]; `format: 1` (V1) and
695/// `format: 2` (V2, top-level `schema/` tree) archives keep refusing
696/// cleanly.
697pub const PUBLISHED_MEM_FORMAT: u32 = 4;
698
699/// The workspace mem config's format version (`<mem>/.memstead/config.json`).
700/// One accepted value; an absent key means exactly this version, and any
701/// other value refuses at parse ([`de_mem_config_format`]).
702pub const MEM_CONFIG_FORMAT: u32 = 1;
703
704/// Deserialize the workspace mem config's `format` key: absent stays `None`
705/// (meaning [`MEM_CONFIG_FORMAT`]), the current version parses, anything
706/// else refuses loudly — a config a future engine may mean differently must
707/// never be silently read as today's shape.
708fn de_mem_config_format<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
709where
710 D: serde::Deserializer<'de>,
711{
712 let value = Option::<u32>::deserialize(deserializer)?;
713 match value {
714 None | Some(MEM_CONFIG_FORMAT) => Ok(value),
715 // A mounted read-mem's cached config is the published shape and
716 // parses through this same struct, so the published versions this
717 // engine reads are accepted here too (their own gate ran at
718 // archive validation).
719 Some(found) if published_format_accepted(found) => Ok(value),
720 Some(found) => Err(serde::de::Error::custom(format!(
721 "unsupported mem config format {found}: this engine reads format \
722 {MEM_CONFIG_FORMAT} (an absent key means the same); a higher value \
723 was written by a newer engine — upgrade before loading this mem"
724 ))),
725 }
726}
727
728impl MemConfig {
729 /// The effective config format version: the declared value, or
730 /// [`MEM_CONFIG_FORMAT`] when the key is absent.
731 pub fn format_version(&self) -> u32 {
732 self.format.unwrap_or(MEM_CONFIG_FORMAT)
733 }
734}
735
736/// Every archive format a current reader accepts, newest first: the
737/// current integer plus format 3 (the pre-title/subject shape — the two
738/// mems already published on the live registry stay installable without
739/// a re-publish). `format: 1` (V1) and `format: 2` (V2, top-level
740/// `schema/` tree) keep refusing cleanly.
741///
742/// A list rather than a predicate body because the accepted set is a
743/// fact worth reading directly, not only a branch to evaluate.
744pub const PUBLISHED_MEM_FORMATS_ACCEPTED: &[u32] = &[PUBLISHED_MEM_FORMAT, 3];
745
746/// Does a reader updated for the current format accept an archive at
747/// `format`? The single predicate every reader gate consults —
748/// validation (`validator::config::parse_config_bytes`) and byte
749/// hydration (`Engine::from_archive_bytes`) alike — so acceptance
750/// cannot drift between them.
751pub fn published_format_accepted(format: u32) -> bool {
752 PUBLISHED_MEM_FORMATS_ACCEPTED.contains(&format)
753}
754
755/// Errors returned by `published_config_from`. Actionable messages —
756/// the caller (export pipeline, publish pipeline) surfaces these
757/// directly to the user without wrapping a raw serde error.
758#[derive(Debug, thiserror::Error)]
759pub enum PublishConversionError {
760 #[error("config.version is required for mem publish — set it in .memstead/config.json")]
761 MissingVersion,
762 #[error(
763 "config must declare `schema` (e.g. \"default@1.0.0\") — set it in .memstead/config.json"
764 )]
765 MissingSchema,
766 #[error(
767 "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)"
768 )]
769 MissingName,
770}
771
772/// The whitelist projection. Everything author-only is discarded; only
773/// the fields that make sense outside the author's working directory
774/// ride into the archive. `format` is pinned at `PUBLISHED_MEM_FORMAT`.
775///
776/// `name` is supplied explicitly by the caller — the on-disk `name`
777/// field is optional and the engine no longer treats it as the
778/// mem-identity source. The published archive still needs an
779/// identity, so the publishing path passes the leaf folder name
780/// (`__MEMSTEAD:mems/<path>/<leaf>/config.json`'s `<leaf>`, or the
781/// disk basename on the legacy disk path) here. Falls back to the
782/// in-config `name` field when the caller passes an empty string and
783/// the config still carries a legacy `name` value (so pre-cutover
784/// archives published before the migration land cleanly).
785pub fn published_config_from(
786 config: &MemConfig,
787 name: &str,
788) -> Result<PublishedMemConfig, PublishConversionError> {
789 let version = config
790 .version
791 .clone()
792 .ok_or(PublishConversionError::MissingVersion)?;
793 let schema = config
794 .schema
795 .clone()
796 .ok_or(PublishConversionError::MissingSchema)?;
797 let resolved_name = if name.is_empty() {
798 config
799 .name
800 .clone()
801 .ok_or(PublishConversionError::MissingName)?
802 } else {
803 name.to_string()
804 };
805 Ok(PublishedMemConfig {
806 format: PUBLISHED_MEM_FORMAT,
807 name: resolved_name,
808 version,
809 description: config.description.clone(),
810 title: config.title.clone(),
811 subject: config.subject.clone(),
812 authors: config.authors.clone(),
813 schema,
814 })
815}
816
817// ---------------------------------------------------------------------------
818// Constants
819// ---------------------------------------------------------------------------
820
821const KNOWN_TOP_LEVEL_KEYS: &[&str] = &[
822 "version",
823 "description",
824 "title",
825 "subject",
826 "authors",
827 "schema",
828 "writeGuidance",
829 "rules",
830 "publish",
831 "language",
832 "readMems",
833 "community",
834 "vcs",
835 "syncState",
836 // Engine-owned or lifecycle keys the struct models: the validator
837 // must not call them unknown ("will be ignored") when the engine
838 // reads every one of them.
839 "format",
840 "processMem",
841 "unregisteredAt",
842 "reviewMark",
843 "mutationStamp",
844 "forkedFrom",
845];
846
847/// Keys that are explicitly rejected with a `LEGACY_FIELD_PRESENT`
848/// envelope when present in a config. The validator surfaces a hard
849/// error (not a soft "unknown key" warning) so agents that recreate
850/// the legacy shape from training-set examples see a structured
851/// rejection instead of silent acceptance with drift.
852///
853/// Each entry pairs the rejected key with an actionable error message.
854/// New tombstones land here when a top-level key migrates from
855/// "deprecated but tolerated" to "must not be re-authored". The table
856/// holds entries for `name` (the field is now path-derived),
857/// `types: [...]` (the pre-existing tombstone, preserved verbatim),
858/// `belongsTo` (cross-mem authorization moved to the workspace file),
859/// and `deps` (cross-mem attachments moved to the mount roster).
860const LEGACY_TOMBSTONE_KEYS: &[(&str, &str)] = &[
861 (
862 "types",
863 "Legacy `types: [...]` field detected — replace with `schema: \"<name>@<version>\"` \
864 (e.g. `\"schema\": \"default@1.0.0\"`).",
865 ),
866 (
867 "name",
868 "Legacy `name` field detected — the mem leaf folder under `__MEMSTEAD:mems/` (or the \
869 disk basename on the legacy disk path) is path-derived under the unified layout; \
870 remove the field from `.memstead/config.json`.",
871 ),
872 (
873 "deps",
874 "Legacy `deps` field detected — a cross-mem attachment is a mount now, not a config \
875 list. Remove the field from `.memstead/config.json` and run `memstead install \
876 <scope>/<name>` so the attachment lands in \
877 `.memstead/state/mounts.json`, where the engine reads it.",
878 ),
879 (
880 "belongsTo",
881 "Legacy `belongsTo` field detected — cross-mem authorization moved to the \
882 workspace-level `[cross_mem_links]` section in `.memstead/workspace.toml`. Remove the \
883 field from `.memstead/config.json` and add an entry under `[cross_mem_links]` \
884 instead.",
885 ),
886];
887
888// ---------------------------------------------------------------------------
889// checkConfig — the main validator
890// ---------------------------------------------------------------------------
891
892/// Validate a raw config JSON value. Returns structured errors and warnings.
893pub fn check_config(config: &Value) -> ConfigCheckResult {
894 let mut errors = Vec::new();
895 let mut warnings = Vec::new();
896
897 let obj = match config.as_object() {
898 Some(o) => o,
899 None => {
900 errors.push("(root): config must be an object".to_string());
901 return ConfigCheckResult {
902 valid: false,
903 errors,
904 warnings,
905 error_code: None,
906 };
907 }
908 };
909
910 // 2. Legacy tombstones — keys that must not be re-authored. Each
911 // hit produces a hard error and pins the `LEGACY_FIELD_PRESENT`
912 // envelope code so callers branch on a stable identifier rather
913 // than the human-readable error message. See
914 // `LEGACY_TOMBSTONE_KEYS` for the reject list.
915 let mut legacy_field_hit = false;
916 for (key, message) in LEGACY_TOMBSTONE_KEYS {
917 if obj.contains_key(*key) {
918 errors.push((*message).to_string());
919 legacy_field_hit = true;
920 }
921 }
922
923 // 2b. Format version: absent means MEM_CONFIG_FORMAT; the current
924 // version passes; anything else is a hard error — the same verdict
925 // the parse-time gate renders, carried here so the validation
926 // surface (CLI check output) names it too.
927 match obj.get("format") {
928 None => {}
929 Some(v) if v.as_u64() == Some(u64::from(MEM_CONFIG_FORMAT)) => {}
930 Some(v)
931 if v.as_u64()
932 .and_then(|n| u32::try_from(n).ok())
933 .is_some_and(published_format_accepted) => {}
934 Some(v) => errors.push(format!(
935 "format: unsupported mem config format {v}: this engine reads format \
936 {MEM_CONFIG_FORMAT} (an absent key means the same); a higher value was \
937 written by a newer engine — upgrade before loading this mem"
938 )),
939 }
940
941 // 3. Schema field: exact `name@x.y.z` reference required. Bare-name
942 // pins are rejected at parse time via SchemaRef::from_str.
943 match obj.get("schema") {
944 Some(Value::String(s)) => {
945 if let Err(e) = s.parse::<SchemaRef>() {
946 errors.push(format!("schema: {e}"));
947 }
948 }
949 Some(_) => errors.push(
950 "schema: must be a string of the form \"<name>@<x.y.z>\" \
951 (exact version pin, e.g. \"default@1.0.0\")"
952 .to_string(),
953 ),
954 None => errors.push(
955 "Config must declare `schema` — exact pin of the form \
956 \"<name>@<x.y.z>\" (e.g. \"default@1.0.0\")"
957 .to_string(),
958 ),
959 }
960
961 // 4. Read-mems map — source presence and shape.
962 // Cache-file existence is checked at engine init (`Engine::init`
963 // via `mem_cache`), not here, so isolated schema tests don't
964 // need real archive fixture files. The cached archive's config is
965 // authoritative for the version; no `version` or `path` is
966 // recorded in the config entry.
967 if let Some(Value::Object(mems)) = obj.get("readMems") {
968 for (name, spec) in mems {
969 let entry_path = format!("readMems.{name}");
970
971 let spec_obj = match spec.as_object() {
972 Some(o) => o,
973 None => {
974 errors.push(format!("{entry_path}: read-mem entry must be an object"));
975 continue;
976 }
977 };
978
979 let source = match spec_obj.get("source").and_then(|v| v.as_object()) {
980 Some(s) => s,
981 None => {
982 errors.push(format!(
983 "{entry_path}.source: read-mem entry must declare a source \
984 (e.g. {{\"type\": \"local\"}} or {{\"type\": \"url\", \"url\": \"…\"}})"
985 ));
986 continue;
987 }
988 };
989
990 match source.get("type").and_then(|v| v.as_str()) {
991 Some("local") => {}
992 Some("url") => match source.get("url").and_then(|v| v.as_str()) {
993 Some(u) if !u.is_empty() => {}
994 _ => errors.push(format!(
995 "{entry_path}.source.url: url source must declare a non-empty 'url' string"
996 )),
997 },
998 // `registry` type is reserved for future use but not
999 // accepted yet — fails here alongside any other unknown.
1000 Some(other) => errors.push(format!(
1001 "{entry_path}.source.type: unknown source type '{other}' \
1002 (expected 'local' or 'url')"
1003 )),
1004 None => errors.push(format!(
1005 "{entry_path}.source.type: source must declare a 'type' \
1006 ('local' or 'url')"
1007 )),
1008 }
1009 }
1010 }
1011
1012 // 5. `belongsTo` is now a tombstone (see `LEGACY_TOMBSTONE_KEYS`).
1013 // Cross-mem authorization moved to the workspace-level
1014 // `[cross_mem_links]` section in `.memstead/workspace.toml`. Per-mem config
1015 // blobs that still carry the field are rejected with the
1016 // tombstone error above; no shape validation runs here.
1017
1018 // 7. Unknown key warnings. Tombstone keys are rejected above and
1019 // skipped here so callers don't see a redundant warning alongside
1020 // the hard error.
1021 for key in obj.keys() {
1022 if KNOWN_TOP_LEVEL_KEYS.contains(&key.as_str())
1023 || LEGACY_TOMBSTONE_KEYS
1024 .iter()
1025 .any(|(k, _)| *k == key.as_str())
1026 {
1027 continue;
1028 }
1029 warnings.push(format!(
1030 "Unknown config key '{key}' \u{2014} will be ignored"
1031 ));
1032 }
1033
1034 let error_code = if legacy_field_hit {
1035 Some("LEGACY_FIELD_PRESENT".to_string())
1036 } else {
1037 None
1038 };
1039
1040 ConfigCheckResult {
1041 valid: errors.is_empty(),
1042 errors,
1043 warnings,
1044 error_code,
1045 }
1046}
1047
1048// ---------------------------------------------------------------------------
1049// Config loading
1050// ---------------------------------------------------------------------------
1051
1052/// Load and parse a config from a mem directory.
1053/// Reads `<mem_dir>/.memstead/config.json`.
1054pub fn load_config(mem_dir: &Path) -> Result<(Value, PathBuf), ConfigError> {
1055 let config_path = mem_dir.join(MEM_META_DIR).join("config.json");
1056 let raw = std::fs::read_to_string(&config_path).map_err(|e| {
1057 if e.kind() == std::io::ErrorKind::NotFound {
1058 ConfigError::NotFound(config_path.display().to_string())
1059 } else {
1060 ConfigError::Io(e)
1061 }
1062 })?;
1063 let parsed: Value = serde_json::from_str(&raw)
1064 .map_err(|_| ConfigError::InvalidJson(config_path.display().to_string()))?;
1065 Ok((parsed, config_path))
1066}
1067
1068/// Parse a raw JSON value into a MemConfig.
1069pub fn parse_mem_config(value: &Value) -> Result<MemConfig, ConfigError> {
1070 serde_json::from_value(value.clone()).map_err(|e| ConfigError::Other(e.to_string()))
1071}
1072
1073/// Load, validate, and parse a mem config from disk.
1074pub fn load_and_validate(mem_dir: &Path) -> Result<MemConfig, ConfigError> {
1075 let (raw, _path) = load_config(mem_dir)?;
1076
1077 let result = check_config(&raw);
1078 if !result.valid {
1079 return Err(ConfigError::ValidationFailed(result.errors));
1080 }
1081
1082 parse_mem_config(&raw)
1083}
1084
1085// ---------------------------------------------------------------------------
1086// Config writing
1087// ---------------------------------------------------------------------------
1088
1089/// Write a config JSON value to disk (pretty-printed with trailing newline).
1090fn write_config(config_path: &Path, config: &Value) -> Result<(), ConfigError> {
1091 let json = serde_json::to_string_pretty(config)? + "\n";
1092 std::fs::write(config_path, json)?;
1093 Ok(())
1094}
1095
1096/// Validate and write a config to disk. Returns check result.
1097fn commit_config(
1098 config_path: &Path,
1099 config: &Value,
1100 dry_run: bool,
1101) -> Result<ConfigCheckResult, ConfigError> {
1102 let check = check_config(config);
1103 if !check.valid {
1104 return Ok(check);
1105 }
1106 if !dry_run {
1107 write_config(config_path, config)?;
1108 }
1109 Ok(check)
1110}
1111
1112// ---------------------------------------------------------------------------
1113// Config CRUD operations
1114// ---------------------------------------------------------------------------
1115
1116/// Allowed top-level fields for `update_config_field`. The
1117/// workspace rewrite dropped `mediums` and
1118/// `projections` here: the engine no longer recognises those blocks so
1119/// they are not writable through the update surface either.
1120const ALLOWED_UPDATE_FIELDS: &[&str] = &[
1121 "version",
1122 "description",
1123 "authors",
1124 "writeGuidance",
1125 "rules",
1126 "readMems",
1127 "schema",
1128 "language",
1129 "publish",
1130];
1131
1132const PROTECTED_FIELDS: &[&str] = &["name"];
1133
1134/// Update a top-level config field.
1135pub fn update_config_field(
1136 config_path: &Path,
1137 config: &mut Value,
1138 field: &str,
1139 value: Value,
1140 dry_run: bool,
1141) -> Result<ConfigCheckResult, ConfigError> {
1142 if PROTECTED_FIELDS.contains(&field) {
1143 return Err(ConfigError::Other(format!("Field '{field}' is protected")));
1144 }
1145
1146 let obj = config
1147 .as_object_mut()
1148 .ok_or_else(|| ConfigError::Other("config must be an object".into()))?;
1149
1150 if !ALLOWED_UPDATE_FIELDS.contains(&field) {
1151 return Err(ConfigError::Other(format!(
1152 "Field '{field}' is not a recognized config field. Allowed: {}",
1153 ALLOWED_UPDATE_FIELDS.join(", ")
1154 )));
1155 }
1156
1157 obj.insert(field.to_string(), value);
1158 commit_config(config_path, config, dry_run)
1159}
1160
1161// ===========================================================================
1162// Tests
1163// ===========================================================================
1164
1165#[cfg(test)]
1166mod tests;