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";
#[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, 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)
}
fn validate_component(kind: &str, value: &str) -> Result<(), StoreError> {
let invalid = value.is_empty()
|| value == "."
|| value == ".."
|| value.contains('/')
|| value.contains('\\')
|| value.contains(':')
|| value.contains('\0');
if invalid {
return Err(StoreError::Other(format!(
"invalid {kind} '{}': must be a single path component \
(no separators, traversal segments, ':' or NUL)",
value.escape_default()
)));
}
Ok(())
}
fn mem_scoped_path(
workspace_root: &Path,
primitive: &str,
mem: &str,
name: &str,
) -> Result<PathBuf, StoreError> {
validate_component("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();
let mem_dirs = match std::fs::read_dir(&dir) {
Ok(rd) => rd,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((out, quarantined)),
Err(e) => {
return Err(StoreError::Io {
path: dir,
source: e,
});
}
};
for mem_entry in mem_dirs.flatten() {
let mem_path = mem_entry.path();
if !mem_path.is_dir() {
continue;
}
let mem = mem_entry.file_name().to_string_lossy().into_owned();
let files = match std::fs::read_dir(&mem_path) {
Ok(rd) => rd,
Err(e) => {
return Err(StoreError::Io {
path: mem_path,
source: e,
});
}
};
for file in files.flatten() {
let path = file.path();
if 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;
};
let path_display = path.display().to_string();
let quarantine =
|q: &mut Vec<QuarantinedBinding>, mem: &str, 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.clone(),
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(&mut quarantined, &mem, name, e);
continue;
}
};
let gate_err = match value.get("version") {
None => Some(StoreError::LegacyProjectionStore { path: path.clone() }),
Some(v) => match v.as_i64() {
Some(1) => Some(StoreError::LegacyProjectionStore { path: path.clone() }),
n if n != Some(i64::from(crate::binding::BINDING_VERSION)) => {
Some(StoreError::UnknownBindingVersion {
path: path.clone(),
version: n.unwrap_or(-1),
})
}
_ => None,
},
};
if let Some(e) = gate_err {
quarantine(&mut quarantined, &mem, name, e);
continue;
}
let config: Binding = match serde_json::from_value(value) {
Ok(c) => c,
Err(e) => {
quarantine(
&mut quarantined,
&mem,
name,
StoreError::Parse {
path: path.clone(),
message: e.to_string(),
},
);
continue;
}
};
out.push(MemPipelineRecord {
mem: mem.clone(),
name,
config,
});
}
}
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))
}
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_values = [
"..",
".",
"",
"../escape",
"a/b",
"a\\b",
"..\\up",
"c:evil",
"nul\0byte",
];
for evil in evil_values {
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());
}
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 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()
}
}