Vault import is a deterministic, re-runnable snapshot; retrieval reads only snapshots

VaultSnapshot::build is the only reader of a vault directory. VaultEvidenceSource::open and the per-query walk are deleted; from_snapshot replaces them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 17:53:06 +01:00
commit 75fdd958aa
2 changed files with 645 additions and 138 deletions

View file

@ -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,

View file

@ -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,11 +37,19 @@ 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")]
@ -40,28 +58,373 @@ pub enum VaultError {
Scope(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.
///
/// `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; empty admits everything
/// under `scope` that is not excluded.
pub include: Vec<String>,
/// Vault-relative directories not entered at all.
pub exclude: Vec<String>,
/// 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 bytes, lowercase hex.
sha256: String,
/// Frontmatter title, else the filename stem.
title: String,
/// Everything after the frontmatter block.
body: String,
aliases: Vec<String>,
/// Wikilink targets, left side only.
links: Vec<String>,
/// 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<SnapshotNote>,
}
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<u8> {
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.
pub fn build(profile: &VaultProfile) -> Result<Self, VaultError> {
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)?,
exclude: canonical_dirs(&profile.exclude)?,
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<String, SnapshotNote> = 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;
};
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<SnapshotNote> = notes.into_values().collect();
Ok(Self {
id: snapshot_id(&canonical, &notes),
profile: canonical,
notes,
})
}
/// Writes this snapshot as `<id>.cc` under `directory`, unless that file is
/// already there, in which case nothing is touched. The file appears whole
/// or not at all.
pub fn import_into(&self, directory: &Path) -> Result<ImportOutcome, VaultError> {
let path = directory.join(format!("{}.cc", self.id));
if path.exists() {
return Ok(ImportOutcome::AlreadyImported(self.id.clone()));
}
std::fs::create_dir_all(directory).map_err(|_| VaultError::Store)?;
let partial = directory.join(format!("{}.cc.partial", self.id));
let _ = std::fs::remove_file(&partial);
{
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)?;
}
std::fs::rename(&partial, &path).map_err(|_| VaultError::Store)?;
Ok(ImportOutcome::Imported(self.id.clone()))
}
/// 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.
pub fn load(directory: &Path, id: &SnapshotId) -> Result<Self, VaultError> {
let path = directory.join(format!("{id}.cc"));
if !path.is_file() {
return Err(VaultError::NotImported);
}
let store = OwnedRedbMessagePackBackingStore::new(&path).map_err(|_| VaultError::Store)?;
let rows = store.pull_all().map_err(|_| VaultError::Store)?;
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)
}
}
/// 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, &note.reference);
field(&mut digest, &note.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<String> {
let path = Path::new(text.trim());
if path.is_absolute()
|| path
.components()
.any(|part| !matches!(part, Component::Normal(_)))
{
return None;
}
Some(
path.components()
.map(|part| part.as_os_str().to_string_lossy().nfc().collect::<String>())
.collect::<Vec<_>>()
.join("/"),
)
}
fn canonical_dirs(dirs: &[String]) -> Result<Vec<String>, VaultError> {
let mut clean = BTreeSet::new();
for dir in dirs {
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('/'))
}
/// `(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::<String>();
let child = if relative.is_empty() {
name.clone()
} else {
format!("{relative}/{name}")
};
if metadata.is_dir() {
if name.starts_with('.')
|| profile.exclude.iter().any(|dir| is_under(&child, dir))
|| (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")
&& (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<VaultNote>,
notes: Vec<SnapshotNote>,
/// 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 +432,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<Self, VaultError> {
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<Self, VaultError> {
let scope = relative_dir(scope).ok_or_else(|| VaultError::Scope(scope.to_owned()))?;
let notes: Vec<SnapshotNote> = snapshot
.notes
.iter()
.filter(|note| scope.is_empty() || is_under(&note.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<PathBuf> = 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::<Vec<_>>()
.join("/");
if reference.trim() != reference || reference.is_empty() {
continue;
}
let stem = path
let mut by_key: BTreeMap<String, Vec<usize>> = BTreeMap::new();
for (index, note) in notes.iter().enumerate() {
let stem = Path::new(&note.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<String> = vec![stem, title.clone()];
keys.extend(aliases);
notes.push((
VaultNote {
reference,
title,
body: body.to_owned(),
links,
},
keys,
));
}
let mut by_key: BTreeMap<String, Vec<usize>> = BTreeMap::new();
for (index, (_, keys)) in notes.iter().enumerate() {
for key in keys {
for key in [stem, note.title.clone()].iter().chain(&note.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 +579,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<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;
}
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 +728,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, VaultError> {
VaultEvidenceSource::from_snapshot(&VaultSnapshot::build(&profile(root))?, scope)
}
fn fixture() -> tempfile::TempDir {
let directory = tempfile::tempdir().unwrap();
let root = directory.path();
@ -505,7 +780,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 +838,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 +893,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 +922,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 +988,7 @@ mod tests {
"quarry stone quarry stone\n",
);
}
let source = VaultEvidenceSource::open(root, "").unwrap();
let source = open(root, "").unwrap();
let mut referents: Vec<String> = (0..MAX_VAULT_RECEIPTS - 1)
.map(|index| format!("plain{index}"))
@ -739,13 +1014,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 +1042,241 @@ 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");
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", "<div class=\"card\"><p>raw html stays</p></div>\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("<p>raw html stays</p>"));
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());
}
/// 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"]),
("zyphos", "Zyphos", vec!["quartz-site", "site", "tools", "state", "notes", "node_modules"]),
("eusocial-interbeing", "Zyphos/Eusocial Interbeing", vec![]),
("delvehold", "Delvehold/Delvehold", 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());
println!("SMOKE {name} notes={} id={}", built.note_count(), built.id());
}
}
}