use std::path::{Path, PathBuf};
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::binding::Binding;
use crate::workspace_store::{StoreError, WORKSPACE_STORE_DIR};
pub const PROJECTIONS_DIR: &str = "projections";
pub const PER_MEM_STORE_DIRS: &[&str] = &[PROJECTIONS_DIR, "state/findings", "state/advance"];
pub fn mem_binding_records(
workspace_root: &Path,
mem: &str,
) -> Result<Vec<(String, Vec<u8>)>, StoreError> {
if validate_mem(mem).is_err() {
return Ok(Vec::new());
}
let dir = primitive_dir(workspace_root, PROJECTIONS_DIR).join(mem);
let mut out: Vec<(String, Vec<u8>)> = Vec::new();
for path in record_files(&dir)? {
let Some(name) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
let bytes = std::fs::read(&path).map_err(|e| StoreError::Io {
path: path.clone(),
source: e,
})?;
out.push((name.to_string(), bytes));
}
Ok(out)
}
fn record_files(dir: &Path) -> Result<Vec<PathBuf>, StoreError> {
let mut out: Vec<PathBuf> = Vec::new();
let entries = match std::fs::read_dir(dir) {
Ok(rd) => rd,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
Err(e) => {
return Err(StoreError::Io {
path: dir.to_path_buf(),
source: e,
});
}
};
for entry in entries {
let path = entry
.map_err(|e| StoreError::Io {
path: dir.to_path_buf(),
source: e,
})?
.path();
if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("json") {
out.push(path);
}
}
out.sort();
Ok(out)
}
fn prune_empty_dirs(dir: &Path, stop: &Path) {
let mut current = dir;
while current != stop && current.starts_with(stop) {
if std::fs::remove_dir(current).is_err() {
return;
}
match current.parent() {
Some(parent) => current = parent,
None => return,
}
}
}
pub fn relocate_mem_store(
workspace_root: &Path,
old: &str,
new: &str,
) -> Result<Vec<(String, Vec<u8>)>, StoreError> {
if validate_mem(old).is_err() || validate_mem(new).is_err() {
return Ok(Vec::new());
}
for dir in PER_MEM_STORE_DIRS {
let tier = primitive_dir(workspace_root, dir);
let old_dir = tier.join(old);
let new_dir = tier.join(new);
let old_records = record_files(&old_dir)?;
if !old_records.is_empty() {
std::fs::create_dir_all(&new_dir).map_err(|e| StoreError::Io {
path: new_dir.clone(),
source: e,
})?;
for path in &old_records {
let Some(file_name) = path.file_name() else {
continue;
};
let target = new_dir.join(file_name);
if target.exists() {
continue;
}
std::fs::rename(path, &target).map_err(|e| StoreError::Io {
path: path.clone(),
source: e,
})?;
}
prune_empty_dirs(&old_dir, &tier);
}
for path in record_files(&new_dir)? {
let text = std::fs::read_to_string(&path).map_err(|e| StoreError::Io {
path: path.clone(),
source: e,
})?;
let Ok(mut doc) = serde_json::from_str::<serde_json::Value>(&text) else {
continue;
};
let mut changed = rewrite_mem_ids(&mut doc, old, new);
if *dir == PROJECTIONS_DIR
&& doc.get("destination_mem").and_then(|v| v.as_str()) == Some(old)
{
doc["destination_mem"] = serde_json::Value::String(new.to_string());
changed = true;
}
if changed {
let mut out = serde_json::to_string_pretty(&doc).unwrap_or(text);
out.push('\n');
std::fs::write(&path, out).map_err(|e| StoreError::Io {
path: path.clone(),
source: e,
})?;
}
}
}
mem_binding_records(workspace_root, new)
}
pub fn remove_mem_store(workspace_root: &Path, mem: &str) -> Result<(), StoreError> {
if validate_mem(mem).is_err() {
return Ok(());
}
for dir in PER_MEM_STORE_DIRS {
let tier = primitive_dir(workspace_root, dir);
let mem_dir = tier.join(mem);
for path in record_files(&mem_dir)? {
remove_file(&path)?;
}
prune_empty_dirs(&mem_dir, &tier);
}
Ok(())
}
fn rewrite_mem_ids(value: &mut serde_json::Value, old: &str, new: &str) -> bool {
let slash_old = format!("{old}/");
let dash_old = format!("{old}--");
fn rewrite_str(s: &str, slash_old: &str, dash_old: &str, new: &str) -> Option<String> {
if let Some(rest) = s.strip_prefix(slash_old) {
return Some(format!("{new}/{rest}"));
}
if let Some(rest) = s.strip_prefix(dash_old) {
return Some(format!("{new}--{rest}"));
}
None
}
match value {
serde_json::Value::String(s) => match rewrite_str(s, &slash_old, &dash_old, new) {
Some(r) => {
*s = r;
true
}
None => false,
},
serde_json::Value::Array(items) => {
let mut changed = false;
for item in items {
changed |= rewrite_mem_ids(item, old, new);
}
changed
}
serde_json::Value::Object(map) => {
let mut changed = false;
let keys: Vec<String> = map.keys().cloned().collect();
for key in keys {
let mut inner = map.remove(&key).expect("key present");
changed |= rewrite_mem_ids(&mut inner, old, new);
let new_key = match rewrite_str(&key, &slash_old, &dash_old, new) {
Some(r) => {
changed = true;
r
}
None => key,
};
map.insert(new_key, inner);
}
changed
}
_ => false,
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct MemPipelineRecord<T> {
pub mem: String,
pub name: String,
pub config: T,
}
#[derive(Debug, Default, Clone, PartialEq, Serialize)]
pub struct BindingConfigs {
pub bindings: Vec<MemPipelineRecord<Binding>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub quarantined: Vec<QuarantinedBinding>,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum BindingLookupError {
#[error(
"binding `{binding}` is quarantined — its stored file failed the load and it serves \
no operations until repaired: [{reason_code}] {reason_message}"
)]
Quarantined {
binding: String,
reason_code: String,
reason_message: String,
path: String,
},
#[error("no active binding: no consuming brief render has published one")]
NoActive,
#[error("no binding `{binding}` in this workspace")]
NotFound {
binding: String,
available: Vec<String>,
},
}
impl BindingLookupError {
pub fn code(&self) -> &'static str {
match self {
BindingLookupError::Quarantined { .. } => "PROJECTION_QUARANTINED",
BindingLookupError::NotFound { .. } => "PROJECTION_NOT_FOUND",
BindingLookupError::NoActive => "NO_ACTIVE_BINDING",
}
}
pub fn details(&self) -> serde_json::Value {
match self {
BindingLookupError::Quarantined {
binding,
reason_code,
reason_message,
path,
} => serde_json::json!({
"binding": binding,
"reason_code": reason_code,
"reason_message": reason_message,
"path": path,
}),
BindingLookupError::NoActive => serde_json::json!({}),
BindingLookupError::NotFound { binding, available } => serde_json::json!({
"binding": binding,
"available": available,
}),
}
}
}
impl BindingConfigs {
pub fn lookup_error(&self, binding_id: &str) -> BindingLookupError {
if let Some(q) = self
.quarantined
.iter()
.find(|q| format!("{}/{}", q.mem, q.name) == binding_id)
{
return BindingLookupError::Quarantined {
binding: binding_id.to_string(),
reason_code: q.reason_code.clone(),
reason_message: q.reason_message.clone(),
path: q.path.clone(),
};
}
let mut available: Vec<String> = self
.bindings
.iter()
.map(|r| format!("{}/{}", r.mem, r.name))
.collect();
available.sort();
BindingLookupError::NotFound {
binding: binding_id.to_string(),
available,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct QuarantinedBinding {
pub mem: String,
pub name: String,
pub path: String,
pub reason_code: String,
pub reason_message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unknown_version: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parse_message: Option<String>,
}
fn primitive_dir(workspace_root: &Path, primitive: &str) -> PathBuf {
workspace_root.join(WORKSPACE_STORE_DIR).join(primitive)
}
pub fn is_single_component(value: &str) -> bool {
!value.is_empty()
&& value != "."
&& value != ".."
&& !value.contains('/')
&& !value.contains('\\')
&& !value.contains(':')
&& !value.contains('\0')
}
pub fn is_mem_path(value: &str) -> bool {
!value.is_empty() && value.split('/').all(is_single_component)
}
pub fn parse_binding_id(binding_id: &str) -> Option<(&str, &str)> {
binding_id
.rsplit_once('/')
.filter(|(mem, stem)| is_mem_path(mem) && is_single_component(stem))
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum BindingIdError {
#[error(
"invalid mem '{}': must be a mem name (plain path components joined by '/'; \
no traversal segments, backslashes, ':' or NUL)",
value.escape_default()
)]
Mem { value: String },
#[error(
"invalid name '{}': must be a single path component (no separators, \
traversal segments, ':' or NUL)",
value.escape_default()
)]
Name { value: String },
#[error(
"invalid binding id '{}': expected `<mem>/<stem>`, the stem a single path \
component after the last '/', the mem a mem name (a nested `team/sub-mem` \
is fine; no traversal segments, ':' or NUL anywhere)",
binding.escape_default()
)]
Id { binding: String },
}
impl BindingIdError {
pub fn code(&self) -> &'static str {
match self {
BindingIdError::Mem { .. }
| BindingIdError::Name { .. }
| BindingIdError::Id { .. } => "PROJECTION_INVALID_NAME",
}
}
pub fn details(&self) -> serde_json::Value {
match self {
BindingIdError::Mem { value } => serde_json::json!({ "kind": "mem", "value": value }),
BindingIdError::Name { value } => serde_json::json!({ "kind": "name", "value": value }),
BindingIdError::Id { binding } => serde_json::json!({ "binding": binding }),
}
}
}
pub fn check_binding_parts(mem: &str, stem: &str) -> Result<(), BindingIdError> {
if !is_mem_path(mem) {
return Err(BindingIdError::Mem {
value: mem.to_string(),
});
}
if !is_single_component(stem) {
return Err(BindingIdError::Name {
value: stem.to_string(),
});
}
Ok(())
}
pub fn parse_binding_id_or_refuse(binding_id: &str) -> Result<(&str, &str), BindingIdError> {
parse_binding_id(binding_id).ok_or_else(|| BindingIdError::Id {
binding: binding_id.to_string(),
})
}
fn validate_component(kind: &str, value: &str) -> Result<(), StoreError> {
if !is_single_component(value) {
return Err(StoreError::Other(format!(
"invalid {kind} '{}': must be a single path component \
(no separators, traversal segments, ':' or NUL)",
value.escape_default()
)));
}
Ok(())
}
fn validate_mem(mem: &str) -> Result<(), StoreError> {
if !is_mem_path(mem) {
return Err(StoreError::Other(format!(
"invalid mem '{}': must be a mem name (plain path components \
joined by '/'; no traversal segments, backslashes, ':' or NUL)",
mem.escape_default()
)));
}
Ok(())
}
fn mem_scoped_path(
workspace_root: &Path,
primitive: &str,
mem: &str,
name: &str,
) -> Result<PathBuf, StoreError> {
validate_mem(mem)?;
validate_component("name", name)?;
Ok(primitive_dir(workspace_root, primitive)
.join(mem)
.join(format!("{name}.json")))
}
fn remove_file(path: &Path) -> Result<(), StoreError> {
std::fs::remove_file(path).map_err(|e| StoreError::Io {
path: path.to_path_buf(),
source: e,
})
}
fn rename_file(from: &Path, to: &Path) -> Result<(), StoreError> {
if to.exists() {
return Err(StoreError::Other(format!(
"rename target already exists: {}",
to.display()
)));
}
std::fs::rename(from, to).map_err(|e| StoreError::Io {
path: from.to_path_buf(),
source: e,
})
}
fn write_json<T: Serialize>(path: &Path, config: &T) -> Result<(), StoreError> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| StoreError::Io {
path: parent.to_path_buf(),
source: e,
})?;
}
let bytes = serde_json::to_vec_pretty(config).map_err(|e| StoreError::Parse {
path: path.to_path_buf(),
message: e.to_string(),
})?;
std::fs::write(path, bytes).map_err(|e| StoreError::Io {
path: path.to_path_buf(),
source: e,
})
}
fn read_json<T: DeserializeOwned>(path: &Path) -> Result<T, StoreError> {
let bytes = std::fs::read(path).map_err(|e| StoreError::Io {
path: path.to_path_buf(),
source: e,
})?;
serde_json::from_slice(&bytes).map_err(|e| StoreError::Parse {
path: path.to_path_buf(),
message: e.to_string(),
})
}
pub fn write_binding(
workspace_root: &Path,
mem: &str,
name: &str,
binding: &Binding,
) -> Result<(), StoreError> {
write_json(
&mem_scoped_path(workspace_root, PROJECTIONS_DIR, mem, name)?,
binding,
)
}
pub fn read_binding(workspace_root: &Path, mem: &str, name: &str) -> Result<Binding, StoreError> {
read_json(&mem_scoped_path(
workspace_root,
PROJECTIONS_DIR,
mem,
name,
)?)
}
pub fn delete_projection(workspace_root: &Path, mem: &str, name: &str) -> Result<(), StoreError> {
remove_file(&mem_scoped_path(
workspace_root,
PROJECTIONS_DIR,
mem,
name,
)?)
}
pub fn rename_projection(
workspace_root: &Path,
mem: &str,
old: &str,
new: &str,
) -> Result<(), StoreError> {
rename_file(
&mem_scoped_path(workspace_root, PROJECTIONS_DIR, mem, old)?,
&mem_scoped_path(workspace_root, PROJECTIONS_DIR, mem, new)?,
)
}
fn load_bindings(
workspace_root: &Path,
) -> Result<(Vec<MemPipelineRecord<Binding>>, Vec<QuarantinedBinding>), StoreError> {
let dir = primitive_dir(workspace_root, PROJECTIONS_DIR);
let mut out: Vec<MemPipelineRecord<Binding>> = Vec::new();
let mut quarantined: Vec<QuarantinedBinding> = Vec::new();
walk_mem_tier(&dir, "", &mut out, &mut quarantined)?;
out.sort_by(|a, b| (a.mem.as_str(), a.name.as_str()).cmp(&(b.mem.as_str(), b.name.as_str())));
quarantined
.sort_by(|a, b| (a.mem.as_str(), a.name.as_str()).cmp(&(b.mem.as_str(), b.name.as_str())));
Ok((out, quarantined))
}
fn walk_mem_tier(
dir: &Path,
mem: &str,
out: &mut Vec<MemPipelineRecord<Binding>>,
quarantined: &mut Vec<QuarantinedBinding>,
) -> Result<(), StoreError> {
let entries = match std::fs::read_dir(dir) {
Ok(rd) => rd,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => {
return Err(StoreError::Io {
path: dir.to_path_buf(),
source: e,
});
}
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let child = entry.file_name().to_string_lossy().into_owned();
let child_mem = if mem.is_empty() {
child
} else {
format!("{mem}/{child}")
};
walk_mem_tier(&path, &child_mem, out, quarantined)?;
continue;
}
if mem.is_empty() || path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
let Some(name) = path.file_stem().map(|s| s.to_string_lossy().into_owned()) else {
continue;
};
load_binding_file(&path, mem, name, out, quarantined);
}
Ok(())
}
fn load_binding_file(
path: &Path,
mem: &str,
name: String,
out: &mut Vec<MemPipelineRecord<Binding>>,
quarantined: &mut Vec<QuarantinedBinding>,
) {
let quarantine = |q: &mut Vec<QuarantinedBinding>, name: String, e: StoreError| {
let (unknown_version, parse_message) = match &e {
StoreError::UnknownBindingVersion { version, .. } => (Some(*version), None),
StoreError::Parse { message, .. } => (None, Some(message.clone())),
_ => (None, None),
};
q.push(QuarantinedBinding {
mem: mem.to_string(),
name,
path: path.display().to_string(),
reason_code: e.code().to_string(),
reason_message: e.to_string(),
unknown_version,
parse_message,
});
};
let value: serde_json::Value = match read_json(path) {
Ok(v) => v,
Err(e) => {
quarantine(quarantined, name, e);
return;
}
};
let gate_err = match value.get("version") {
None => Some(StoreError::LegacyProjectionStore {
path: path.to_path_buf(),
}),
Some(v) => match v.as_i64() {
Some(1) => Some(StoreError::LegacyProjectionStore {
path: path.to_path_buf(),
}),
n if n != Some(i64::from(crate::binding::BINDING_VERSION)) => {
Some(StoreError::UnknownBindingVersion {
path: path.to_path_buf(),
version: n.unwrap_or(-1),
})
}
_ => None,
},
};
if let Some(e) = gate_err {
quarantine(quarantined, name, e);
return;
}
let config: Binding = match serde_json::from_value(value) {
Ok(c) => c,
Err(e) => {
quarantine(
quarantined,
name,
StoreError::Parse {
path: path.to_path_buf(),
message: e.to_string(),
},
);
return;
}
};
out.push(MemPipelineRecord {
mem: mem.to_string(),
name,
config,
});
}
pub fn load_pipeline_configs(workspace_root: &Path) -> Result<BindingConfigs, StoreError> {
let (bindings, quarantined) = load_bindings(workspace_root)?;
Ok(BindingConfigs {
bindings,
quarantined,
})
}
pub fn load_pipeline_configs_strict(workspace_root: &Path) -> Result<BindingConfigs, StoreError> {
let configs = load_pipeline_configs(workspace_root)?;
if let Some(q) = configs.quarantined.first() {
let path = PathBuf::from(&q.path);
return Err(match q.reason_code.as_str() {
"UNKNOWN_BINDING_VERSION" => StoreError::UnknownBindingVersion {
path,
version: q.unknown_version.unwrap_or(-1),
},
"WORKSPACE_STORE_PARSE" => StoreError::Parse {
path,
message: q.parse_message.clone().unwrap_or_default(),
},
_ => StoreError::LegacyProjectionStore { path },
});
}
Ok(configs)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pipeline::{MediumType, PatternEntry, PatternMode};
use tempfile::TempDir;
#[test]
fn mutations_refuse_traversal_in_mem_and_name() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let binding = sample_binding();
let evil_components = [
"..",
".",
"",
"../escape",
"a\\b",
"..\\up",
"c:evil",
"nul\0byte",
];
for evil in evil_components {
assert!(
write_binding(root, evil, "ok", &binding).is_err(),
"mem '{}' must refuse",
evil.escape_default()
);
assert!(
write_binding(root, "ok", evil, &binding).is_err(),
"name '{}' must refuse",
evil.escape_default()
);
assert!(delete_projection(root, evil, "ok").is_err());
assert!(delete_projection(root, "ok", evil).is_err());
assert!(rename_projection(root, evil, "a", "b").is_err());
assert!(rename_projection(root, "ok", evil, "b").is_err());
assert!(rename_projection(root, "ok", "a", evil).is_err());
}
for evil_mem in ["library/../escape", "library/..", "a//b", "/a", "a/"] {
assert!(
write_binding(root, evil_mem, "ok", &binding).is_err(),
"mem '{}' must refuse",
evil_mem.escape_default()
);
assert!(delete_projection(root, evil_mem, "ok").is_err());
assert!(rename_projection(root, evil_mem, "a", "b").is_err());
}
assert!(write_binding(root, "ok", "a/b", &binding).is_err());
assert!(delete_projection(root, "ok", "a/b").is_err());
assert!(rename_projection(root, "ok", "a/b", "c").is_err());
assert!(rename_projection(root, "ok", "a", "b/c").is_err());
assert!(
!root.parent().unwrap().join("escape.json").exists(),
"no write may land outside the workspace"
);
write_binding(root, "engine", "graph", &binding).unwrap();
assert!(
root.join(".memstead/projections/engine/graph.json")
.is_file()
);
}
#[test]
fn nested_mem_names_nest_the_store_tier() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let binding = sample_binding();
write_binding(root, "library/sample", "notes", &binding).unwrap();
assert!(
root.join(".memstead/projections/library/sample/notes.json")
.is_file(),
"the record lands under the nested tier"
);
let back = read_binding(root, "library/sample", "notes").unwrap();
assert_eq!(back, binding);
let configs = load_pipeline_configs(root).unwrap();
let keys: Vec<_> = configs
.bindings
.iter()
.map(|r| (r.mem.as_str(), r.name.as_str()))
.collect();
assert_eq!(keys, vec![("library/sample", "notes")]);
write_binding(root, "library", "index", &binding).unwrap();
let names = |mem: &str| -> Vec<String> {
mem_binding_records(root, mem)
.unwrap()
.into_iter()
.map(|(n, _)| n)
.collect()
};
assert_eq!(names("library/sample"), vec!["notes".to_string()]);
assert_eq!(names("library"), vec!["index".to_string()]);
let configs = load_pipeline_configs(root).unwrap();
let keys: Vec<_> = configs
.bindings
.iter()
.map(|r| (r.mem.as_str(), r.name.as_str()))
.collect();
assert_eq!(
keys,
vec![("library", "index"), ("library/sample", "notes")]
);
rename_projection(root, "library/sample", "notes", "notes-2").unwrap();
assert!(
root.join(".memstead/projections/library/sample/notes-2.json")
.is_file()
);
remove_mem_store(root, "library").unwrap();
assert!(
!root
.join(".memstead/projections/library/index.json")
.exists(),
"the parent path's own record is gone"
);
assert!(
root.join(".memstead/projections/library/sample/notes-2.json")
.is_file(),
"a nested mem's tier survives the parent path's removal"
);
remove_mem_store(root, "library/sample").unwrap();
assert!(
!root.join(".memstead/projections/library").exists(),
"emptied tiers are pruned up to the projections root"
);
assert!(root.join(".memstead/projections").is_dir());
}
#[test]
fn relocate_moves_only_the_named_mems_records() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let binding = sample_binding();
write_binding(root, "library", "index", &binding).unwrap();
write_binding(root, "library/sample", "notes", &binding).unwrap();
let moved = relocate_mem_store(root, "library", "evidence").unwrap();
assert_eq!(moved.len(), 1);
assert_eq!(moved[0].0, "index");
assert!(
root.join(".memstead/projections/evidence/index.json")
.is_file()
);
assert!(
root.join(".memstead/projections/library/sample/notes.json")
.is_file(),
"the nested mem is another mem and does not move"
);
let moved = relocate_mem_store(root, "library/sample", "library/other").unwrap();
assert_eq!(moved[0].0, "notes");
assert!(
root.join(".memstead/projections/library/other/notes.json")
.is_file()
);
assert!(!root.join(".memstead/projections/library/sample").exists());
}
#[test]
fn parse_binding_id_splits_at_the_last_separator() {
assert_eq!(parse_binding_id("engine/graph"), Some(("engine", "graph")));
assert_eq!(
parse_binding_id("library/sample/notes"),
Some(("library/sample", "notes"))
);
assert_eq!(
parse_binding_id("planning/plan-first-sample/notes"),
Some(("planning/plan-first-sample", "notes"))
);
for malformed in [
"noslash",
"",
"/graph",
"engine/",
"engine//graph",
"../escape",
"library/../graph",
"library/./graph",
"library/sample/..",
"a\\b/graph",
"c:evil/graph",
] {
assert_eq!(
parse_binding_id(malformed),
None,
"'{}' must refuse",
malformed.escape_default()
);
}
assert!(is_mem_path("library"));
assert!(is_mem_path("library/sample"));
assert!(!is_mem_path("library/../x"));
assert!(!is_mem_path(""));
assert!(is_single_component("notes"));
assert!(!is_single_component("library/notes"));
}
#[test]
fn load_enumeration_is_sorted_and_per_mem() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let binding = sample_binding();
write_binding(root, "engine", "z-binding", &binding).unwrap();
write_binding(root, "engine", "a-binding", &binding).unwrap();
write_binding(root, "macos", "m-binding", &binding).unwrap();
let configs = load_pipeline_configs(root).unwrap();
let keys: Vec<_> = configs
.bindings
.iter()
.map(|r| (r.mem.as_str(), r.name.as_str()))
.collect();
assert_eq!(
keys,
vec![
("engine", "a-binding"),
("engine", "z-binding"),
("macos", "m-binding"),
]
);
}
#[test]
fn malformed_config_surfaces_typed_parse_error_naming_the_file() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let bad = root.join(".memstead/projections/macos");
std::fs::create_dir_all(&bad).unwrap();
std::fs::write(bad.join("broken.json"), b"{ not valid json").unwrap();
let configs = load_pipeline_configs(root).unwrap();
assert_eq!(configs.quarantined.len(), 1);
assert_eq!(configs.quarantined[0].reason_code, "WORKSPACE_STORE_PARSE");
let err = load_pipeline_configs_strict(root).unwrap_err();
match err {
StoreError::Parse { path, .. } => {
assert!(path.ends_with("broken.json"), "got {path:?}");
}
other => panic!("expected Parse error, got {other:?}"),
}
}
#[test]
fn delete_removes_the_record_and_load_reflects_it() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
write_binding(root, "engine", "graph", &sample_binding()).unwrap();
delete_projection(root, "engine", "graph").unwrap();
assert!(
!root
.join(".memstead/projections/engine/graph.json")
.exists()
);
let configs = load_pipeline_configs(root).unwrap();
assert!(configs.bindings.is_empty());
}
#[test]
fn delete_of_missing_record_surfaces_io_error() {
let tmp = TempDir::new().unwrap();
let err = delete_projection(tmp.path(), "engine", "nope").unwrap_err();
match err {
StoreError::Io { source, .. } => {
assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
}
other => panic!("expected Io error, got {other:?}"),
}
}
#[test]
fn rename_moves_the_record_preserving_config() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let binding = sample_binding();
write_binding(root, "engine", "old-name", &binding).unwrap();
rename_projection(root, "engine", "old-name", "new-name").unwrap();
assert!(
!root
.join(".memstead/projections/engine/old-name.json")
.exists()
);
let configs = load_pipeline_configs(root).unwrap();
assert_eq!(configs.bindings.len(), 1);
assert_eq!(configs.bindings[0].name, "new-name");
assert_eq!(configs.bindings[0].config, binding);
}
#[test]
fn rename_refuses_to_clobber_an_existing_target() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let binding = sample_binding();
write_binding(root, "engine", "a", &binding).unwrap();
write_binding(root, "engine", "b", &binding).unwrap();
let err = rename_projection(root, "engine", "a", "b").unwrap_err();
assert!(matches!(err, StoreError::Other(_)), "got {err:?}");
assert!(root.join(".memstead/projections/engine/a.json").exists());
assert!(root.join(".memstead/projections/engine/b.json").exists());
}
#[test]
fn rename_of_missing_source_surfaces_io_error() {
let tmp = TempDir::new().unwrap();
let err = rename_projection(tmp.path(), "engine", "missing", "whatever").unwrap_err();
assert!(matches!(err, StoreError::Io { .. }), "got {err:?}");
}
fn sample_binding() -> Binding {
use crate::binding::{BINDING_VERSION, BuildMode, BuildOperation, Operations};
use crate::pipeline::{IngestTrigger, Source};
Binding {
version: BINDING_VERSION,
intent: Some("prose".to_string()),
sources: vec![Source {
name: "source-tree".to_string(),
medium_type: MediumType::Codebase,
pointer: "../public".to_string(),
change_detection: None,
scope: vec![PatternEntry {
path: "../public/**/*.rs".to_string(),
mode: PatternMode::Allow,
}],
engagement: None,
preparation: None,
}],
reference_mems: vec![],
destination_mem: "engine".to_string(),
deny_paths: vec![],
coverage_semantics: None,
rules: None,
prune: None,
operations: Operations {
build: Some(BuildOperation {
mode: BuildMode::Discovery,
trigger: IngestTrigger::Loop,
batch_size: 20,
post_actions: None,
}),
sync: None,
verify: None,
},
}
}
#[test]
fn empty_store_loads_empty_binding_configs() {
let tmp = TempDir::new().unwrap();
let configs = load_pipeline_configs(tmp.path()).unwrap();
assert_eq!(configs, BindingConfigs::default());
}
#[test]
fn binding_loader_round_trips_a_v2_binding() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let binding = sample_binding();
write_binding(root, "engine", "graph", &binding).unwrap();
let configs = load_pipeline_configs(root).unwrap();
assert_eq!(configs.bindings.len(), 1);
assert_eq!(configs.bindings[0].mem, "engine");
assert_eq!(configs.bindings[0].name, "graph");
assert_eq!(configs.bindings[0].config, binding);
}
#[test]
fn version_less_projection_refuses_as_retired_format() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let dir = root.join(".memstead/projections/engine");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("graph.json"),
br#"{"intent": "legacy", "source_facets": ["f"], "reference_mems": [], "destination_mem": "engine"}"#,
)
.unwrap();
let err = load_pipeline_configs_strict(root).unwrap_err();
match err {
StoreError::LegacyProjectionStore { path } => {
assert!(path.ends_with("graph.json"), "got {path:?}");
let msg = err_message(&StoreError::LegacyProjectionStore { path });
assert!(msg.contains("retired binding format"), "got {msg}");
assert!(msg.contains("memstead projection init"), "got {msg}");
assert!(!msg.contains("projection migrate"), "got {msg}");
}
other => panic!("expected LegacyProjectionStore, got {other:?}"),
}
}
#[test]
fn v1_binding_refuses_as_retired_format() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let dir = root.join(".memstead/projections/engine");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("graph.json"),
br#"{"version": 1, "source_facets": ["source-tree"], "destination_mem": "engine", "operations": {"build": {"mode": "discovery", "trigger": "loop", "batch_size": 20}}}"#,
)
.unwrap();
let err = load_pipeline_configs_strict(root).unwrap_err();
match err {
StoreError::LegacyProjectionStore { path } => {
assert!(path.ends_with("graph.json"), "got {path:?}");
let msg = err_message(&StoreError::LegacyProjectionStore { path });
assert!(msg.contains("retired binding format"), "got {msg}");
assert!(msg.contains("memstead projection init"), "got {msg}");
}
other => panic!("expected LegacyProjectionStore, got {other:?}"),
}
}
#[test]
fn unknown_binding_version_refuses() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let dir = root.join(".memstead/projections/engine");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("graph.json"),
br#"{"version": 99, "destination_mem": "engine", "operations": {"build": {"mode": "discovery", "trigger": "loop", "batch_size": 20}}}"#,
)
.unwrap();
let err = load_pipeline_configs_strict(root).unwrap_err();
assert!(
matches!(err, StoreError::UnknownBindingVersion { version: 99, .. }),
"got {err:?}"
);
}
fn err_message(e: &StoreError) -> String {
e.to_string()
}
}