pub mod git;
pub mod index;
pub mod queue;
pub mod state;
pub mod projects;
mod node;
mod slug;
pub use node::{Node, NodeType, Scope};
pub use node::is_valid_slug;
pub use slug::slugify;
use std::path::{Path, PathBuf};
use crate::errors::CoreError;
pub(crate) const IGNORED_ENTRIES: &[&str] = &[
"index.db",
"index.db-wal",
"index.db-shm",
"health.json",
"queue/",
"state/",
"run.lock",
"backups/",
"retro.db",
"retro.db-wal",
"retro.db-shm",
"retro.db.backup",
"audit.jsonl",
"runner.log",
"runner.log.1",
"briefings/",
"hook-stderr.log",
"warnings.log",
];
pub fn gitignore_content() -> String {
let mut content = IGNORED_ENTRIES.join("\n");
content.push('\n');
content
}
pub struct LoadResult {
pub nodes: Vec<(PathBuf, Node)>,
pub warnings: Vec<String>,
}
pub struct Store {
root: PathBuf,
}
impl Store {
pub fn open(root: impl Into<PathBuf>) -> Self {
Store { root: root.into() }
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn knowledge_dir(&self) -> PathBuf {
self.root.join("knowledge")
}
fn scope_dir(&self, scope: &Scope) -> PathBuf {
match scope {
Scope::Global => self.knowledge_dir().join("global"),
Scope::Project(slug) => self.knowledge_dir().join("projects").join(slug),
}
}
pub fn node_path(&self, scope: &Scope, id: &str) -> PathBuf {
self.scope_dir(scope).join(format!("{id}.md"))
}
pub fn ensure_layout(&self) -> Result<(), CoreError> {
let io = |e: std::io::Error| CoreError::Io(e.to_string());
std::fs::create_dir_all(self.knowledge_dir().join("global")).map_err(io)?;
std::fs::create_dir_all(self.knowledge_dir().join("projects")).map_err(io)?;
let gitignore = self.root.join(".gitignore");
if !gitignore.exists() {
std::fs::write(&gitignore, gitignore_content()).map_err(io)?;
}
Ok(())
}
pub fn write_node(&self, node: &Node) -> Result<PathBuf, CoreError> {
let io = |e: std::io::Error| CoreError::Io(e.to_string());
let path = self.node_path(&node.scope, &node.id);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(io)?;
}
std::fs::write(&path, node.to_markdown()).map_err(io)?;
Ok(path)
}
pub fn get(&self, scope: &Scope, id: &str) -> Result<Option<Node>, CoreError> {
if !is_valid_slug(id) {
return Ok(None);
}
let path = self.node_path(scope, id);
if !path.exists() {
return Ok(None);
}
let content = std::fs::read_to_string(&path).map_err(|e| CoreError::Io(e.to_string()))?;
let node = Node::from_markdown(&content).map_err(|e| match e {
CoreError::Parse(msg) => CoreError::Parse(format!("{}: {}", path.display(), msg)),
other => other,
})?;
Ok(Some(node))
}
pub fn load_all(&self) -> Result<LoadResult, CoreError> {
let mut result = LoadResult {
nodes: Vec::new(),
warnings: Vec::new(),
};
let mut dirs = vec![self.knowledge_dir().join("global")];
let projects_dir = self.knowledge_dir().join("projects");
if projects_dir.is_dir() {
let entries =
std::fs::read_dir(&projects_dir).map_err(|e| CoreError::Io(e.to_string()))?;
for entry in entries.flatten() {
if entry.path().is_dir() {
dirs.push(entry.path());
}
}
}
for dir in dirs {
if !dir.is_dir() {
continue;
}
let entries = std::fs::read_dir(&dir).map_err(|e| CoreError::Io(e.to_string()))?;
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("md") {
continue;
}
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(e) => {
result.warnings.push(format!("{}: {}", path.display(), e));
continue;
}
};
match Node::from_markdown(&content) {
Ok(node) => {
let canonical = self.node_path(&node.scope, &node.id);
if path != canonical {
result.warnings.push(format!(
"{}: declares {}/{} which belongs at {} — skipped",
path.display(),
node.scope,
node.id,
canonical.display()
));
continue;
}
result.nodes.push((path, node));
}
Err(e) => {
result.warnings.push(format!("{}: {}", path.display(), e));
}
}
}
}
Ok(result)
}
pub fn unique_slug(&self, base: &str, scope: &Scope) -> String {
let slug = slugify(base);
if !self.node_path(scope, &slug).exists() {
return slug;
}
let mut i = 2;
loop {
let candidate = format!("{slug}-{i}");
if !self.node_path(scope, &candidate).exists() {
return candidate;
}
i += 1;
}
}
pub fn invalidate(&self, scope: &Scope, id: &str, by: &str) -> Result<bool, CoreError> {
let Some(mut node) = self.get(scope, id)? else {
return Ok(false);
};
node.invalidated_by = Some(by.to_string());
node.updated = chrono::Utc::now().date_naive();
self.write_node(&node)?;
Ok(true)
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::NaiveDate;
use tempfile::TempDir;
fn node(id: &str, scope: Scope) -> Node {
Node {
id: id.to_string(),
scope,
node_type: NodeType::Rule,
confidence: 0.8,
sources: vec!["session:abc".to_string()],
created: NaiveDate::from_ymd_opt(2026, 7, 1).unwrap(),
updated: NaiveDate::from_ymd_opt(2026, 7, 1).unwrap(),
invalidated_by: None,
body: "Test rule body.".to_string(),
}
}
#[test]
fn ensure_layout_creates_dirs_and_gitignore() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path());
store.ensure_layout().unwrap();
assert!(tmp.path().join("knowledge/global").is_dir());
assert!(tmp.path().join("knowledge/projects").is_dir());
let gi = std::fs::read_to_string(tmp.path().join(".gitignore")).unwrap();
assert!(gi.contains("index.db"));
assert!(gi.contains("queue/"));
std::fs::write(tmp.path().join(".gitignore"), "custom\n").unwrap();
store.ensure_layout().unwrap();
let gi = std::fs::read_to_string(tmp.path().join(".gitignore")).unwrap();
assert_eq!(gi, "custom\n");
}
#[test]
fn node_paths_by_scope() {
let store = Store::open("/tmp/x");
assert_eq!(
store.node_path(&Scope::Global, "my-rule"),
std::path::Path::new("/tmp/x/knowledge/global/my-rule.md")
);
assert_eq!(
store.node_path(&Scope::Project("proj".to_string()), "my-rule"),
std::path::Path::new("/tmp/x/knowledge/projects/proj/my-rule.md")
);
}
#[test]
fn write_then_load_roundtrip() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path());
store.ensure_layout().unwrap();
let g = node("global-rule", Scope::Global);
let p = node("proj-rule", Scope::Project("my-proj".to_string()));
store.write_node(&g).unwrap();
store.write_node(&p).unwrap();
let result = store.load_all().unwrap();
assert_eq!(result.warnings.len(), 0);
assert_eq!(result.nodes.len(), 2);
let ids: Vec<&str> = result.nodes.iter().map(|(_, n)| n.id.as_str()).collect();
assert!(ids.contains(&"global-rule"));
assert!(ids.contains(&"proj-rule"));
}
#[test]
fn load_all_skips_unparseable_with_warning() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path());
store.ensure_layout().unwrap();
store.write_node(&node("good", Scope::Global)).unwrap();
std::fs::write(
tmp.path().join("knowledge/global/broken.md"),
"not a node at all",
)
.unwrap();
let result = store.load_all().unwrap();
assert_eq!(result.nodes.len(), 1);
assert_eq!(result.warnings.len(), 1);
assert!(result.warnings[0].contains("broken.md"));
}
#[test]
fn load_all_ignores_non_md_files() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path());
store.ensure_layout().unwrap();
std::fs::write(tmp.path().join("knowledge/global/.DS_Store"), "junk").unwrap();
let result = store.load_all().unwrap();
assert!(result.nodes.is_empty());
assert!(result.warnings.is_empty());
}
#[test]
fn get_reads_single_node() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path());
store.ensure_layout().unwrap();
store.write_node(&node("findable", Scope::Global)).unwrap();
assert!(store.get(&Scope::Global, "findable").unwrap().is_some());
assert!(store.get(&Scope::Global, "missing").unwrap().is_none());
}
#[test]
fn unique_slug_appends_counter_on_collision() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path());
store.ensure_layout().unwrap();
assert_eq!(store.unique_slug("My Rule", &Scope::Global), "my-rule");
store.write_node(&node("my-rule", Scope::Global)).unwrap();
assert_eq!(store.unique_slug("My Rule", &Scope::Global), "my-rule-2");
store.write_node(&node("my-rule-2", Scope::Global)).unwrap();
assert_eq!(store.unique_slug("My Rule", &Scope::Global), "my-rule-3");
assert_eq!(
store.unique_slug("My Rule", &Scope::Project("p".to_string())),
"my-rule"
);
}
#[test]
fn load_all_skips_copied_duplicate_with_warning() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path());
store.ensure_layout().unwrap();
store.write_node(&node("original", Scope::Global)).unwrap();
std::fs::copy(
tmp.path().join("knowledge/global/original.md"),
tmp.path().join("knowledge/global/original-copy.md"),
)
.unwrap();
let result = store.load_all().unwrap();
assert_eq!(result.nodes.len(), 1);
assert_eq!(result.warnings.len(), 1);
assert!(
result.warnings[0].contains("original-copy.md"),
"got: {:?}",
result.warnings
);
}
#[test]
fn load_all_skips_misplaced_scope_with_warning() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path());
store.ensure_layout().unwrap();
let n = node("misplaced", Scope::Project("other-proj".to_string()));
std::fs::write(
tmp.path().join("knowledge/global/misplaced.md"),
n.to_markdown(),
)
.unwrap();
let result = store.load_all().unwrap();
assert!(result.nodes.is_empty());
assert_eq!(result.warnings.len(), 1);
assert!(
result.warnings[0].contains("belongs at"),
"got: {:?}",
result.warnings
);
}
#[test]
fn invalidate_sets_field_and_touches_updated() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path());
store.ensure_layout().unwrap();
store.write_node(&node("old-rule", Scope::Global)).unwrap();
let found = store
.invalidate(&Scope::Global, "old-rule", "new-rule")
.unwrap();
assert!(found);
let n = store.get(&Scope::Global, "old-rule").unwrap().unwrap();
assert_eq!(n.invalidated_by.as_deref(), Some("new-rule"));
assert_eq!(n.updated, chrono::Utc::now().date_naive());
assert!(!store.invalidate(&Scope::Global, "missing", "x").unwrap());
}
#[test]
fn get_parse_error_includes_file_path() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path());
store.ensure_layout().unwrap();
std::fs::write(tmp.path().join("knowledge/global/bad.md"), "not a node").unwrap();
let err = store.get(&Scope::Global, "bad").unwrap_err();
assert!(err.to_string().contains("bad.md"), "got: {err}");
}
}