diff --git a/crates/ghostlight/src/lib.rs b/crates/ghostlight/src/lib.rs index 3f64965..1f25445 100644 --- a/crates/ghostlight/src/lib.rs +++ b/crates/ghostlight/src/lib.rs @@ -143,7 +143,10 @@ pub use table::{ decode_authoring_call, decode_authoring_calls, describe_refusal, describe_refusal_to_actor, id_text, id_text_matches, table_view, }; -pub use vault::{VaultError, VaultEvidenceSource}; +pub use vault::{ + ImportOutcome, SnapshotId, VAULT_PROFILE_SCHEMA, VAULT_SNAPSHOT_SCHEMA, VaultError, + VaultEvidenceSource, VaultProfile, VaultSnapshot, +}; pub use verse::{ CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, ProviderCallRecord, RUN_RECORD_SCHEMA, RecordedCoverBudget, RecordingInferencePort, Refusal, RefusalReason, RunClaim, diff --git a/crates/ghostlight/src/vault.rs b/crates/ghostlight/src/vault.rs index 905a775..c545deb 100644 --- a/crates/ghostlight/src/vault.rs +++ b/crates/ghostlight/src/vault.rs @@ -1,20 +1,30 @@ -//! A read-only markdown vault, behind the world's `EvidenceSource` seam. +//! A vault is imported once into an immutable, content-addressed snapshot, and +//! the world's `EvidenceSource` seam reads only snapshots. //! -//! It resolves referent strings to notes and hands back bounded excerpts. It -//! never writes, never leaves its configured root, never touches git or the -//! network, and holds no world truth: its output is `EvidenceReceipt`s whose -//! `excerpt` and `source` are prompt material and whose `reference` is the only -//! thing that can ever reach the journal. +//! `VaultSnapshot::build` is the only reader of a vault directory. It admits +//! the notes a `VaultProfile` names, hashes their bytes, parses titles, aliases +//! and wikilinks, and derives the snapshot id from the profile and those bytes +//! alone: no clock, no model, no host path. Retrieval then runs against the +//! snapshot, so a live edit to the vault cannot change what a seed or an +//! elaborator is shown until the vault is imported again, and an import of +//! unchanged bytes is a no-op. //! -//! It is the one authority in the seed lane that can be tested with no kernel -//! at all, which is why it is a module. +//! Evidence is bounded excerpts: output is `EvidenceReceipt`s whose `excerpt` +//! and `source` are prompt material and whose `reference` is the only thing that +//! can ever reach the journal. Nothing here writes to a vault, touches git or +//! the network, or holds world truth. use super::EvidenceRef; use super::elaboration::{EvidenceError, EvidenceQuery, EvidenceReceipt, EvidenceSource}; use async_trait::async_trait; +use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write as _; use std::path::{Component, Path, PathBuf}; use thiserror::Error; +use unicode_normalization::UnicodeNormalization; /// Below `MAX_PATCH_EVIDENCE` (64), so a session that cites everything it was /// handed still fits inside one patch. @@ -27,41 +37,494 @@ const MAX_EXCERPT_CHARS: usize = 800; const MAX_VAULT_NOTES: usize = 4_096; const MAX_NOTE_BYTES: u64 = 512 * 1024; -/// Neither variant carries an absolute filesystem path: `seed_once` maps this -/// error straight into the owner's command receipt, and the reference format -/// this module hands back is deliberately vault-relative, so the error text -/// must be too. `Root` names no path at all; `Scope` carries only the -/// vault-relative scope string the caller supplied. +/// CultCache schema ids of the two persistent kinds. +pub const VAULT_PROFILE_SCHEMA: &str = "ghostlight.vault_profile.v1"; +pub const VAULT_SNAPSHOT_SCHEMA: &str = "ghostlight.vault_snapshot.v1"; +/// Domain tag of the id digest. Changing how the id is derived changes this. +const ID_DOMAIN: &[u8] = b"ghostlight.vault_snapshot.v1\0"; +/// A snapshot is a fact about bytes, not an event, so its row carries a fixed +/// store time rather than a clock read. +const SNAPSHOT_STORED_AT: &str = "1970-01-01T00:00:00+00:00"; + +/// No variant carries an absolute filesystem path: `seed_once` maps this error +/// straight into the owner's command receipt, and the reference format this +/// module hands back is deliberately vault-relative, so the error text must be +/// too. `Scope` carries only the vault-relative string the caller supplied. #[derive(Debug, Error)] pub enum VaultError { #[error("vault root is not a readable directory")] Root, #[error("vault scope escapes its root: {0}")] Scope(String), + #[error("vault pattern is not a vault-relative path written with forward slashes: {0}")] + Pattern(String), #[error("vault holds more than {MAX_VAULT_NOTES} notes")] TooManyNotes, + #[error("the snapshot store could not be written or read")] + Store, + #[error("no snapshot with that id is in the store")] + NotImported, + #[error("the stored snapshot is not a canonical snapshot of its own id")] + Corrupt, } -/// One note as the reader holds it. The body is kept in memory because the -/// corpora this reads are a few megabytes of markdown and a per-query file read -/// would buy nothing but a second failure mode. -#[derive(Clone, Debug)] -struct VaultNote { - /// The evidence reference: the note's vault-relative path with forward +/// What to import from one vault. Any Obsidian-style folder of `.md` files plugs +/// in through a profile. `.obsidian`, `.git` and every other dot-directory are +/// always skipped, and so is a nested vault (a subdirectory holding its own +/// `.obsidian`) unless `include` names it or something inside it. Repository +/// machinery is never lore: a file named `AGENTS.md`, `CLAUDE.md` or `README.md` +/// (any case, any depth) is always skipped. +/// +/// Production profiles are the table in the ignored `real_vaults_build` test at +/// the foot of this file; a profile is data and nothing else owns one. +/// +/// `root` is machine-local: it locates the files and is deliberately not part of +/// the snapshot id nor carried into the snapshot, so one vault imported on two +/// hosts is one snapshot. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct VaultProfile { + pub name: String, + pub root: PathBuf, + /// Vault-relative directories to admit notes from, no wildcards; empty + /// admits everything under `scope` that is not excluded. + pub include: Vec, + /// Vault-relative paths of directories or files not admitted, written with + /// forward slashes: `Spoilers.md`, `Game Design`, `Stories/*/Branch Map.md`. + /// A `*` stands for any run of characters inside one path component, never + /// across a `/`. A pattern also excludes everything under a directory it + /// names. A backslash is refused at build rather than matching nothing. + pub exclude: Vec, + /// A vault-relative subdirectory the import is narrowed to; empty is the + /// whole root. References stay relative to `root`. + pub scope: String, +} + +/// The sha256, as lowercase hex, of the canonical encoding of the profile and +/// the sorted `(path, sha256)` pairs of its admitted notes. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct SnapshotId(String); + +impl SnapshotId { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for SnapshotId { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.0) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ImportOutcome { + Imported(SnapshotId), + /// The store already holds this id; nothing was written. + AlreadyImported(SnapshotId), +} + +/// One note as the snapshot holds it. The body is kept because the corpora this +/// reads are a few megabytes of markdown and retrieval must not return to the +/// directory. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +struct SnapshotNote { + /// The evidence reference: the note's NFC vault-relative path with forward /// slashes, e.g. `Spoilers/Places/Low Sere.md`. It is a path and not a /// wikilink target, because stems collide across directories; not a scheme, /// because the kernel has no scheme registry; and not a digest, because a /// human must be able to resolve it years later. reference: String, + /// Of the file's text with CRLF folded to LF, lowercase hex. + sha256: String, + /// Frontmatter title, else the filename stem. title: String, - /// Everything after the frontmatter block. - body: String, + aliases: Vec, /// Wikilink targets, left side only. links: Vec, + /// Everything after the frontmatter block. HTML blocks stay as text. + body: String, +} + +/// An immutable import of one vault. It holds no path to the vault. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct VaultSnapshot { + id: SnapshotId, + /// The canonical profile with `root` emptied. + profile: VaultProfile, + notes: Vec, +} + +impl VaultSnapshot { + pub fn id(&self) -> &SnapshotId { + &self.id + } + + pub fn profile(&self) -> &VaultProfile { + &self.profile + } + + pub fn note_count(&self) -> usize { + self.notes.len() + } + + /// The canonical bytes of the snapshot: the same vault gives the same bytes. + pub fn to_bytes(&self) -> Vec { + rmp_serde::to_vec_named(self).expect("a snapshot is plain data") + } + + /// The only reader of a vault directory. `scope` and every walk step are + /// bounded: each directory and note is canonicalized and admitted only when + /// its canonical form still starts with the vault's canonical root, and a + /// directory entry that is itself a reparse point is refused outright + /// rather than descended into, because canonicalizing its *contents* would + /// still resolve through it before the containment check ever ran. + /// + /// Known limit: a hard link inside the root to a file outside it is an + /// ordinary file with its own name and is admitted. A link count above one + /// does not say where the other names live, so no cheap check exists; the + /// vaults are operator-owned copies and a profile's root must be trusted. + pub fn build(profile: &VaultProfile) -> Result { + let root = profile.root.canonicalize().map_err(|_| VaultError::Root)?; + if !root.is_dir() { + return Err(VaultError::Root); + } + let scope = relative_dir(&profile.scope).ok_or_else(|| VaultError::Scope(profile.scope.clone()))?; + let canonical = VaultProfile { + name: profile.name.clone(), + root: PathBuf::new(), + include: canonical_dirs(&profile.include, false)?, + exclude: canonical_dirs(&profile.exclude, true)?, + scope: scope.clone(), + }; + let start = if scope.is_empty() { + root.clone() + } else { + root.join(&scope) + .canonicalize() + .map_err(|_| VaultError::Scope(scope.clone()))? + }; + if !start.starts_with(&root) || !start.is_dir() { + return Err(VaultError::Scope(scope)); + } + + let mut found = Vec::new(); + collect_notes(&root, &start, &scope, &canonical, &mut found)?; + found.sort(); + + let mut notes: BTreeMap = BTreeMap::new(); + for (reference, path) in found { + if notes.contains_key(&reference) { + continue; + } + let Ok(metadata) = std::fs::metadata(&path) else { + continue; + }; + if metadata.len() > MAX_NOTE_BYTES { + continue; + } + let Ok(bytes) = std::fs::read(&path) else { + continue; + }; + let Ok(text) = String::from_utf8(bytes) else { + continue; + }; + // A checkout with autocrlf holds the same note: fold before the + // hash, the parse and the stored body. + let text = text.replace("\r\n", "\n"); + let stem = Path::new(&reference) + .file_stem() + .map(|value| value.to_string_lossy().into_owned()) + .unwrap_or_default(); + let (front, body) = split_frontmatter(&text); + let (front_title, aliases) = read_front_keys(front); + notes.insert( + reference.clone(), + SnapshotNote { + reference, + sha256: hex(&Sha256::digest(text.as_bytes())), + title: front_title.unwrap_or(stem), + aliases, + links: wikilink_targets(body), + body: body.to_owned(), + }, + ); + } + let notes: Vec = notes.into_values().collect(); + Ok(Self { + id: snapshot_id(&canonical, ¬es), + profile: canonical, + notes, + }) + } + + /// Writes this snapshot as `.cc` under `directory`. A directory entry + /// that already loads as this snapshot is left untouched; one that does not + /// (zero bytes, foreign, torn) is replaced. The file appears whole or not at + /// all: it is written under a name no other importer shares and renamed into + /// place, and a rename that loses to a concurrent importer of the same id is + /// success, because the winner holds the same bytes. The store's lock + /// sidecar is removed, so an import leaves exactly one file. + pub fn import_into(&self, directory: &Path) -> Result { + let already = || Self::load(directory, &self.id).is_ok_and(|held| held == *self); + if already() { + return Ok(ImportOutcome::AlreadyImported(self.id.clone())); + } + std::fs::create_dir_all(directory).map_err(|_| VaultError::Store)?; + let path = directory.join(format!("{}.cc", self.id)); + let partial = directory.join(format!("{}.cc.{}.partial", self.id, unique_suffix())); + let written = self.write_store(&partial); + let _ = std::fs::remove_file(sidecar(&partial)); + let published = written.and_then(|()| { + // Unix replaces a held file atomically. Windows refuses to, so a + // corrupt predecessor is removed and the rename tried once more. + std::fs::rename(&partial, &path) + .or_else(|_| { + if already() { + return Ok(()); + } + let _ = std::fs::remove_file(&path); + std::fs::rename(&partial, &path) + }) + .map_err(|_| VaultError::Store) + }); + let _ = std::fs::remove_file(&partial); + match published { + Ok(()) => Ok(ImportOutcome::Imported(self.id.clone())), + Err(_) if already() => Ok(ImportOutcome::AlreadyImported(self.id.clone())), + Err(error) => Err(error), + } + } + + fn write_store(&self, partial: &Path) -> Result<(), VaultError> { + let mut store = OwnedRedbMessagePackBackingStore::new(partial).map_err(|_| VaultError::Store)?; + store + .push(&CultCacheEnvelope { + key: self.id.to_string(), + r#type: VAULT_SNAPSHOT_SCHEMA.into(), + payload: self.to_bytes(), + stored_at: SNAPSHOT_STORED_AT.into(), + schema_id: Some(VAULT_SNAPSHOT_SCHEMA.into()), + }) + .map_err(|_| VaultError::Store) + } + + /// Reads the stored snapshot of `id`. The id is the stored row's own key and + /// field, read back and compared, never re-derived: the note bytes it was + /// derived from are not kept. + /// + /// The store opens a file read-write, creates a lock sidecar beside it and + /// writes a table on open, so the stored file is never opened: a private + /// copy in the system temp directory is, and removed after. Loading leaves + /// the store directory as it was, works on a read-only one, and takes no + /// lock that a concurrent loader or importer could collide with. + pub fn load(directory: &Path, id: &SnapshotId) -> Result { + let path = directory.join(format!("{id}.cc")); + if !path.is_file() { + return Err(VaultError::NotImported); + } + let scratch = std::env::temp_dir().join(format!("ghostlight-vault-load-{}", unique_suffix())); + let copied = std::fs::create_dir_all(&scratch) + .and_then(|()| std::fs::copy(&path, scratch.join("snapshot.cc"))) + .map_err(|_| VaultError::Store); + let read = copied.and_then(|_| Self::read_row(&scratch.join("snapshot.cc"), id)); + let _ = std::fs::remove_dir_all(&scratch); + read + } + + fn read_row(copy: &Path, id: &SnapshotId) -> Result { + let store = OwnedRedbMessagePackBackingStore::new(copy).map_err(|_| VaultError::Corrupt)?; + let rows = store.pull_all().map_err(|_| VaultError::Corrupt)?; + let [row] = rows.as_slice() else { + return Err(VaultError::Corrupt); + }; + if row.r#type != VAULT_SNAPSHOT_SCHEMA + || row.schema_id.as_deref() != Some(VAULT_SNAPSHOT_SCHEMA) + || row.key != id.as_str() + { + return Err(VaultError::Corrupt); + } + let snapshot: Self = rmp_serde::from_slice(&row.payload).map_err(|_| VaultError::Corrupt)?; + if snapshot.id != *id || snapshot.to_bytes() != row.payload { + return Err(VaultError::Corrupt); + } + Ok(snapshot) + } +} + +/// Unique across processes and threads: no two importers or loaders share a +/// temporary name. +fn unique_suffix() -> String { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + format!("{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) +} + +/// The lock file the store leaves beside the file it opened. +fn sidecar(path: &Path) -> PathBuf { + let mut name = path.as_os_str().to_owned(); + name.push(".lock"); + PathBuf::from(name) +} + +/// Length-prefixed fields, so no two profiles or note lists share an encoding. +fn snapshot_id(profile: &VaultProfile, notes: &[SnapshotNote]) -> SnapshotId { + fn field(digest: &mut Sha256, text: &str) { + digest.update((text.len() as u64).to_be_bytes()); + digest.update(text.as_bytes()); + } + fn list(digest: &mut Sha256, items: &[String]) { + digest.update((items.len() as u64).to_be_bytes()); + for item in items { + field(digest, item); + } + } + let mut digest = Sha256::new(); + digest.update(ID_DOMAIN); + field(&mut digest, &profile.name); + field(&mut digest, &profile.scope); + list(&mut digest, &profile.include); + list(&mut digest, &profile.exclude); + digest.update((notes.len() as u64).to_be_bytes()); + for note in notes { + field(&mut digest, ¬e.reference); + field(&mut digest, ¬e.sha256); + } + SnapshotId(hex(&digest.finalize())) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().fold(String::new(), |mut text, byte| { + let _ = write!(text, "{byte:02x}"); + text + }) +} + +/// `text` as an NFC, forward-slashed, vault-relative directory path, or `None` +/// when it is absolute or holds anything but plain components. +fn relative_dir(text: &str) -> Option { + let path = Path::new(text.trim()); + if path + .components() + .any(|part| !matches!(part, Component::Normal(_))) + { + return None; + } + Some( + path.components() + .map(|part| part.as_os_str().to_string_lossy().nfc().collect::()) + .collect::>() + .join("/"), + ) +} + +fn canonical_dirs(dirs: &[String], wildcards: bool) -> Result, VaultError> { + let mut clean = BTreeSet::new(); + for dir in dirs { + if dir.contains('\\') || (!wildcards && dir.contains('*')) { + return Err(VaultError::Pattern(dir.clone())); + } + match relative_dir(dir) { + Some(text) if !text.is_empty() => clean.insert(text), + _ => return Err(VaultError::Scope(dir.clone())), + }; + } + Ok(clean.into_iter().collect()) +} + +/// Component-wise: `a/b` is under `a` and under itself, `ab` is not under `a`. +fn is_under(path: &str, dir: &str) -> bool { + path == dir || path.strip_prefix(dir).is_some_and(|rest| rest.starts_with('/')) +} + +/// Whether `path` or one of its ancestors matches `pattern`, component-wise. +fn matches_pattern(path: &str, pattern: &str) -> bool { + fn glob(pattern: &[char], text: &[char]) -> bool { + match pattern.split_first() { + None => text.is_empty(), + Some(('*', rest)) => (0..=text.len()).any(|taken| glob(rest, &text[taken..])), + Some((head, rest)) => text.first() == Some(head) && glob(rest, &text[1..]), + } + } + let parts: Vec<&str> = path.split('/').collect(); + let wanted: Vec<&str> = pattern.split('/').collect(); + wanted.len() <= parts.len() + && wanted.iter().zip(&parts).all(|(want, part)| { + glob(&want.chars().collect::>(), &part.chars().collect::>()) + }) +} + +/// Repository and agent files are never lore, in any vault, at any depth. +fn is_machinery(name: &str) -> bool { + ["AGENTS.md", "CLAUDE.md", "README.md"] + .iter() + .any(|machine| name.eq_ignore_ascii_case(machine)) +} + +/// `(reference, path)` of every admitted note below `directory`; `relative` is +/// `directory`'s own vault-relative path. Entry order is the filesystem's and +/// carries no meaning: the caller sorts. +fn collect_notes( + root: &Path, + directory: &Path, + relative: &str, + profile: &VaultProfile, + into: &mut Vec<(String, PathBuf)>, +) -> Result<(), VaultError> { + let entries = std::fs::read_dir(directory).map_err(|_| VaultError::Root)?; + for entry in entries.flatten() { + let path = entry.path(); + let Ok(metadata) = std::fs::symlink_metadata(&path) else { + continue; + }; + if is_reparse_point(&metadata) { + continue; + } + let name = entry.file_name().to_string_lossy().nfc().collect::(); + let child = if relative.is_empty() { + name.clone() + } else { + format!("{relative}/{name}") + }; + if metadata.is_dir() { + if name.starts_with('.') + || profile.exclude.iter().any(|pattern| matches_pattern(&child, pattern)) + || (path.join(".obsidian").is_dir() + && !profile.include.iter().any(|dir| is_under(dir, &child) || is_under(&child, dir))) + { + continue; + } + let Ok(canonical) = path.canonicalize() else { + continue; + }; + if !canonical.starts_with(root) { + continue; + } + collect_notes(root, &path, &child, profile, into)?; + } else if path.extension().is_some_and(|value| value == "md") + && !is_machinery(&name) + && !profile.exclude.iter().any(|pattern| matches_pattern(&child, pattern)) + && (profile.include.is_empty() || profile.include.iter().any(|dir| is_under(&child, dir))) + { + let Ok(canonical) = path.canonicalize() else { + continue; + }; + if !canonical.starts_with(root) || child.trim() != child { + continue; + } + if into.len() >= MAX_VAULT_NOTES { + return Err(VaultError::TooManyNotes); + } + into.push((child, path)); + } + } + Ok(()) } pub struct VaultEvidenceSource { - notes: Vec, + notes: Vec, /// Many-to-one: filename stem, frontmatter title, and each alias all key /// the same note. Ambiguity is resolved by the shortest reference path, and /// refused for that referent when two candidates tie. @@ -69,98 +532,35 @@ pub struct VaultEvidenceSource { } impl VaultEvidenceSource { - /// `root` is the configured vault root; `scope` is a relative subdirectory - /// or empty. Both are canonicalized and the scope must live under the root, - /// so `..`, an absolute scope, and a symlink out are all refused here. A - /// spoiler tier is a directory in every vault that has one, so it is - /// expressed as a scope and there is no tier field anywhere in this file. - pub fn open(root: &Path, scope: &str) -> Result { - let root = root.canonicalize().map_err(|_| VaultError::Root)?; - if !root.is_dir() { - return Err(VaultError::Root); + /// `scope` is a relative subdirectory of the snapshot or empty. A spoiler + /// tier is a directory in every vault that has one, so it is expressed as a + /// scope and there is no tier field anywhere in this file. `..`, an + /// absolute scope, and a scope that holds no note are refused. + pub fn from_snapshot(snapshot: &VaultSnapshot, scope: &str) -> Result { + let scope = relative_dir(scope).ok_or_else(|| VaultError::Scope(scope.to_owned()))?; + let notes: Vec = snapshot + .notes + .iter() + .filter(|note| scope.is_empty() || is_under(¬e.reference, &scope)) + .cloned() + .collect(); + if notes.is_empty() && !scope.is_empty() { + return Err(VaultError::Scope(scope)); } - let scope_path = if scope.trim().is_empty() { - root.clone() - } else { - let relative = Path::new(scope.trim()); - if relative.is_absolute() - || relative - .components() - .any(|part| !matches!(part, Component::Normal(_))) - { - return Err(VaultError::Scope(scope.to_owned())); - } - let joined = root.join(relative); - let canonical = joined - .canonicalize() - .map_err(|_| VaultError::Scope(scope.to_owned()))?; - if !canonical.starts_with(&root) { - return Err(VaultError::Scope(scope.to_owned())); - } - canonical - }; - - let mut paths: Vec = Vec::new(); - collect_notes(&root, &scope_path, &mut paths)?; - paths.sort(); - - let mut notes = Vec::new(); - for path in paths { - let Ok(metadata) = std::fs::metadata(&path) else { - continue; - }; - if metadata.len() > MAX_NOTE_BYTES { - continue; - } - let Ok(text) = std::fs::read_to_string(&path) else { - continue; - }; - let Ok(relative) = path.strip_prefix(&root) else { - continue; - }; - let reference = relative - .components() - .map(|part| part.as_os_str().to_string_lossy().into_owned()) - .collect::>() - .join("/"); - if reference.trim() != reference || reference.is_empty() { - continue; - } - let stem = path + let mut by_key: BTreeMap> = BTreeMap::new(); + for (index, note) in notes.iter().enumerate() { + let stem = Path::new(¬e.reference) .file_stem() .map(|value| value.to_string_lossy().into_owned()) .unwrap_or_default(); - let (front, body) = split_frontmatter(&text); - let (front_title, aliases) = read_front_keys(front); - let title = front_title.unwrap_or_else(|| stem.clone()); - let links = wikilink_targets(body); - let mut keys: Vec = vec![stem, title.clone()]; - keys.extend(aliases); - notes.push(( - VaultNote { - reference, - title, - body: body.to_owned(), - links, - }, - keys, - )); - } - - let mut by_key: BTreeMap> = BTreeMap::new(); - for (index, (_, keys)) in notes.iter().enumerate() { - for key in keys { + for key in [stem, note.title.clone()].iter().chain(¬e.aliases) { let key = key.trim().to_lowercase(); - if key.is_empty() { - continue; + if !key.is_empty() { + by_key.entry(key).or_default().push(index); } - by_key.entry(key).or_default().push(index); } } - Ok(Self { - notes: notes.into_iter().map(|(note, _)| note).collect(), - by_key, - }) + Ok(Self { notes, by_key }) } /// Exact key first, then a bounded keyword search. A referent whose exact @@ -279,47 +679,6 @@ impl EvidenceSource for VaultEvidenceSource { } } -/// `root` is the vault's canonical root, fixed for the whole walk. Every -/// directory and note is canonicalized and admitted only when its canonical -/// form still starts with `root`, so a junction or symlink planted inside the -/// scope cannot walk the reader out to wherever it points. A directory entry -/// whose own metadata is a reparse point is refused outright rather than -/// descended into: canonicalizing its *contents* would still resolve through -/// the reparse point before the containment check ever runs. -fn collect_notes(root: &Path, directory: &Path, into: &mut Vec) -> Result<(), VaultError> { - let entries = std::fs::read_dir(directory).map_err(|_| VaultError::Root)?; - for entry in entries.flatten() { - let path = entry.path(); - let Ok(metadata) = std::fs::symlink_metadata(&path) else { - continue; - }; - if is_reparse_point(&metadata) { - continue; - } - if metadata.is_dir() { - let Ok(canonical) = path.canonicalize() else { - continue; - }; - if !canonical.starts_with(root) { - continue; - } - collect_notes(root, &path, into)?; - } else if path.extension().is_some_and(|value| value == "md") { - let Ok(canonical) = path.canonicalize() else { - continue; - }; - if !canonical.starts_with(root) { - continue; - } - if into.len() >= MAX_VAULT_NOTES { - return Err(VaultError::TooManyNotes); - } - into.push(path); - } - } - Ok(()) -} - /// A directory junction on Windows carries the reparse-point attribute /// alongside the directory attribute, so `file_attributes` is the only signal /// that distinguishes it from a real directory; elsewhere a symlink is enough @@ -469,6 +828,22 @@ mod tests { std::fs::write(path, text).unwrap(); } + fn profile(root: &Path) -> VaultProfile { + VaultProfile { + name: "fixture".into(), + root: root.to_path_buf(), + ..VaultProfile::default() + } + } + + fn snapshot(root: &Path) -> VaultSnapshot { + VaultSnapshot::build(&profile(root)).unwrap() + } + + fn open(root: &Path, scope: &str) -> Result { + VaultEvidenceSource::from_snapshot(&VaultSnapshot::build(&profile(root))?, scope) + } + fn fixture() -> tempfile::TempDir { let directory = tempfile::tempdir().unwrap(); let root = directory.path(); @@ -505,7 +880,7 @@ mod tests { #[tokio::test] async fn the_vault_resolves_titles_aliases_and_wikilinks_inside_its_scope() { let directory = fixture(); - let whole = VaultEvidenceSource::open(directory.path(), "").unwrap(); + let whole = open(directory.path(), "").unwrap(); let receipts = whole.retrieve(&query(&["Low Sere"])).await.unwrap(); assert_eq!( @@ -563,7 +938,7 @@ mod tests { ); // The spoiler tier is a directory, so it is a scope. - let public = VaultEvidenceSource::open(directory.path(), "Public").unwrap(); + let public = open(directory.path(), "Public").unwrap(); assert!( public .retrieve(&query(&["Provenance"])) @@ -618,7 +993,7 @@ mod tests { return; } - let source = VaultEvidenceSource::open(directory.path(), "Public").unwrap(); + let source = open(directory.path(), "Public").unwrap(); let receipts = source.retrieve(&query(&["Secret"])).await.unwrap(); assert!( receipts.is_empty(), @@ -647,7 +1022,7 @@ mod tests { write(root, "Public/Places/Long Note.md", &huge); let before = tree(root); - let source = VaultEvidenceSource::open(root, "").unwrap(); + let source = open(root, "").unwrap(); for name in ["Long Note", "The Long Note", "obese"] { let receipts = source.retrieve(&query(&[name])).await.unwrap(); assert!( @@ -713,7 +1088,7 @@ mod tests { "quarry stone quarry stone\n", ); } - let source = VaultEvidenceSource::open(root, "").unwrap(); + let source = open(root, "").unwrap(); let mut referents: Vec = (0..MAX_VAULT_RECEIPTS - 1) .map(|index| format!("plain{index}")) @@ -739,13 +1114,13 @@ mod tests { for (case, opened) in [ ( "an escaping scope", - VaultEvidenceSource::open(root, "Public/../.."), + open(root, "Public/../.."), ), // The reachable misconfiguration: `GHOSTLIGHT_SEED_VAULT_ROOT` // naming something that is not a directory. ( "a root that is a file", - VaultEvidenceSource::open(&root.join("Public/index.md"), ""), + open(&root.join("Public/index.md"), ""), ), ] { let Err(error) = opened else { @@ -767,12 +1142,589 @@ mod tests { let root = directory.path(); for scope in ["..", "../..", "Public/../..", "Public/../../etc"] { assert!( - VaultEvidenceSource::open(root, scope).is_err(), + open(root, scope).is_err(), "{scope} was admitted" ); } let absolute = root.join("Public"); - assert!(VaultEvidenceSource::open(root, &absolute.display().to_string()).is_err()); - assert!(VaultEvidenceSource::open(root, "Public").is_ok()); + assert!(open(root, &absolute.display().to_string()).is_err()); + assert!(open(root, "Public").is_ok()); + } + + /// Two trees with the same bytes, made in a different order, at different + /// paths and with shuffled modification times, are one snapshot: one id, one + /// byte string. The root and the clock are not part of it. + #[test] + fn a_snapshot_is_deterministic() { + let first = fixture(); + let second = tempfile::tempdir().unwrap(); + for (relative, text) in [ + ("Spoilers/Dungeons/Provenance.md", "The hinge was built by the drowned. Link: [[Low Sere#Nothing]]\n"), + ("Public/World/index.md", "World index, deeper.\n"), + ("Public/index.md", "Public index.\n"), + ("Public/Places/Rain Gate.md", "---\ntitle: The Rain Gate\naliases:\n - Gate of Rain\n - Hinge\nstatus: canonical\n---\n# Body\nWater enters here.\n\n## Tolls\nA toll of one is charged.\n"), + ("Public/Places/Low Sere.md", "The sere runs dry nine months a year.\nSee [[Rain Gate]] and [[Rain Gate|the gate]].\n"), + ] { + write(second.path(), relative, text); + } + let mut paths = Vec::new(); + collect_all(second.path(), &mut paths); + for (age, path) in paths.iter().enumerate() { + let when = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000 * (age as u64 + 1)); + std::fs::File::options() + .write(true) + .open(path) + .unwrap() + .set_modified(when) + .unwrap(); + } + let a = snapshot(first.path()); + let b = snapshot(second.path()); + assert_eq!(a.id(), b.id()); + assert_eq!(a.to_bytes(), b.to_bytes()); + assert_eq!(a.id().as_str().len(), 64); + assert_eq!(a.note_count(), 5); + assert_eq!(a.id(), snapshot(first.path()).id()); + } + + #[test] + fn re_import_of_unchanged_bytes_is_a_no_op() { + let vault = fixture(); + let store = tempfile::tempdir().unwrap(); + let built = snapshot(vault.path()); + assert_eq!( + built.import_into(store.path()).unwrap(), + ImportOutcome::Imported(built.id().clone()) + ); + let stored = store.path().join(format!("{}.cc", built.id())); + let before = std::fs::read(&stored).unwrap(); + let listing = || { + let mut names: Vec<_> = std::fs::read_dir(store.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + names.sort(); + names + }; + let names = listing(); + assert_eq!(names.len(), 1, "an import leaves exactly one file: {names:?}"); + + let again = snapshot(vault.path()); + assert_eq!( + again.import_into(store.path()).unwrap(), + ImportOutcome::AlreadyImported(built.id().clone()) + ); + assert_eq!(before, std::fs::read(&stored).unwrap()); + assert_eq!(names, listing()); + + let loaded = VaultSnapshot::load(store.path(), built.id()).unwrap(); + assert_eq!(loaded, built); + } + + #[test] + fn a_missing_or_foreign_snapshot_is_refused_on_load() { + let vault = fixture(); + let store = tempfile::tempdir().unwrap(); + let built = snapshot(vault.path()); + assert!(matches!( + VaultSnapshot::load(store.path(), built.id()), + Err(VaultError::NotImported) + )); + // A file under one id that holds another snapshot is not that snapshot. + write(vault.path(), "Public/extra.md", "extra\n"); + let other = snapshot(vault.path()); + other.import_into(store.path()).unwrap(); + std::fs::rename( + store.path().join(format!("{}.cc", other.id())), + store.path().join(format!("{}.cc", built.id())), + ) + .unwrap(); + assert!(matches!( + VaultSnapshot::load(store.path(), built.id()), + Err(VaultError::Corrupt) + )); + } + + #[test] + fn one_byte_of_an_admitted_note_changes_the_id_and_an_excluded_folder_does_not() { + let vault = fixture(); + write(vault.path(), "Brainstorming/idea.md", "first\n"); + write(vault.path(), ".obsidian/workspace.md", "first\n"); + let profile = VaultProfile { + exclude: vec!["Brainstorming".into()], + ..profile(vault.path()) + }; + let base = VaultSnapshot::build(&profile).unwrap(); + + write(vault.path(), "Brainstorming/idea.md", "second\n"); + write(vault.path(), ".obsidian/workspace.md", "second\n"); + write(vault.path(), "Brainstorming/new.md", "new\n"); + assert_eq!(VaultSnapshot::build(&profile).unwrap().id(), base.id()); + + write(vault.path(), "Public/index.md", "Public index!\n"); + assert_ne!(VaultSnapshot::build(&profile).unwrap().id(), base.id()); + write(vault.path(), "Public/index.md", "Public index.\n"); + assert_eq!(VaultSnapshot::build(&profile).unwrap().id(), base.id()); + + // The profile is part of the id: the same bytes under another name or + // another exclusion are another snapshot. + let renamed = VaultProfile { + name: "other".into(), + ..profile.clone() + }; + assert_ne!(VaultSnapshot::build(&renamed).unwrap().id(), base.id()); + assert_ne!(snapshot(vault.path()).id(), base.id()); + } + + #[tokio::test] + async fn live_edits_do_not_reach_a_snapshot() { + let vault = fixture(); + let built = snapshot(vault.path()); + let source = VaultEvidenceSource::from_snapshot(&built, "").unwrap(); + let ask = || query(&["Rain Gate#Tolls", "Low Sere", "Provenance"]); + let before = source.retrieve(&ask()).await.unwrap(); + + write(vault.path(), "Public/Places/Rain Gate.md", "---\ntitle: Gone\n---\nRewritten.\n"); + std::fs::remove_file(vault.path().join("Public/Places/Low Sere.md")).unwrap(); + write(vault.path(), "Public/Places/New.md", "A new place, [[Rain Gate]].\n"); + + let after = source.retrieve(&ask()).await.unwrap(); + assert_eq!(before.len(), after.len()); + for (b, a) in before.iter().zip(&after) { + assert_eq!((&b.reference, &b.excerpt, &b.source), (&a.reference, &a.excerpt, &a.source)); + } + let rebuilt = VaultEvidenceSource::from_snapshot(&built, "").unwrap(); + assert!(rebuilt.retrieve(&query(&["New"])).await.unwrap().is_empty()); + assert_ne!(snapshot(vault.path()).id(), built.id()); + } + + #[test] + fn dot_directories_and_nested_vaults_are_skipped_unless_included() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + write(root, "Top.md", "top\n"); + write(root, ".git/notes.md", "git\n"); + write(root, ".quartz-build/page.md", "build\n"); + write(root, "Docs/.hidden/secret.md", "hidden\n"); + write(root, "Nested/.obsidian/app.json", "{}\n"); + write(root, "Nested/Inner.md", "inner\n"); + write(root, "Nested/Deeper/Leaf.md", "leaf\n"); + write(root, "Docs/Page.md", "

raw html stays

\n"); + + let default = snapshot(root); + let references: Vec<_> = default.notes.iter().map(|note| note.reference.as_str()).collect(); + assert_eq!(references, ["Docs/Page.md", "Top.md"]); + assert!(default.notes[0].body.contains("

raw html stays

")); + + for include in ["Nested", "Nested/Deeper"] { + let named = VaultSnapshot::build(&VaultProfile { + include: vec![include.into()], + ..profile(root) + }) + .unwrap(); + assert!( + named.notes.iter().any(|note| note.reference.starts_with("Nested/")), + "including {include} did not admit the nested vault" + ); + assert!(named.notes.iter().all(|note| note.reference.starts_with(include))); + } + + // The nested vault, as its own root, is a vault of its own. + let own = snapshot(&root.join("Nested")); + assert_eq!(own.note_count(), 2); + } + + #[test] + fn include_and_scope_narrow_the_import_and_references_stay_root_relative() { + let vault = fixture(); + let included = VaultSnapshot::build(&VaultProfile { + include: vec!["Public/Places".into()], + ..profile(vault.path()) + }) + .unwrap(); + assert_eq!(included.note_count(), 2); + let scoped = VaultSnapshot::build(&VaultProfile { + scope: "Public/Places".into(), + ..profile(vault.path()) + }) + .unwrap(); + assert_eq!(scoped.note_count(), 2); + assert!(scoped.notes.iter().all(|note| note.reference.starts_with("Public/Places/"))); + assert!(VaultSnapshot::build(&VaultProfile { scope: "../x".into(), ..profile(vault.path()) }).is_err()); + assert!(VaultSnapshot::build(&VaultProfile { exclude: vec!["/abs".into()], ..profile(vault.path()) }).is_err()); + } + + fn listing(directory: &Path) -> Vec { + let mut names: Vec = std::fs::read_dir(directory) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names + } + + /// Stores `rows` as the file a snapshot of `id` would be, however wrong. + fn plant(directory: &Path, id: &SnapshotId, rows: &[CultCacheEnvelope]) { + let path = directory.join(format!("{id}.cc")); + { + let mut store = OwnedRedbMessagePackBackingStore::new(&path).unwrap(); + for row in rows { + store.push(row).unwrap(); + } + } + let _ = std::fs::remove_file(sidecar(&path)); + } + + fn row(key: &str, payload: Vec) -> CultCacheEnvelope { + CultCacheEnvelope { + key: key.into(), + r#type: VAULT_SNAPSHOT_SCHEMA.into(), + payload, + stored_at: SNAPSHOT_STORED_AT.into(), + schema_id: Some(VAULT_SNAPSHOT_SCHEMA.into()), + } + } + + /// Every way a stored file can fail to be the snapshot of its name is + /// Corrupt, one condition at a time; the honest file loads. + #[test] + fn load_refuses_a_row_that_is_wrong_in_any_one_way() { + let vault = fixture(); + let built = snapshot(vault.path()); + let id = built.id(); + write(vault.path(), "Public/extra.md", "extra\n"); + let other = snapshot(vault.path()); + let honest = row(id.as_str(), built.to_bytes()); + let non_canonical = rmp_serde::to_vec(&built).unwrap(); + assert_ne!(non_canonical, built.to_bytes()); + assert_eq!(rmp_serde::from_slice::(&non_canonical).unwrap(), built); + + let cases: Vec<(&str, Vec)> = vec![ + ("no rows", vec![]), + ("two rows", vec![honest.clone(), row("second", built.to_bytes())]), + ("foreign type", vec![CultCacheEnvelope { r#type: "other.v1".into(), ..honest.clone() }]), + ("no schema id", vec![CultCacheEnvelope { schema_id: None, ..honest.clone() }]), + ( + "foreign schema id", + vec![CultCacheEnvelope { schema_id: Some("other.v1".into()), ..honest.clone() }], + ), + ("foreign key", vec![row(other.id().as_str(), built.to_bytes())]), + ("another snapshot's bytes", vec![row(id.as_str(), other.to_bytes())]), + ("a non-canonical encoding", vec![row(id.as_str(), non_canonical)]), + ("garbage payload", vec![row(id.as_str(), b"not msgpack".to_vec())]), + ]; + for (label, rows) in cases { + let store = tempfile::tempdir().unwrap(); + plant(store.path(), id, &rows); + assert!( + matches!(VaultSnapshot::load(store.path(), id), Err(VaultError::Corrupt)), + "{label} loaded" + ); + } + let store = tempfile::tempdir().unwrap(); + plant(store.path(), id, &[honest]); + assert_eq!(&VaultSnapshot::load(store.path(), id).unwrap(), &built); + } + + /// A stored file that is not a snapshot of its name is replaced by an + /// import, never reported as already imported. + #[test] + fn a_poisoned_store_entry_is_replaced_not_reported_as_imported() { + let vault = fixture(); + let built = snapshot(vault.path()); + for poison in [Vec::new(), b"definitely not a store".to_vec()] { + let store = tempfile::tempdir().unwrap(); + let path = store.path().join(format!("{}.cc", built.id())); + std::fs::write(&path, &poison).unwrap(); + assert!(matches!(VaultSnapshot::load(store.path(), built.id()), Err(VaultError::Corrupt))); + assert_eq!( + built.import_into(store.path()).unwrap(), + ImportOutcome::Imported(built.id().clone()) + ); + assert_eq!(VaultSnapshot::load(store.path(), built.id()).unwrap(), built); + assert_eq!(listing(store.path()), [format!("{}.cc", built.id())]); + } + // A well-formed store holding another snapshot's row is replaced too. + let store = tempfile::tempdir().unwrap(); + plant(store.path(), built.id(), &[row(built.id().as_str(), b"x".to_vec())]); + assert!(built.import_into(store.path()).unwrap() == ImportOutcome::Imported(built.id().clone())); + assert_eq!(VaultSnapshot::load(store.path(), built.id()).unwrap(), built); + } + + /// Importers racing on one snapshot all succeed and leave one loadable file. + #[test] + fn concurrent_imports_of_one_snapshot_leave_one_loadable_file() { + let vault = fixture(); + let built = std::sync::Arc::new(snapshot(vault.path())); + for _ in 0..8 { + let store = tempfile::tempdir().unwrap(); + let directory = std::sync::Arc::new(store.path().to_path_buf()); + let workers: Vec<_> = (0..4) + .map(|_| { + let (built, directory) = (built.clone(), directory.clone()); + std::thread::spawn(move || { + let imported = built.import_into(&directory).unwrap(); + let loaded = VaultSnapshot::load(&directory, built.id()).unwrap(); + (imported, loaded) + }) + }) + .collect(); + for worker in workers { + let (_, loaded) = worker.join().unwrap(); + assert_eq!(&loaded, &*built); + } + assert_eq!(listing(store.path()), [format!("{}.cc", built.id())]); + assert_eq!( + built.import_into(store.path()).unwrap(), + ImportOutcome::AlreadyImported(built.id().clone()) + ); + } + } + + /// An import that cannot publish says so: a directory squatting on the + /// snapshot's name is an error, not a snapshot already held. + #[test] + fn an_import_that_cannot_publish_is_an_error() { + let vault = fixture(); + let built = snapshot(vault.path()); + let store = tempfile::tempdir().unwrap(); + let squatter = store.path().join(format!("{}.cc", built.id())); + std::fs::create_dir_all(squatter.join("inside")).unwrap(); + assert!(matches!(built.import_into(store.path()), Err(VaultError::Store))); + assert_eq!(listing(store.path()), [format!("{}.cc", built.id())]); + } + + #[test] + fn load_leaves_the_store_directory_as_it_found_it() { + let vault = fixture(); + let built = snapshot(vault.path()); + let store = tempfile::tempdir().unwrap(); + built.import_into(store.path()).unwrap(); + let file = store.path().join(format!("{}.cc", built.id())); + let before = std::fs::read(&file).unwrap(); + for _ in 0..2 { + VaultSnapshot::load(store.path(), built.id()).unwrap(); + } + assert_eq!(listing(store.path()), [format!("{}.cc", built.id())]); + assert_eq!(before, std::fs::read(&file).unwrap()); + } + + /// A scope that is a file, or a link out of the root, is refused as Scope; + /// a scope that holds no note is refused; an empty vault with no scope is + /// an empty source. + #[test] + fn a_scope_must_be_a_directory_inside_the_root_holding_a_note() { + let vault = fixture(); + let outside = tempfile::tempdir().unwrap(); + write(outside.path(), "Leak.md", "leak\n"); + assert!(matches!( + VaultSnapshot::build(&VaultProfile { scope: "Public/index.md".into(), ..profile(vault.path()) }), + Err(VaultError::Scope(_)) + )); + #[cfg(unix)] + { + std::os::unix::fs::symlink(outside.path(), vault.path().join("Out")).unwrap(); + assert!(matches!( + VaultSnapshot::build(&VaultProfile { scope: "Out".into(), ..profile(vault.path()) }), + Err(VaultError::Scope(_)) + )); + } + let built = snapshot(vault.path()); + assert!(matches!(VaultEvidenceSource::from_snapshot(&built, "Nowhere"), Err(VaultError::Scope(_)))); + assert!(VaultEvidenceSource::from_snapshot(&built, "Spoilers").is_ok()); + let empty = tempfile::tempdir().unwrap(); + assert!(VaultEvidenceSource::from_snapshot(&snapshot(empty.path()), "").is_ok()); + assert!(matches!( + VaultEvidenceSource::from_snapshot(&snapshot(empty.path()), "Spoilers"), + Err(VaultError::Scope(_)) + )); + } + + /// A name that does not survive trimming cannot be a reference. + #[test] + fn a_note_whose_name_begins_with_a_space_is_not_admitted() { + let vault = tempfile::tempdir().unwrap(); + write(vault.path(), "Good.md", "good\n"); + write(vault.path(), " Padded.md", "padded\n"); + assert_eq!(references(&snapshot(vault.path())), ["Good.md"]); + } + + fn references(snapshot: &VaultSnapshot) -> Vec<&str> { + snapshot.notes.iter().map(|note| note.reference.as_str()).collect() + } + + /// The same note checked out with CRLF line endings is the same snapshot, + /// down to the stored body and digest. + #[test] + fn crlf_and_lf_checkouts_are_one_snapshot() { + let lf = tempfile::tempdir().unwrap(); + let crlf = tempfile::tempdir().unwrap(); + write(lf.path(), "A.md", "---\ntitle: Alpha\n---\nline one\nline two\n"); + write(crlf.path(), "A.md", "---\r\ntitle: Alpha\r\n---\r\nline one\r\nline two\r\n"); + let (a, b) = (snapshot(lf.path()), snapshot(crlf.path())); + assert_eq!(a.id(), b.id()); + assert_eq!(a.to_bytes(), b.to_bytes()); + assert_eq!(b.notes[0].title, "Alpha"); + assert!(!b.notes[0].body.contains('\r')); + } + + /// Include and exclude are part of the id even when they change no note. + #[test] + fn include_and_exclude_are_in_the_id_even_when_they_admit_the_same_notes() { + let vault = fixture(); + let base = snapshot(vault.path()); + let excluded = VaultSnapshot::build(&VaultProfile { + exclude: vec!["Nothing Here".into()], + ..profile(vault.path()) + }) + .unwrap(); + let included = VaultSnapshot::build(&VaultProfile { + include: vec!["Public".into(), "Spoilers".into()], + ..profile(vault.path()) + }) + .unwrap(); + assert_eq!(excluded.note_count(), base.note_count()); + assert_eq!(included.note_count(), base.note_count()); + assert_ne!(excluded.id(), base.id()); + assert_ne!(included.id(), base.id()); + assert_ne!(excluded.id(), included.id()); + // The two lists are not interchangeable. + let swapped = VaultSnapshot::build(&VaultProfile { + exclude: vec!["Public".into(), "Spoilers".into()], + ..profile(vault.path()) + }) + .unwrap(); + assert_ne!(swapped.id(), included.id()); + assert_eq!(base.profile().root, PathBuf::new()); + assert_eq!(base.profile().name, "fixture"); + assert_eq!(excluded.profile().exclude, ["Nothing Here"]); + } + + /// Exclusion names files and globs, and repository machinery is never lore. + #[test] + fn file_and_glob_excludes_and_machinery_files_keep_notes_out() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + for note in [ + "Keep.md", + "Spoilers.md", + "AGENTS.md", + "claude.md", + "Sub/README.md", + "Sub/Deep/CLAUDE.md", + "Sub/Note.md", + "static/vendor/page.md", + "Stories/Coordinator Strategy.md", + "Stories/One/Coordinator Strategy.md", + "Stories/One/Branch Map.md", + "Stories/One/Kept.md", + "Stories/Two/Coordinator Strategy.md", + "Stories/Two/Deep/Coordinator Strategy.md", + ] { + write(root, note, "x\n"); + } + let built = VaultSnapshot::build(&VaultProfile { + exclude: vec![ + "Spoilers.md".into(), + "static".into(), + "Stories/*/Coordinator Strategy.md".into(), + "Stories/*/Branch Map.md".into(), + ], + ..profile(root) + }) + .unwrap(); + assert_eq!( + references(&built), + [ + "Keep.md", + "Stories/Coordinator Strategy.md", + "Stories/One/Kept.md", + "Stories/Two/Deep/Coordinator Strategy.md", + "Sub/Note.md", + ] + ); + // `*` stays inside one component and may sit inside a name. + assert!(matches_pattern("Stories/One/x.md", "Stories/*/x.md")); + assert!(!matches_pattern("Stories/One/Two/x.md", "Stories/*/x.md")); + assert!(matches_pattern("Game Design/a/b.md", "Game*")); + assert!(!matches_pattern("Game", "Game Design")); + } + + /// A backslash pattern is refused with a clear error, never matched against + /// nothing; an empty pattern and a wildcard include are refused too. + #[test] + fn a_backslash_or_empty_pattern_is_refused_at_build() { + let vault = fixture(); + for exclude in ["Public\\Places", "Stories\\*\\Map.md", ""] { + let error = VaultSnapshot::build(&VaultProfile { + exclude: vec![exclude.into()], + ..profile(vault.path()) + }) + .unwrap_err(); + assert!( + matches!(error, VaultError::Pattern(_) | VaultError::Scope(_)), + "{exclude:?} gave {error:?}" + ); + } + let backslash = VaultSnapshot::build(&VaultProfile { + exclude: vec!["Public\\Places".into()], + ..profile(vault.path()) + }) + .unwrap_err(); + assert!(matches!(backslash, VaultError::Pattern(ref text) if text == "Public\\Places")); + assert!(backslash.to_string().contains("forward slashes")); + assert!(matches!( + VaultSnapshot::build(&VaultProfile { include: vec!["Pub*".into()], ..profile(vault.path()) }), + Err(VaultError::Pattern(_)) + )); + assert!(matches!( + VaultSnapshot::build(&VaultProfile { include: vec!["a\\b".into()], ..profile(vault.path()) }), + Err(VaultError::Pattern(_)) + )); + } + + /// Real vaults, read-only. `GHOSTLIGHT_VAULT_SMOKE` names a directory that + /// holds byte-for-byte copies of `AetheriaLore`, `Zyphos` and `Delvehold`. + #[test] + #[ignore = "needs the real vaults"] + fn real_vaults_build() { + let base = PathBuf::from(std::env::var("GHOSTLIGHT_VAULT_SMOKE").unwrap()); + let cases = [ + ( + "aetheria", + "AetheriaLore/Aetheria", + vec![ + "Brainstorming", + "Game Design", + "Spoilers.md", + "static", + "Stories/How Branching Stories Are Made.md", + "Stories/*/Coordinator Strategy.md", + "Stories/*/Branch Map.md", + ], + ), + ("zyphos", "Zyphos/Eusocial Interbeing", vec!["Game Design", "Inspirations"]), + ("delvehold", "Delvehold/Delvehold", vec!["Game Design", "Documentation"]), + ("avatar", "Avatar", vec![]), + ]; + for (name, relative, exclude) in cases { + let profile = VaultProfile { + name: name.into(), + root: base.join(relative), + exclude: exclude.into_iter().map(str::to_owned).collect(), + ..VaultProfile::default() + }; + let built = VaultSnapshot::build(&profile).unwrap(); + let again = VaultSnapshot::build(&profile).unwrap(); + assert_eq!(built.id(), again.id()); + for note in &built.notes { + let leaf = note.reference.rsplit('/').next().unwrap(); + assert!(!is_machinery(leaf), "{name} admitted {}", note.reference); + for pattern in &built.profile().exclude { + assert!(!matches_pattern(¬e.reference, pattern), "{name} admitted {}", note.reference); + } + } + println!("SMOKE {name} notes={} id={}", built.note_count(), built.id()); + } } }