use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const MEM_META_DIR: &str = ".memstead";
pub const ARCHIVE_META_DIR: &str = ".memstead";
pub const ARCHIVE_CONFIG_PATH: &str = ".memstead/config.json";
pub const ARCHIVE_SCHEMA_PREFIX: &str = ".memstead/schema/";
pub const ARCHIVE_PROVENANCE_PATH: &str = ".memstead/provenance.json";
pub const ARCHIVE_ANCHORS_PATH: &str = ".memstead/anchors.json";
pub const ARCHIVE_CHECKS_PATH: &str = ".memstead/checks.json";
pub const ARCHIVE_EXTENSION: &str = "mem";
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
#[error("config file not found: {0}")]
NotFound(String),
#[error("invalid JSON in config file: {0}")]
InvalidJson(String),
#[error("config validation failed:\n{}", .0.iter().map(|e| format!(" - {e}")).collect::<Vec<_>>().join("\n"))]
ValidationFailed(Vec<String>),
#[error("{0}")]
Other(String),
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[error("json error: {0}")]
Json(#[from] serde_json::Error),
}
#[derive(Debug, Clone)]
pub struct ConfigCheckResult {
pub valid: bool,
pub errors: Vec<String>,
pub warnings: Vec<String>,
pub error_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoleConfig {
pub include: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub exclude: Option<Vec<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublishConfig {
pub roles: HashMap<String, RoleConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommunityOverride {
#[serde(skip_serializing_if = "Option::is_none")]
pub resolution: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub seed: Option<u32>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadMemSpec {
pub source: ReadMemSource,
#[serde(default, skip_serializing_if = "Option::is_none", rename = "cacheKey")]
pub cache_key: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ReadMemSource {
Local,
Url { url: String },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SchemaRef {
pub name: String,
pub version: semver::Version,
}
impl SchemaRef {
pub fn new(name: impl Into<String>, version: semver::Version) -> Self {
Self {
name: name.into(),
version,
}
}
pub fn as_display(&self) -> String {
format!("{}@{}", self.name, self.version)
}
}
impl std::fmt::Display for SchemaRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}@{}", self.name, self.version)
}
}
impl std::str::FromStr for SchemaRef {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let trimmed = s.trim();
if trimmed.is_empty() {
return Err("schema reference must not be empty (expected \"name@x.y.z\")".into());
}
let (name, version_str) = trimmed.split_once('@').ok_or_else(|| {
format!(
"schema reference '{trimmed}' must include an exact version — expected \"name@x.y.z\""
)
})?;
if name.is_empty() {
return Err("schema reference name must not be empty".into());
}
if version_str == "latest" {
return Err(format!(
"schema reference '{trimmed}' uses 'latest' — exact semver versions only"
));
}
if version_str.starts_with(['^', '~', '>', '<', '=', '*']) {
return Err(format!(
"schema reference '{trimmed}' uses range syntax — exact semver only (e.g. 'default@1.0.0')"
));
}
let version = semver::Version::parse(version_str).map_err(|e| {
format!("schema reference '{trimmed}' has invalid semver version '{version_str}': {e}")
})?;
Ok(Self {
name: name.to_string(),
version,
})
}
}
impl Serialize for SchemaRef {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.as_display())
}
}
impl<'de> Deserialize<'de> for SchemaRef {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
s.parse::<SchemaRef>().map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct VcsConfig {
pub gitdir: String,
#[serde(default = "vcs_worktree_default")]
pub worktree: String,
}
fn vcs_worktree_default() -> String {
".".to_string()
}
fn deserialize_vcs_tolerant<'de, D>(deserializer: D) -> Result<Option<VcsConfig>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = Option::<Value>::deserialize(deserializer)?;
match value {
None | Some(Value::Null) => Ok(None),
Some(Value::Object(_)) => {
let v = value.unwrap();
Ok(Some(
serde_json::from_value(v).map_err(serde::de::Error::custom)?,
))
}
Some(_) => Ok(None),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct MemSubject {
pub scope: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
#[serde(default)]
pub exclusions: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct MutationStamp {
pub engine_version: String,
pub schema: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ForkedFrom {
pub mem: String,
pub sha: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remote: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base: Option<String>,
}
impl ForkedFrom {
pub fn base_sha(&self) -> &str {
self.base.as_deref().unwrap_or(&self.sha)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemConfig {
#[serde(
default,
deserialize_with = "de_mem_config_format",
skip_serializing_if = "Option::is_none"
)]
pub format: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<semver::Version>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subject: Option<MemSubject>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authors: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub process_mem: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub schema: Option<SchemaRef>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub write_guidance: HashMap<String, Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rules: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub publish: Option<PublishConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub language: Option<String>,
#[serde(
rename = "readMems",
default,
skip_serializing_if = "BTreeMap::is_empty"
)]
pub read_mems: BTreeMap<String, ReadMemSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub community: Option<CommunityOverride>,
#[serde(
default,
deserialize_with = "deserialize_vcs_tolerant",
skip_serializing_if = "Option::is_none"
)]
pub vcs: Option<VcsConfig>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unregistered_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub renaming_from: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub sync_state: BTreeMap<String, String>,
#[serde(
default,
rename = "reviewMark",
skip_serializing_if = "Option::is_none"
)]
pub review_mark: Option<String>,
#[serde(
default,
rename = "mutationStamp",
skip_serializing_if = "Option::is_none"
)]
pub mutation_stamp: Option<MutationStamp>,
#[serde(
default,
rename = "forkedFrom",
skip_serializing_if = "Option::is_none"
)]
pub forked_from: Option<ForkedFrom>,
#[serde(flatten)]
pub extra: HashMap<String, Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct PublishedMemConfig {
pub format: u32,
pub name: String,
pub version: semver::Version,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subject: Option<MemSubject>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authors: Option<Vec<String>>,
pub schema: SchemaRef,
}
pub const PUBLISHED_MEM_FORMAT: u32 = 4;
pub const MEM_CONFIG_FORMAT: u32 = 1;
fn de_mem_config_format<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = Option::<u32>::deserialize(deserializer)?;
match value {
None | Some(MEM_CONFIG_FORMAT) => Ok(value),
Some(found) if published_format_accepted(found) => Ok(value),
Some(found) => Err(serde::de::Error::custom(format!(
"unsupported mem config format {found}: this engine reads format \
{MEM_CONFIG_FORMAT} (an absent key means the same); a higher value \
was written by a newer engine — upgrade before loading this mem"
))),
}
}
impl MemConfig {
pub fn format_version(&self) -> u32 {
self.format.unwrap_or(MEM_CONFIG_FORMAT)
}
}
pub const PUBLISHED_MEM_FORMATS_ACCEPTED: &[u32] = &[PUBLISHED_MEM_FORMAT, 3];
pub fn published_format_accepted(format: u32) -> bool {
PUBLISHED_MEM_FORMATS_ACCEPTED.contains(&format)
}
#[derive(Debug, thiserror::Error)]
pub enum PublishConversionError {
#[error("config.version is required for mem publish — set it in .memstead/config.json")]
MissingVersion,
#[error(
"config must declare `schema` (e.g. \"default@1.0.0\") — set it in .memstead/config.json"
)]
MissingSchema,
#[error(
"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)"
)]
MissingName,
}
pub fn published_config_from(
config: &MemConfig,
name: &str,
) -> Result<PublishedMemConfig, PublishConversionError> {
let version = config
.version
.clone()
.ok_or(PublishConversionError::MissingVersion)?;
let schema = config
.schema
.clone()
.ok_or(PublishConversionError::MissingSchema)?;
let resolved_name = if name.is_empty() {
config
.name
.clone()
.ok_or(PublishConversionError::MissingName)?
} else {
name.to_string()
};
Ok(PublishedMemConfig {
format: PUBLISHED_MEM_FORMAT,
name: resolved_name,
version,
description: config.description.clone(),
title: config.title.clone(),
subject: config.subject.clone(),
authors: config.authors.clone(),
schema,
})
}
const KNOWN_TOP_LEVEL_KEYS: &[&str] = &[
"version",
"description",
"title",
"subject",
"authors",
"schema",
"writeGuidance",
"rules",
"publish",
"language",
"readMems",
"community",
"vcs",
"syncState",
"format",
"processMem",
"unregisteredAt",
"reviewMark",
"mutationStamp",
"forkedFrom",
"renamingFrom",
];
const LEGACY_TOMBSTONE_KEYS: &[(&str, &str)] = &[
(
"types",
"Legacy `types: [...]` field detected — replace with `schema: \"<name>@<version>\"` \
(e.g. `\"schema\": \"default@1.0.0\"`).",
),
(
"name",
"Legacy `name` field detected — the mem leaf folder under `__MEMSTEAD:mems/` (or the \
disk basename on the legacy disk path) is path-derived under the unified layout; \
remove the field from `.memstead/config.json`.",
),
(
"deps",
"Legacy `deps` field detected — a cross-mem attachment is a mount now, not a config \
list. Remove the field from `.memstead/config.json` and run `memstead install \
<scope>/<name>` so the attachment lands in \
`.memstead/state/mounts.json`, where the engine reads it.",
),
(
"belongsTo",
"Legacy `belongsTo` field detected — cross-mem authorization moved to the \
workspace-level `[cross_mem_links]` section in `.memstead/workspace.toml`. Remove the \
field from `.memstead/config.json` and add an entry under `[cross_mem_links]` \
instead.",
),
];
pub fn check_config(config: &Value) -> ConfigCheckResult {
let mut errors = Vec::new();
let mut warnings = Vec::new();
let obj = match config.as_object() {
Some(o) => o,
None => {
errors.push("(root): config must be an object".to_string());
return ConfigCheckResult {
valid: false,
errors,
warnings,
error_code: None,
};
}
};
let mut legacy_field_hit = false;
for (key, message) in LEGACY_TOMBSTONE_KEYS {
if obj.contains_key(*key) {
errors.push((*message).to_string());
legacy_field_hit = true;
}
}
match obj.get("format") {
None => {}
Some(v) if v.as_u64() == Some(u64::from(MEM_CONFIG_FORMAT)) => {}
Some(v)
if v.as_u64()
.and_then(|n| u32::try_from(n).ok())
.is_some_and(published_format_accepted) => {}
Some(v) => errors.push(format!(
"format: unsupported mem config format {v}: this engine reads format \
{MEM_CONFIG_FORMAT} (an absent key means the same); a higher value was \
written by a newer engine — upgrade before loading this mem"
)),
}
match obj.get("schema") {
Some(Value::String(s)) => {
if let Err(e) = s.parse::<SchemaRef>() {
errors.push(format!("schema: {e}"));
}
}
Some(_) => errors.push(
"schema: must be a string of the form \"<name>@<x.y.z>\" \
(exact version pin, e.g. \"default@1.0.0\")"
.to_string(),
),
None => errors.push(
"Config must declare `schema` — exact pin of the form \
\"<name>@<x.y.z>\" (e.g. \"default@1.0.0\")"
.to_string(),
),
}
if let Some(Value::Object(mems)) = obj.get("readMems") {
for (name, spec) in mems {
let entry_path = format!("readMems.{name}");
let spec_obj = match spec.as_object() {
Some(o) => o,
None => {
errors.push(format!("{entry_path}: read-mem entry must be an object"));
continue;
}
};
let source = match spec_obj.get("source").and_then(|v| v.as_object()) {
Some(s) => s,
None => {
errors.push(format!(
"{entry_path}.source: read-mem entry must declare a source \
(e.g. {{\"type\": \"local\"}} or {{\"type\": \"url\", \"url\": \"…\"}})"
));
continue;
}
};
match source.get("type").and_then(|v| v.as_str()) {
Some("local") => {}
Some("url") => match source.get("url").and_then(|v| v.as_str()) {
Some(u) if !u.is_empty() => {}
_ => errors.push(format!(
"{entry_path}.source.url: url source must declare a non-empty 'url' string"
)),
},
Some(other) => errors.push(format!(
"{entry_path}.source.type: unknown source type '{other}' \
(expected 'local' or 'url')"
)),
None => errors.push(format!(
"{entry_path}.source.type: source must declare a 'type' \
('local' or 'url')"
)),
}
}
}
for key in obj.keys() {
if KNOWN_TOP_LEVEL_KEYS.contains(&key.as_str())
|| LEGACY_TOMBSTONE_KEYS
.iter()
.any(|(k, _)| *k == key.as_str())
{
continue;
}
warnings.push(format!(
"Unknown config key '{key}' \u{2014} will be ignored"
));
}
let error_code = if legacy_field_hit {
Some("LEGACY_FIELD_PRESENT".to_string())
} else {
None
};
ConfigCheckResult {
valid: errors.is_empty(),
errors,
warnings,
error_code,
}
}
pub fn load_config(mem_dir: &Path) -> Result<(Value, PathBuf), ConfigError> {
let config_path = mem_dir.join(MEM_META_DIR).join("config.json");
let raw = std::fs::read_to_string(&config_path).map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
ConfigError::NotFound(config_path.display().to_string())
} else {
ConfigError::Io(e)
}
})?;
let parsed: Value = serde_json::from_str(&raw)
.map_err(|_| ConfigError::InvalidJson(config_path.display().to_string()))?;
Ok((parsed, config_path))
}
pub fn parse_mem_config(value: &Value) -> Result<MemConfig, ConfigError> {
serde_json::from_value(value.clone()).map_err(|e| ConfigError::Other(e.to_string()))
}
pub fn load_and_validate(mem_dir: &Path) -> Result<MemConfig, ConfigError> {
let (raw, _path) = load_config(mem_dir)?;
let result = check_config(&raw);
if !result.valid {
return Err(ConfigError::ValidationFailed(result.errors));
}
parse_mem_config(&raw)
}
fn write_config(config_path: &Path, config: &Value) -> Result<(), ConfigError> {
let json = serde_json::to_string_pretty(config)? + "\n";
std::fs::write(config_path, json)?;
Ok(())
}
fn commit_config(
config_path: &Path,
config: &Value,
dry_run: bool,
) -> Result<ConfigCheckResult, ConfigError> {
let check = check_config(config);
if !check.valid {
return Ok(check);
}
if !dry_run {
write_config(config_path, config)?;
}
Ok(check)
}
const ALLOWED_UPDATE_FIELDS: &[&str] = &[
"version",
"description",
"authors",
"writeGuidance",
"rules",
"readMems",
"schema",
"language",
"publish",
];
const PROTECTED_FIELDS: &[&str] = &["name"];
pub fn update_config_field(
config_path: &Path,
config: &mut Value,
field: &str,
value: Value,
dry_run: bool,
) -> Result<ConfigCheckResult, ConfigError> {
if PROTECTED_FIELDS.contains(&field) {
return Err(ConfigError::Other(format!("Field '{field}' is protected")));
}
let obj = config
.as_object_mut()
.ok_or_else(|| ConfigError::Other("config must be an object".into()))?;
if !ALLOWED_UPDATE_FIELDS.contains(&field) {
return Err(ConfigError::Other(format!(
"Field '{field}' is not a recognized config field. Allowed: {}",
ALLOWED_UPDATE_FIELDS.join(", ")
)));
}
obj.insert(field.to_string(), value);
commit_config(config_path, config, dry_run)
}
#[cfg(test)]
mod tests;