From 51363eaccf15609faf37bfb18d3d4bb589949a23 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:10:30 +0100 Subject: [PATCH] Library: production vault profiles in one table, recorded current import and premise on the snapshot, elaborator takes its evidence, sweep takes a session bound Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/controllers.rs | 76 ++++----- crates/ghostlight/src/elaboration.rs | 15 +- crates/ghostlight/src/lib.rs | 4 +- crates/ghostlight/src/vault.rs | 222 +++++++++++++++++++++++---- 4 files changed, 244 insertions(+), 73 deletions(-) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 0d3f841..db8931a 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -3231,14 +3231,15 @@ impl ControllerRunner { }) } - /// The authoring lane, built from the same ports the decision lanes use. - /// `NullEvidenceSource` is what production supplies until a retrieval organ - /// lands; the bound that buys is stated where the source is defined. - pub fn elaborator(&self) -> ElaborationRunner { + /// The authoring lane, built from the same ports the decision lanes use, + /// reading the evidence the caller's timeline is bound to. A world with no + /// vault passes `NullEvidenceSource`, whose bound is stated where it is + /// defined; there is no mode flag choosing between them. + pub fn elaborator(&self, evidence: Arc) -> ElaborationRunner { ElaborationRunner::new( self.elaboration.clone(), Arc::clone(&self.inference), - Arc::new(NullEvidenceSource), + evidence, Arc::clone(&self.work), self.models.elaborator.clone(), ) @@ -3248,8 +3249,7 @@ impl ControllerRunner { /// same work store. The port is not one this runner holds: it carries the /// owner's verified evidence and therefore belongs to the request that /// asked for the work, and the evidence source is supplied by that request - /// too. `NullEvidenceSource` stays the elaborator's; there is no mode flag - /// choosing between them. + /// too. pub fn seeder( &self, port: SeedPort, @@ -14272,7 +14272,7 @@ mod tests { let runner = sweep_runner(&mailbox, port.clone(), store.clone()); let sweep = tokio::spawn({ let permits = permits.clone(); - async move { runner.sweep(permits).await } + async move { runner.sweep(permits, usize::MAX).await } }); port.entered.acquire_many(2).await.unwrap().forget(); @@ -14331,7 +14331,7 @@ mod tests { let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); let sweep = tokio::spawn({ let permits = permits.clone(); - async move { runner.sweep(permits).await } + async move { runner.sweep(permits, usize::MAX).await } }); for _ in 0..2 { @@ -14371,7 +14371,7 @@ mod tests { let runner = sweep_runner(&mailbox, port.clone(), store.clone()); let sweep = tokio::spawn({ let permits = permits.clone(); - async move { runner.sweep(permits).await } + async move { runner.sweep(permits, usize::MAX).await } }); store.listed.acquire().await.unwrap().forget(); @@ -14411,7 +14411,7 @@ mod tests { let port = Arc::new(port); let store = fresh_store(); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(permits).await.unwrap(); + runner.sweep(permits, usize::MAX).await.unwrap(); assert_eq!(port.calls(), 1); assert_eq!(*port.free_while_inferring.lock().unwrap(), vec![1]); assert_eq!(elaboration_commands(store.custody_probe().await.unwrap()), 1); @@ -14447,7 +14447,7 @@ mod tests { let port = Arc::new(SweepPort::new(|call, _| idle_round(call))); let store = fresh_store(); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(2)).await.unwrap(); + runner.sweep(pool(2), usize::MAX).await.unwrap(); assert_eq!(port.calls(), 1, "the nested boundary was claimed more than once"); assert_eq!(store.work.lock().unwrap().len(), 1); drop(runner); @@ -14473,7 +14473,7 @@ mod tests { })); let store = fresh_store(); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(2)).await.unwrap(); + runner.sweep(pool(2), usize::MAX).await.unwrap(); assert_eq!(port.calls(), 1, "one deficit, one session"); let first: Vec = store.work.lock().unwrap().keys().copied().collect(); assert_eq!(first.len(), 1); @@ -14481,7 +14481,7 @@ mod tests { assert!(snapshot.subjects.iter().any(|subject| subject.label == "Sere p1")); assert!(snapshot.boundaries.is_empty()); - runner.sweep(pool(2)).await.unwrap(); + runner.sweep(pool(2), usize::MAX).await.unwrap(); assert_eq!(port.calls(), 2, "the second ancestry ran no new session"); let stored = store.work.lock().unwrap(); assert_eq!(stored.len(), 2, "the committed row was adopted"); @@ -14523,7 +14523,7 @@ mod tests { let recording = fresh_store(); let store = ListingProbe::over(recording.clone()); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(permits.clone()).await.unwrap(); + runner.sweep(permits.clone(), usize::MAX).await.unwrap(); assert_eq!(store.listings.load(Ordering::SeqCst), 0, "a Draft world's listing was read"); assert_eq!(port.calls(), 0, "a Draft world reached the provider"); assert!(recording.work.lock().unwrap().is_empty(), "a Draft world gained a row"); @@ -14644,7 +14644,7 @@ mod tests { let port = Arc::new(SweepPort::new(|call, _| idle_round(call))); let store = fresh_store(); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); assert_eq!(port.calls(), 1, "the uncovered boundary ran no session"); let stored = store.work.lock().unwrap(); assert_eq!(stored.len(), 1); @@ -14677,7 +14677,7 @@ mod tests { } })); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - runner.sweep(pool(2)).await.expect("a retryable fault ended the sweep"); + runner.sweep(pool(2), usize::MAX).await.expect("a retryable fault ended the sweep"); assert_eq!(port.calls(), 2); let snapshot = mailbox.snapshot().await.unwrap(); assert!(place_labelled(&snapshot, "The Shed on The Far Road").is_some()); @@ -14711,7 +14711,7 @@ mod tests { let port = Arc::new(SweepPort::new(|call, _| idle_round(call))); let store = fresh_store(); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); assert_eq!(port.calls(), 2, "the deficit and the uncovered boundary are two sessions"); let stored = store.work.lock().unwrap(); let sessions: Vec = stored.values().map(recorded_session).collect(); @@ -14757,7 +14757,7 @@ mod tests { } })); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - runner.sweep(pool(1)).await.expect("a retryable fault ended the sweep"); + runner.sweep(pool(1), usize::MAX).await.expect("a retryable fault ended the sweep"); assert_eq!(port.calls(), 2, "no session started after a retryable fault"); let snapshot = mailbox.snapshot().await.unwrap(); assert_eq!(snapshot.boundaries.len(), 1, "the second session did not commit"); @@ -14820,7 +14820,7 @@ mod tests { calls: std::sync::atomic::AtomicUsize::new(0), }); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - let sweep = tokio::spawn(async move { runner.sweep(pool(2)).await }); + let sweep = tokio::spawn(async move { runner.sweep(pool(2), usize::MAX).await }); port.faulted.acquire().await.unwrap().forget(); port.release.add_permits(1); let result = sweep.await.unwrap(); @@ -14856,7 +14856,7 @@ mod tests { )) })); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - let Err(error) = runner.sweep(pool(1)).await else { + let Err(error) = runner.sweep(pool(1), usize::MAX).await else { panic!("a quarantine-class fault did not end the sweep with an error"); }; assert!(error.requires_quarantine(), "{error:?}"); @@ -14938,7 +14938,7 @@ mod tests { let sweep = tokio::spawn({ let runner = runner.clone(); let permits = permits.clone(); - async move { runner.sweep(permits).await } + async move { runner.sweep(permits, usize::MAX).await } }); port.panicking.acquire().await.unwrap().forget(); port.release.add_permits(1); @@ -14956,7 +14956,7 @@ mod tests { assert_eq!(port.calls.load(Ordering::SeqCst), 2); assert_eq!(permits.available_permits(), 2, "a permit outlived its session"); - runner.sweep(permits.clone()).await.expect("the sweep after a panic did not run"); + runner.sweep(permits.clone(), usize::MAX).await.expect("the sweep after a panic did not run"); assert_eq!(port.calls.load(Ordering::SeqCst), 3); let snapshot = mailbox.snapshot().await.unwrap(); assert!(snapshot.boundaries.is_empty()); @@ -14985,7 +14985,7 @@ mod tests { })); let permits = pool(1); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - let Err(error) = runner.sweep(permits.clone()).await else { + let Err(error) = runner.sweep(permits.clone(), usize::MAX).await else { panic!("a panicking session did not end the sweep with an error"); }; assert!(error.requires_quarantine(), "{error:?}"); @@ -15018,7 +15018,7 @@ mod tests { CultCacheControllerWorkStore::open(directory.path().join("controller-work.cc")).unwrap(), ); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); let (first_id, refused) = { let journal = store.journal.lock().unwrap(); assert_eq!(journal.work.len(), 1); @@ -15039,7 +15039,7 @@ mod tests { "the tick did not move the ancestry" ); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); assert_eq!(port.calls(), 2, "the refused round was repeated or skipped"); { let journal = store.journal.lock().unwrap(); @@ -15095,7 +15095,7 @@ mod tests { CultCacheControllerWorkStore::open(directory.path().join("controller-work.cc")).unwrap(), ); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); let command_id = { let journal = store.journal.lock().unwrap(); assert_eq!(journal.work.len(), 1); @@ -15123,7 +15123,7 @@ mod tests { assert_eq!(after.revision, before.revision + 2); assert_eq!(after.boundaries, before.boundaries, "the commits moved the boundary"); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); assert_eq!(port.calls(), 2); { let journal = store.journal.lock().unwrap(); @@ -15160,7 +15160,7 @@ mod tests { ); let refusing = Arc::new(SweepPort::new(|call, _| refused_round(call))); let runner = sweep_runner(&mailbox, refusing.clone(), store.clone()); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); drop(runner); let ControllerWork::Elaboration(ElaborationCheckpoint::ElaboratorInFlight { command_id, @@ -15203,7 +15203,7 @@ mod tests { let idle = Arc::new(SweepPort::new(|call, _| idle_round(call))); let runner = sweep_runner(&mailbox, idle.clone(), store.clone()); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); assert_eq!(idle.calls(), 0, "the ready row ran a new inference"); let snapshot = mailbox.snapshot().await.unwrap(); assert!(snapshot.boundaries.is_empty(), "the ready row was not submitted"); @@ -15298,13 +15298,13 @@ mod tests { CultCacheControllerWorkStore::open(directory.path().join("controller-work.cc")).unwrap(), ); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - let mut results = vec![runner.sweep(pool(1)).await]; + let mut results = vec![runner.sweep(pool(1), usize::MAX).await]; for tick in 1..=5 { mailbox .submit_clock(CommandId::new(), TickMinutes::new(60).unwrap()) .await .unwrap(); - results.push(runner.sweep(pool(1)).await); + results.push(runner.sweep(pool(1), usize::MAX).await); assert_eq!(port.calls(), tick + 1, "tick {tick}: one inference per sweep"); assert_eq!( store.journal.lock().unwrap().work.len(), @@ -15366,7 +15366,7 @@ mod tests { let other_id = *store.journal.lock().unwrap().work.keys().next().unwrap(); let other_bytes = row_payload(&store, other_id).unwrap(); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); assert_eq!(port.calls(), 2, "the entry built no fresh session"); let journal = store.journal.lock().unwrap(); assert_eq!(journal.work.len(), 2, "the other jurisdiction's row was adopted"); @@ -15399,7 +15399,7 @@ mod tests { Arc::new(SweepPort::new(|call, _| refused_round(call))), scratch.clone(), ); - foreign_runner.sweep(pool(1)).await.unwrap(); + foreign_runner.sweep(pool(1), usize::MAX).await.unwrap(); drop(foreign_runner); drop(foreign_mailbox); foreign_task.await.unwrap(); @@ -15457,7 +15457,7 @@ mod tests { let foreign_bytes = row_payload(&store, command_id).unwrap(); let port = Arc::new(SweepPort::new(|call, _| idle_round(call))); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); assert_eq!(port.calls(), 1, "the entry built no fresh session"); assert_eq!(store.journal.lock().unwrap().work.len(), 2, "the foreign row was adopted"); assert_eq!( @@ -15480,7 +15480,7 @@ mod tests { .unwrap(), ); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); let finished = { let journal = store.journal.lock().unwrap(); let (id, work) = journal.work.iter().next().unwrap(); @@ -15495,7 +15495,7 @@ mod tests { .submit_clock(CommandId::new(), TickMinutes::new(60).unwrap()) .await .unwrap(); - runner.sweep(pool(1)).await.unwrap(); + runner.sweep(pool(1), usize::MAX).await.unwrap(); assert_eq!(port.calls(), 2, "the finished row was adopted in place of a fresh session"); assert_eq!(store.journal.lock().unwrap().work.len(), 2); assert_eq!(row_payload(&store, finished).unwrap(), finished_bytes); @@ -17685,7 +17685,7 @@ mod tests { models().elaborator, ); elaborator - .sweep(Arc::new(tokio::sync::Semaphore::new(1))) + .sweep(Arc::new(tokio::sync::Semaphore::new(1)), usize::MAX) .await .unwrap(); drop(elaborator); diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index c12b733..e969f74 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -328,7 +328,7 @@ pub trait EvidenceSource: Send + Sync { /// structure and operate on it, but cannot mint quantity, because `admit` /// requires a listed reference and there are none. Creation of quantity without /// provenance should be impossible, not merely discouraged. -pub(crate) struct NullEvidenceSource; +pub struct NullEvidenceSource; #[async_trait] impl EvidenceSource for NullEvidenceSource { @@ -634,8 +634,9 @@ impl ElaborationRunner { /// One sweep: one snapshot, one read of the store's in-flight sessions, one /// claim set, and one session per entry. One permit per session for its - /// whole step, from the ceiling the caller owns. The library holds no - /// concurrency number of its own. + /// whole step, from the ceiling the caller owns, and at most `max_sessions` + /// sessions start, in claim order: the rest of the demand waits for the + /// next sweep. The library holds no concurrency or spend number of its own. /// /// The claim set is the only set of sessions alive only while one sweep /// runs at a time. The caller's loop awaits each sweep; nothing here guards @@ -646,7 +647,11 @@ impl ElaborationRunner { /// returned such an error. A session that panics is that same error: its /// siblings finish, nothing starts after it, and it is returned. Any other /// error ends only its own session. - pub async fn sweep(&self, permits: Arc) -> Result<(), ControllerError> { + pub async fn sweep( + &self, + permits: Arc, + max_sessions: usize, + ) -> Result<(), ControllerError> { let snapshot = self.mailbox.snapshot().await.map_err(snapshot_error)?; if snapshot.phase != WorldPhase::Active { return Ok(()); @@ -658,7 +663,7 @@ impl ElaborationRunner { // it before it starts the session that permit admits. let stopped = Arc::new(AtomicBool::new(false)); let mut running = JoinSet::new(); - for (command_id, session) in entries { + for (command_id, session) in entries.into_iter().take(max_sessions) { if stopped.load(Ordering::SeqCst) { break; } diff --git a/crates/ghostlight/src/lib.rs b/crates/ghostlight/src/lib.rs index 1f25445..bc45a01 100644 --- a/crates/ghostlight/src/lib.rs +++ b/crates/ghostlight/src/lib.rs @@ -102,7 +102,7 @@ pub use aetheria::{ pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover}; pub use elaboration::{ ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, EvidenceError, EvidenceQuery, - EvidenceReceipt, EvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row, + EvidenceReceipt, EvidenceSource, NullEvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row, }; pub use grammar::{ GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb, @@ -145,7 +145,7 @@ pub use table::{ }; pub use vault::{ ImportOutcome, SnapshotId, VAULT_PROFILE_SCHEMA, VAULT_SNAPSHOT_SCHEMA, VaultError, - VaultEvidenceSource, VaultProfile, VaultSnapshot, + VaultEvidenceSource, VaultProfile, VaultSnapshot, production_profile, production_vault_names, }; pub use verse::{ CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, ProviderCallRecord, diff --git a/crates/ghostlight/src/vault.rs b/crates/ghostlight/src/vault.rs index c545deb..0ed5d20 100644 --- a/crates/ghostlight/src/vault.rs +++ b/crates/ghostlight/src/vault.rs @@ -75,8 +75,8 @@ pub enum VaultError { /// 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. +/// Production profiles are `PRODUCTION_VAULTS` below; 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 @@ -100,6 +100,66 @@ pub struct VaultProfile { pub scope: String, } +/// A vault production serves: its name, its root under the host's vault base, +/// and what is never lore. The one place a production profile is written; the +/// base directory is the host's own, so the same table builds on a workstation +/// and on a server. +struct ProductionVault { + name: &'static str, + root: &'static str, + exclude: &'static [&'static str], +} + +const PRODUCTION_VAULTS: [ProductionVault; 4] = [ + ProductionVault { + name: "aetheria", + root: "AetheriaLore/Aetheria", + exclude: &[ + "Brainstorming", + "Game Design", + "Spoilers.md", + "static", + "Stories/How Branching Stories Are Made.md", + "Stories/*/Coordinator Strategy.md", + "Stories/*/Branch Map.md", + ], + }, + // Eusocial Interbeing is the Zyphos setting (ruling vault-profile-zyphos); + // the Zyphos repository around it is machinery. + ProductionVault { + name: "zyphos", + root: "Zyphos/Eusocial Interbeing", + exclude: &["Game Design", "Inspirations"], + }, + ProductionVault { + name: "delvehold", + root: "Delvehold/Delvehold", + exclude: &["Game Design", "Documentation"], + }, + ProductionVault { + name: "avatar", + root: "Avatar", + exclude: &[], + }, +]; + +/// The names of the vaults production serves. +pub fn production_vault_names() -> impl Iterator { + PRODUCTION_VAULTS.iter().map(|vault| vault.name) +} + +/// The production profile of `name`, rooted under `base`, or `None` for a name +/// production does not serve. +pub fn production_profile(name: &str, base: &Path) -> Option { + let vault = PRODUCTION_VAULTS.iter().find(|vault| vault.name == name)?; + Some(VaultProfile { + name: vault.name.into(), + root: base.join(vault.root), + exclude: vault.exclude.iter().map(|text| (*text).to_owned()).collect(), + ..VaultProfile::default() + }) +} + /// 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)] @@ -110,6 +170,16 @@ impl SnapshotId { pub fn as_str(&self) -> &str { &self.0 } + + /// The id a stored name spells: sixty-four lowercase hex digits, nothing + /// that could name another path. + pub fn parse(text: &str) -> Result { + if text.len() == 64 && text.bytes().all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) { + Ok(Self(text.to_owned())) + } else { + Err(VaultError::Corrupt) + } + } } impl std::fmt::Display for SnapshotId { @@ -335,6 +405,52 @@ impl VaultSnapshot { read } + /// Records this snapshot as the one `profile`'s last import produced: the + /// file `.current` in the store holds its id. The server reads + /// this pointer and never a vault directory; only an importer writes it. + pub fn record_current(&self, directory: &Path) -> Result<(), VaultError> { + let path = current_path(directory, &self.profile.name)?; + let partial = directory.join(format!("{}.current.{}.partial", self.profile.name, unique_suffix())); + let written = std::fs::write(&partial, self.id.as_str()) + .and_then(|()| std::fs::rename(&partial, &path).or_else(|_| { + let _ = std::fs::remove_file(&path); + std::fs::rename(&partial, &path) + })) + .map_err(|_| VaultError::Store); + let _ = std::fs::remove_file(&partial); + written + } + + /// The id the last import of `profile` recorded in `directory`. + pub fn current_id(directory: &Path, profile: &str) -> Result { + let text = std::fs::read_to_string(current_path(directory, profile)?) + .map_err(|_| VaultError::NotImported)?; + SnapshotId::parse(text.trim()) + } + + /// A deterministic premise for a seed given no brief: the first + /// `MAX_EXCERPT_CHARS` of the vault's entry note. The entry note is the + /// shallowest `index` note, else the shallowest note named for the + /// vault's scope or title, else the first note by path; a vault of no + /// notes has none. + pub fn premise(&self) -> Option { + let depth = |note: &&SnapshotNote| note.reference.matches('/').count(); + let stem = |note: &SnapshotNote| { + Path::new(¬e.reference) + .file_stem() + .map(|value| value.to_string_lossy().to_lowercase()) + .unwrap_or_default() + }; + let entry = self + .notes + .iter() + .filter(|note| stem(note) == "index") + .min_by_key(|note| depth(note)) + .or_else(|| self.notes.iter().min_by_key(|note| depth(note)))?; + let text: String = entry.body.trim().chars().take(MAX_EXCERPT_CHARS).collect(); + (!text.is_empty()).then_some(text) + } + 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)?; @@ -363,6 +479,17 @@ fn unique_suffix() -> String { } /// The lock file the store leaves beside the file it opened. +/// `.current` in a store directory. A profile name is lowercase +/// ASCII letters, digits and hyphens: it is a file name and never a path. +fn current_path(directory: &Path, profile: &str) -> Result { + if profile.is_empty() + || !profile.bytes().all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-')) + { + return Err(VaultError::NotImported); + } + Ok(directory.join(format!("{profile}.current"))) +} + fn sidecar(path: &Path) -> PathBuf { let mut name = path.as_os_str().to_owned(); name.push(".lock"); @@ -1683,37 +1810,76 @@ mod tests { )); } + /// The import records which snapshot a profile last produced; the server + /// reads that record and nothing else. A name that is not a file name, or a + /// record that is not an id, is refused. + #[test] + fn an_import_records_its_snapshot_as_the_profiles_current_one() { + let vault = fixture(); + let built = snapshot(vault.path()); + let store = tempfile::tempdir().unwrap(); + built.import_into(store.path()).unwrap(); + assert!(matches!( + VaultSnapshot::current_id(store.path(), "fixture"), + Err(VaultError::NotImported) + )); + built.record_current(store.path()).unwrap(); + built.record_current(store.path()).unwrap(); + assert_eq!(&VaultSnapshot::current_id(store.path(), "fixture").unwrap(), built.id()); + for name in ["", "../fixture", "Fixture", "a/b"] { + assert!( + matches!(VaultSnapshot::current_id(store.path(), name), Err(VaultError::NotImported)), + "{name:?}" + ); + } + std::fs::write(store.path().join("fixture.current"), "../../etc/passwd").unwrap(); + assert!(matches!( + VaultSnapshot::current_id(store.path(), "fixture"), + Err(VaultError::Corrupt) + )); + } + + /// The seed's premise is the shallowest index note's opening, bounded. + #[test] + fn the_premise_is_the_entry_notes_opening() { + let vault = fixture(); + assert_eq!(snapshot(vault.path()).premise().as_deref(), Some("Public index.")); + let long = tempfile::tempdir().unwrap(); + write(long.path(), "Zed.md", &"x".repeat(MAX_EXCERPT_CHARS + 50)); + assert_eq!(snapshot(long.path()).premise().unwrap().chars().count(), MAX_EXCERPT_CHARS); + let empty = tempfile::tempdir().unwrap(); + assert_eq!(snapshot(empty.path()).premise(), None); + } + + /// The production table is the one place a profile is written: Zyphos is + /// Eusocial Interbeing without its design and inspiration folders, and + /// every name is a valid pointer name. + #[test] + fn the_production_table_names_four_vaults_rooted_under_the_hosts_base() { + let base = Path::new("/vaults"); + assert_eq!( + production_vault_names().collect::>(), + ["aetheria", "zyphos", "delvehold", "avatar"] + ); + let zyphos = production_profile("zyphos", base).unwrap(); + assert_eq!(zyphos.root, base.join("Zyphos/Eusocial Interbeing")); + assert_eq!(zyphos.exclude, ["Game Design", "Inspirations"]); + assert!(production_profile("nowhere", base).is_none()); + let store = Path::new("/store"); + for name in production_vault_names() { + assert!(current_path(store, name).is_ok(), "{name}"); + } + } + /// Real vaults, read-only. `GHOSTLIGHT_VAULT_SMOKE` names a directory that - /// holds byte-for-byte copies of `AetheriaLore`, `Zyphos` and `Delvehold`. + /// holds byte-for-byte copies of `AetheriaLore`, `Zyphos`, `Delvehold` and + /// `Avatar`, laid out as the production table's roots expect. #[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() - }; + for name in production_vault_names() { + let profile = production_profile(name, &base).unwrap(); let built = VaultSnapshot::build(&profile).unwrap(); let again = VaultSnapshot::build(&profile).unwrap(); assert_eq!(built.id(), again.id());