From 75fdd958aa08ef828517a43f14cd811045fd9256 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:53:06 +0100 Subject: [PATCH 01/12] 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 --- crates/ghostlight/src/lib.rs | 5 +- crates/ghostlight/src/vault.rs | 818 ++++++++++++++++++++++++++------- 2 files changed, 665 insertions(+), 158 deletions(-) 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..7a32808 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,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, + /// Vault-relative directories not entered at all. + 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 bytes, 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. + 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)?, + 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 = 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 = notes.into_values().collect(); + Ok(Self { + id: snapshot_id(&canonical, ¬es), + profile: canonical, + notes, + }) + } + + /// Writes this snapshot as `.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 { + 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 { + 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, ¬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.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::()) + .collect::>() + .join("/"), + ) +} + +fn canonical_dirs(dirs: &[String]) -> Result, 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::(); + 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, + 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 +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 { - 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 +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) -> 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::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 = (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", "

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()); + } + + /// 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()); + } } } From 4f53151e3d929cc09d62b7a6a80e8c156f623698 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:55:36 +0100 Subject: [PATCH 02/12] vault test: name the files an import leaves --- crates/ghostlight/src/vault.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ghostlight/src/vault.rs b/crates/ghostlight/src/vault.rs index 7a32808..0b7f6c8 100644 --- a/crates/ghostlight/src/vault.rs +++ b/crates/ghostlight/src/vault.rs @@ -1107,7 +1107,7 @@ mod tests { names }; let names = listing(); - assert_eq!(names.len(), 1, "an import leaves exactly one file"); + assert_eq!(names.len(), 1, "an import leaves exactly one file: {names:?}"); let again = snapshot(vault.path()); assert_eq!( From ddab6c93bd29a9da3da120f48ae45e6661e04f6a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:58:57 +0100 Subject: [PATCH 03/12] vault import: remove the store's lock sidecar --- crates/ghostlight/src/vault.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ghostlight/src/vault.rs b/crates/ghostlight/src/vault.rs index 0b7f6c8..f69381c 100644 --- a/crates/ghostlight/src/vault.rs +++ b/crates/ghostlight/src/vault.rs @@ -267,6 +267,8 @@ impl VaultSnapshot { .map_err(|_| VaultError::Store)?; } std::fs::rename(&partial, &path).map_err(|_| VaultError::Store)?; + // The store leaves its lock sidecar beside the file it created. + let _ = std::fs::remove_file(directory.join(format!("{}.cc.partial.lock", self.id))); Ok(ImportOutcome::Imported(self.id.clone())) } From 6df910a92579566ee833cde39bf07f9090aef9d6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 18:01:27 +0100 Subject: [PATCH 04/12] vault smoke: add the Avatar vault --- crates/ghostlight/src/vault.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ghostlight/src/vault.rs b/crates/ghostlight/src/vault.rs index f69381c..ae6901b 100644 --- a/crates/ghostlight/src/vault.rs +++ b/crates/ghostlight/src/vault.rs @@ -1267,6 +1267,7 @@ mod tests { ("zyphos", "Zyphos", vec!["quartz-site", "site", "tools", "state", "notes", "node_modules"]), ("eusocial-interbeing", "Zyphos/Eusocial Interbeing", vec![]), ("delvehold", "Delvehold/Delvehold", vec![]), + ("avatar", "Avatar", vec![]), ]; for (name, relative, exclude) in cases { let profile = VaultProfile { From 12f4f17ccf9af5431f7885e895374f54d8d1214e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:59:00 +0100 Subject: [PATCH 05/12] Connector lane speaks model-connector v4: delete codex-connector and its v2 port, typed refusals, failures and usage, controller_work.v19 The v2 CodexConnectorInferencePort and the codex-connector dependency are deleted. ConnectorInferencePort speaks model-connector v4 to claude-connector, maps every Refusal and FailureKind to a typed InferenceFaultClass and reports Usage as TokenUsage. The SDK prefix claims a model only when the sidecar is configured, and open_inference refuses a sidecar that would take a connector model. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 459 ++++++++++- Cargo.toml | 2 +- crates/ghostlight-verse/src/main.rs | 3 + crates/ghostlight/Cargo.toml | 2 +- crates/ghostlight/src/controllers.rs | 877 ++++++++++++++++----- crates/ghostlight/src/elaboration.rs | 24 +- crates/ghostlight/src/local_inference.rs | 83 +- crates/ghostlight/src/patch.rs | 4 +- crates/ghostlight/src/sdk_inference.rs | 134 ++-- crates/ghostlight/src/table.rs | 10 +- crates/ghostlight/src/tool_schema.rs | 6 +- crates/ghostlight/src/verse/calls.rs | 28 +- crates/ghostlight/src/verse/calls/tests.rs | 65 +- crates/ghostlight/src/verse/run/tests.rs | 2 +- 14 files changed, 1289 insertions(+), 410 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 09a0b20..584c27c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -52,6 +52,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -82,10 +91,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] -name = "base64" -version = "0.23.1" +name = "base64ct" +version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "bitflags" @@ -172,20 +181,10 @@ dependencies = [ ] [[package]] -name = "codex-connector" -version = "0.1.0" -source = "git+https://github.com/GameCult/CodexConnector.git?rev=68fe94b9475823de92ed766a97ea962d48723708#68fe94b9475823de92ed766a97ea962d48723708" -dependencies = [ - "aes-gcm", - "base64 0.23.1", - "rand_core 0.6.4", - "rmp-serde", - "serde", - "serde_json", - "sha2", - "thiserror", - "zeroize", -] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" [[package]] name = "core-foundation-sys" @@ -238,7 +237,7 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a01 dependencies = [ "anyhow", "chrono", - "cultcache-rs-derive", + "cultcache-rs-derive 0.1.0", "fs2", "redb", "rmp-serde", @@ -249,6 +248,26 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "cultcache-rs" +version = "0.3.1" +source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" +dependencies = [ + "anyhow", + "chrono", + "cultcache-rs-derive 0.2.0", + "fs2", + "redb", + "rmp-serde", + "serde", + "serde_bytes", + "serde_json", + "serde_stacker", + "stacker", + "uuid", + "windows-sys 0.59.0", +] + [[package]] name = "cultcache-rs-derive" version = "0.1.0" @@ -259,6 +278,78 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "cultcache-rs-derive" +version = "0.2.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "cultnet-rs" +version = "0.2.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" +dependencies = [ + "aes-gcm", + "anyhow", + "base64", + "chrono", + "cultcache-rs 0.3.1", + "ed25519-dalek", + "hmac", + "rand 0.9.5", + "rmp-serde", + "rmpv", + "serde", + "serde_bytes", + "serde_json", + "sha2", + "socket2 0.5.10", + "uuid", + "windows-sys 0.61.2", + "zeroize", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + [[package]] name = "digest" version = "0.10.7" @@ -267,6 +358,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -280,6 +372,36 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + [[package]] name = "errno" version = "0.3.14" @@ -296,6 +418,12 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "find-msvc-tools" version = "0.1.11" @@ -404,6 +532,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -413,7 +553,7 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", + "r-efi 6.0.0", "rand_core 0.10.1", "wasm-bindgen", ] @@ -434,9 +574,9 @@ version = "0.1.0" dependencies = [ "async-trait", "chrono", - "codex-connector", - "cultcache-rs", + "cultcache-rs 0.1.0", "ghostlight-persona-projection", + "model-connector", "reqwest", "rmp-serde", "rmpv", @@ -475,6 +615,15 @@ dependencies = [ "tokio", ] +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "http" version = "1.5.0" @@ -556,7 +705,7 @@ version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ - "base64 0.22.1", + "base64", "bytes", "futures-channel", "futures-util", @@ -567,7 +716,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2", + "socket2 0.6.5", "tokio", "tower-service", "tracing", @@ -789,6 +938,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "model-connector" +version = "0.1.0" +source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=edf2f8e03cbb61df385b9b145b46f676ce3b70d5#edf2f8e03cbb61df385b9b145b46f676ce3b70d5" +dependencies = [ + "aes-gcm", + "base64", + "cultnet-rs", + "rand_core 0.6.4", + "rmp-serde", + "rmpv", + "schemars", + "serde", + "serde_bytes", + "serde_json", + "sha2", + "thiserror", + "zeroize", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -798,6 +967,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -845,6 +1023,16 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "polyval" version = "0.6.2" @@ -866,6 +1054,15 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -875,6 +1072,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quinn" version = "0.11.11" @@ -888,7 +1095,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls", - "socket2", + "socket2 0.6.5", "thiserror", "tokio", "tracing", @@ -904,7 +1111,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand", + "rand 0.10.2", "rand_pcg", "ring", "rustc-hash", @@ -926,7 +1133,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2", + "socket2 0.6.5", "tracing", "windows-sys 0.61.2", ] @@ -940,12 +1147,28 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + [[package]] name = "rand" version = "0.10.2" @@ -957,6 +1180,16 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -966,6 +1199,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "rand_core" version = "0.10.1" @@ -999,13 +1241,33 @@ dependencies = [ "bitflags", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "reqwest" version = "0.12.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ - "base64 0.22.1", + "base64", "bytes", "futures-core", "futures-util", @@ -1080,6 +1342,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417" dependencies = [ "rmp", + "serde", + "serde_bytes", ] [[package]] @@ -1088,6 +1352,15 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.4" @@ -1148,12 +1421,43 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.3", +] + [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -1194,6 +1498,17 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "serde_json" version = "1.0.151" @@ -1207,6 +1522,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_stacker" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a" +dependencies = [ + "serde", + "serde_core", + "stacker", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -1246,6 +1572,15 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "slab" version = "0.4.12" @@ -1258,6 +1593,16 @@ version = "1.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "socket2" version = "0.6.5" @@ -1268,12 +1613,35 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "subtle" version = "2.6.1" @@ -1392,7 +1760,7 @@ dependencies = [ "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.6.5", "tokio-macros", "windows-sys 0.61.2", ] @@ -1613,6 +1981,15 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.127" @@ -1882,6 +2259,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "writeable" version = "0.6.4" @@ -1911,6 +2294,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" diff --git a/Cargo.toml b/Cargo.toml index aa81258..4af483e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,7 @@ version = "0.1.0" anyhow = "1" async-trait = "0.1" chrono = { version = "0.4", features = ["serde"] } -codex-connector = { git = "https://github.com/GameCult/CodexConnector.git", rev = "68fe94b9475823de92ed766a97ea962d48723708" } +model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5" } cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } rmp-serde = "1.3" diff --git a/crates/ghostlight-verse/src/main.rs b/crates/ghostlight-verse/src/main.rs index 9c70d06..29e93fc 100644 --- a/crates/ghostlight-verse/src/main.rs +++ b/crates/ghostlight-verse/src/main.rs @@ -341,6 +341,9 @@ fn lane_fault(error: &ControllerOpenError) -> &'static str { "--key-file is unreadable, empty, or not one run of visible ASCII" } ControllerOpenError::SharedModelPrefix { .. } => "two inference lanes claim one model prefix", + ControllerOpenError::SidecarClaimsConnectorModel { .. } => { + "the SDK sidecar prefix claims a connector model" + } ControllerOpenError::EmptyModelPrefix { .. } => "an inference lane's model prefix is empty", } } diff --git a/crates/ghostlight/Cargo.toml b/crates/ghostlight/Cargo.toml index 7fca500..f366f56 100644 --- a/crates/ghostlight/Cargo.toml +++ b/crates/ghostlight/Cargo.toml @@ -7,7 +7,7 @@ license.workspace = true [dependencies] async-trait.workspace = true chrono.workspace = true -codex-connector.workspace = true +model-connector.workspace = true cultcache-rs.workspace = true ghostlight-persona-projection = { path = "../ghostlight-persona-projection" } reqwest.workspace = true diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 97d7edd..19df3df 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -31,11 +31,12 @@ use crate::{ }; use async_trait::async_trait; use chrono::Utc; -use codex_connector::{ - CodexConnectorClient, CodexConnectorClientError, CodexInputItem, CodexProviderRequest, - CodexRefusal, CodexToolChoice, CodexToolDefinition, CodexTransportDisposition, - CodexTransportEventPayload, CodexTransportInvocation, CodexTransportOutcome, - provider_request_sha256, +use model_connector::{ + ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest, ReasoningEffort, + Refusal, + ToolChoice, ToolDefinition, TransportDisposition, TransportEventPayload, TransportInvocation, + TransportResult, + TransportOutcome, provider_request_sha256, }; use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; use ghostlight_persona_projection::{ @@ -78,11 +79,11 @@ pub(super) const CELL_TOOL_STEP_BUDGET: usize = 2; /// carried by tool identity, never by a model-written argument. const HANDLE_SEPARATOR: &str = "__"; const PERSONA_WORD_BUDGET: usize = 180; -const CONTROLLER_WORK_ROW: &str = "controller_work.v18"; +const CONTROLLER_WORK_ROW: &str = "controller_work.v19"; /// The `controller-work` state slot's schema. `pub` so a deploy recipe (or a /// test pinning one) can check /// itself against this constant instead of hand-copying the version number. -pub const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v18"; +pub const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v19"; /// The Interpreter's byte-span capture tool. It is not the generated `speak` /// affordance tool: one captures an utterance out of preserved prose, the other @@ -124,7 +125,7 @@ pub enum InferencePurpose { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct InferenceRequest { purpose: InferencePurpose, - provider: CodexProviderRequest, + provider: ProviderRequest, } impl InferenceRequest { @@ -141,7 +142,7 @@ impl InferenceRequest { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct PreparedInference { pub purpose: InferencePurpose, - pub(super) invocation: CodexTransportInvocation, + pub(super) invocation: TransportInvocation, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -253,6 +254,28 @@ pub enum InferenceFaultClass { /// A recording port refused the call because it could pass the run's /// token cap. Nothing was sent; the run stops and does not retry. BudgetExhausted, + /// The connector does not allow the requested model. Terminal: the lane's + /// model name is wrong for this connector. + ModelNotAllowed, + /// The requested output allowance exceeds the connector's bound. + OutputBound, + /// The request is larger than the connector will carry. + PayloadBound, + /// The connector found another provider's reasoning state in the request. + ForeignReasoningState, + /// The provider is refusing requests until its own window resets. + ProviderRejected, + /// The provider answered that the request is too frequent. + RateLimited, + /// The provider could not be reached or answered with an outage. + Unavailable, + /// The provider judged the request itself invalid. Terminal. + InvalidRequest, + /// The provider rejected the connector's credential. Terminal. + Authentication, + /// The provider failed in a way it did not type, or its result could not + /// be carried. Terminal. + ProviderFailed, Unclassified, } @@ -340,7 +363,7 @@ impl InferenceFault { } /// A call id the connector's own validators would refuse cannot be persisted: -/// the evaluator rebuilds these into `CodexInputItem`s that `validate()` will +/// the evaluator rebuilds these into `InputItem`s that `validate()` will /// see again. Both the local and SDK ports police a provider reply against /// this one rule, so there is one copy rather than two that can drift. pub(super) fn call_id_is_valid(call_id: &str) -> bool { @@ -416,16 +439,17 @@ impl TracingInferencePort { out.push_str("-- input --\n"); for item in &request.input { match item { - CodexInputItem::UserText { text } => out.push_str(&format!("[user]\n{text}\n")), - CodexInputItem::AssistantText { text } => { + InputItem::UserText { text } => out.push_str(&format!("[user]\n{text}\n")), + InputItem::AssistantText { text } => { out.push_str(&format!("[assistant]\n{text}\n")); } - CodexInputItem::ToolCall { + InputItem::ToolCall { name, arguments, .. } => out.push_str(&format!("[tool call {name}]\n{arguments}\n")), - CodexInputItem::ToolResult { output, .. } => { + InputItem::ToolResult { output, .. } => { out.push_str(&format!("[tool result]\n{output}\n")); } + InputItem::ReasoningState { .. } => out.push_str("[reasoning state]\n"), } } if !request.tools.is_empty() { @@ -501,7 +525,7 @@ impl PreparedInference { serde_json::to_vec(&request) .map_err(|_| InferenceFault::new("an inference request could not be serialized"))?; let purpose = request.purpose; - let invocation = CodexTransportInvocation::new( + let invocation = TransportInvocation::new( caller_runtime_id, expires_at_unix_ms, Sha256::digest(request_bytes).into(), @@ -515,16 +539,20 @@ impl PreparedInference { } } -/// Production lowering to CodexConnector. There is deliberately no retry, -/// fallback model, output repair, or stage registry here; transport failure is -/// returned to the owning controller flow with its pending evidence intact. +/// Production lowering to claude-connector over the model-connector v4 +/// contract. The port is one shot: it makes no retry, fallback model or output +/// repair. Whether a fault may be tried again is the fault's own disposition, +/// derived here from the typed refusal or failure kind and never from a +/// transport string; the owning flow decides when, and a run's token cap bounds +/// it. This is the only code that reads the connector key or speaks to the +/// connector. #[derive(Clone)] -struct CodexConnectorInferencePort { - client: CodexConnectorClient, +struct ConnectorInferencePort { + client: ConnectorClient, caller_runtime_id: String, } -impl CodexConnectorInferencePort { +impl ConnectorInferencePort { fn new( endpoint: SocketAddr, connection_key: String, @@ -533,16 +561,16 @@ impl CodexConnectorInferencePort { let caller_runtime_id = caller_runtime_id.into(); if caller_runtime_id.trim().is_empty() || caller_runtime_id.trim() != caller_runtime_id { return Err(InferenceFault::new( - "CodexConnector caller runtime must be one exact nonempty identity", + "the connector caller runtime must be one exact nonempty identity", )); } - let client = CodexConnectorClient::new( + let client = ConnectorClient::new( endpoint, connection_key, MAX_CONNECTOR_FRAME_BYTES, Some(RESPONSE_TIMEOUT), ) - .map_err(|_| InferenceFault::new("the CodexConnector client could not be built"))?; + .map_err(|_| InferenceFault::new("the connector client could not be built"))?; Ok(Self { client, caller_runtime_id, @@ -556,14 +584,14 @@ impl CodexConnectorInferencePort { ) -> Result { let bytes = Zeroizing::new( std::fs::read(path.as_ref()) - .map_err(|_| InferenceFault::new("the CodexConnector key file could not be read"))?, + .map_err(|_| InferenceFault::new("the connector key file could not be read"))?, ); let raw = std::str::from_utf8(bytes.as_slice()) - .map_err(|_| InferenceFault::new("the CodexConnector key file is not UTF-8"))?; + .map_err(|_| InferenceFault::new("the connector key file is not UTF-8"))?; let key = raw.trim_end_matches(['\r', '\n']); if key.is_empty() || key.len() != raw.trim().len() { return Err(InferenceFault::new( - "CodexConnector key file is empty or has surrounding whitespace", + "the connector key file is empty or has surrounding whitespace", )); } Self::new(endpoint, key.to_owned(), caller_runtime_id) @@ -575,84 +603,169 @@ impl CodexConnectorInferencePort { "persisted inference caller does not match the configured runtime identity", )); } - let result = self - .client - .execute(&request.invocation) - .map_err(|error| match error { - CodexConnectorClientError::Connection(_) => { - InferenceFault::retryable("the CodexConnector connection failed") - } - CodexConnectorClientError::InvalidConfig - | CodexConnectorClientError::FrameSize - | CodexConnectorClientError::Encoding - | CodexConnectorClientError::Transport(_) => { - InferenceFault::integrity_violation("the CodexConnector transport failed") - } - })?; - let (events, receipt) = match result.disposition { - CodexTransportDisposition::Refused(reason) => { - return Err(match reason { - CodexRefusal::InFlight => { - InferenceFault::retryable("CodexConnector refused request: in flight") - } - CodexRefusal::Capacity => { - InferenceFault::retryable("CodexConnector refused request: at capacity") - } - CodexRefusal::Expired => { - InferenceFault::new("CodexConnector refused request: expired") - } - CodexRefusal::Indeterminate => { - InferenceFault::new("CodexConnector refused request: indeterminate") - } - CodexRefusal::IdentitySubstitution => InferenceFault::integrity_violation( - "CodexConnector refused request: identity substitution", - ), - CodexRefusal::ProviderDigestSubstitution => InferenceFault::integrity_violation( - "CodexConnector refused request: provider digest substitution", - ), - CodexRefusal::Policy => { - InferenceFault::integrity_violation("CodexConnector refused request: policy") - } - CodexRefusal::ReplayConflict => InferenceFault::integrity_violation( - "CodexConnector refused request: replay conflict", - ), - CodexRefusal::Malformed => InferenceFault::integrity_violation( - "CodexConnector refused request: malformed", - ), - }); - } - CodexTransportDisposition::Transported { events, receipt } => (events, receipt), - }; - if let CodexTransportOutcome::Failed { .. } = &receipt.outcome { - return Err(InferenceFault::new("the Codex provider reported a failed outcome")); + lift_result( + self.client + .execute(&request.invocation) + .map_err(client_fault)?, + ) + } +} + +/// What a connector result becomes: events and reported usage, or the typed +/// fault its refusal or failure kind names. +fn lift_result(result: TransportResult) -> Result { + let (events, receipt) = match result.disposition { + TransportDisposition::Refused(reason) => return Err(refusal_fault(reason)), + TransportDisposition::Transported { events, receipt } => (events, receipt), + }; + let usage = match &receipt.outcome { + TransportOutcome::Completed { usage, .. } => TokenUsage { + // The whole prompt, cache traffic included, as `TokenUsage` + // defines it; the provider counts cache reads and writes apart + // from plain input. + prompt: usage + .input_tokens + .saturating_add(usage.cache_read_tokens) + .saturating_add(usage.cache_write_tokens), + completion: usage.output_tokens, + cached_prompt: Some(usage.cache_read_tokens), + }, + TransportOutcome::Failed { kind, message, .. } => { + // The provider's own words go to the operator log, never into + // the fault: a fault's detail is fixed text. + tracing::warn!(kind = ?kind, message = %message, "the connector reported a failed outcome"); + return Err(failure_fault(*kind)); } - let events = events - .into_iter() - .map(|event| match event.payload { - CodexTransportEventPayload::TextDelta { text } => InferenceEvent::Text(text), - CodexTransportEventPayload::ToolCall { - call_id, - name, - arguments, - } => InferenceEvent::ToolCall { - call_id, - name, - arguments, - }, - }) - .collect(); - let receipt_bytes = rmp_serde::to_vec_named(&receipt) - .map_err(|_| InferenceFault::new("the CodexConnector receipt could not be encoded"))?; - Ok(InferenceOutput { - events, - receipt_digest: format!("sha256:{:x}", Sha256::digest(&receipt_bytes)), - usage: None, + }; + // A reasoning block is opaque and Ghostlight replays no provider + // state, so only text and tool calls become events. + let events = events + .into_iter() + .filter_map(|event| match event.payload { + TransportEventPayload::TextDelta { text } => Some(InferenceEvent::Text(text)), + TransportEventPayload::ToolCall { + call_id, + name, + arguments, + } => Some(InferenceEvent::ToolCall { + call_id, + name, + arguments, + }), + TransportEventPayload::ReasoningState { .. } => None, }) + .collect(); + let receipt_bytes = rmp_serde::to_vec_named(&receipt) + .map_err(|_| InferenceFault::new("the connector receipt could not be encoded"))?; + Ok(InferenceOutput { + events, + receipt_digest: format!("sha256:{:x}", Sha256::digest(&receipt_bytes)), + usage: Some(usage), + }) +} + +/// A client-side failure. A connection that closed, reset, timed out or never +/// opened is retryable: a connector replays a completed request by its id, so +/// asking again cannot double-spend. Everything else means the exchange itself +/// is wrong. +fn client_fault(error: ConnectorClientError) -> InferenceFault { + use std::io::ErrorKind; + match error { + ConnectorClientError::Connection(io) => match io.kind() { + ErrorKind::TimedOut | ErrorKind::WouldBlock => { + InferenceFault::retryable("the connector did not answer in time") + .classed(InferenceFaultClass::Timeout) + } + ErrorKind::UnexpectedEof + | ErrorKind::ConnectionReset + | ErrorKind::ConnectionAborted + | ErrorKind::BrokenPipe => { + InferenceFault::retryable("the connector closed the connection before a reply") + .classed(InferenceFaultClass::NoResponse) + } + _ => InferenceFault::retryable("the connector connection failed") + .classed(InferenceFaultClass::Connect), + }, + ConnectorClientError::InvalidConfig + | ConnectorClientError::FrameSize + | ConnectorClientError::RequestIdTooLong + | ConnectorClientError::Transport(_) => { + InferenceFault::integrity_violation("the connector transport failed") + } + } +} + +/// One fault class per refusal the connector can name. Capacity and in-flight +/// are the connector asking to be tried later. The identity, digest, replay +/// and framing refusals mean the exchange is not what it claims. A model, size +/// or provider refusal is final for this request and stays visible: it is +/// recoverable by an operator, never retried, and not an integrity breach. +fn refusal_fault(reason: Refusal) -> InferenceFault { + match reason { + Refusal::InFlight => InferenceFault::retryable("the connector refused the request: in flight"), + Refusal::Capacity => InferenceFault::retryable("the connector refused the request: at capacity"), + Refusal::Expired => InferenceFault::new("the connector refused the request: expired"), + Refusal::Indeterminate => InferenceFault::new("the connector refused the request: indeterminate"), + Refusal::IdentitySubstitution => InferenceFault::integrity_violation( + "the connector refused the request: identity substitution", + ), + Refusal::ProviderDigestSubstitution => InferenceFault::integrity_violation( + "the connector refused the request: provider digest substitution", + ), + Refusal::ReplayConflict => InferenceFault::integrity_violation( + "the connector refused the request: replay conflict", + ), + Refusal::Malformed => { + InferenceFault::integrity_violation("the connector refused the request: malformed") + } + Refusal::ForeignReasoningState => InferenceFault::integrity_violation( + "the connector refused the request: foreign reasoning state", + ) + .classed(InferenceFaultClass::ForeignReasoningState), + Refusal::ModelNotAllowed => { + InferenceFault::new("the connector does not allow the requested model") + .classed(InferenceFaultClass::ModelNotAllowed) + } + Refusal::OutputBound => { + InferenceFault::new("the requested output exceeds the connector's bound") + .classed(InferenceFaultClass::OutputBound) + } + Refusal::PayloadBound => { + InferenceFault::new("the request exceeds the connector's payload bound") + .classed(InferenceFaultClass::PayloadBound) + } + Refusal::ProviderRejected => { + InferenceFault::new("the provider is refusing requests right now") + .classed(InferenceFaultClass::ProviderRejected) + } + } +} + +/// A provider failure outcome by its typed kind. Rate limits, an unavailable +/// provider and a provider timeout clear with time and are retryable. An +/// invalid request, a failed credential or a provider fault will answer the +/// same way again, so they are terminal. +fn failure_fault(kind: FailureKind) -> InferenceFault { + match kind { + FailureKind::RateLimited => InferenceFault::retryable("the provider rate-limited the request") + .classed(InferenceFaultClass::RateLimited), + FailureKind::Unavailable => InferenceFault::retryable("the provider is unavailable") + .classed(InferenceFaultClass::Unavailable), + FailureKind::Timeout => InferenceFault::retryable("the provider timed out") + .classed(InferenceFaultClass::Timeout), + FailureKind::InvalidRequest => InferenceFault::new("the provider rejected the request as invalid") + .classed(InferenceFaultClass::InvalidRequest), + FailureKind::Authentication => InferenceFault::new("the provider rejected the connector's credential") + .classed(InferenceFaultClass::Authentication), + FailureKind::ResultSize | FailureKind::Provider => { + InferenceFault::new("the provider reported a failed outcome") + .classed(InferenceFaultClass::ProviderFailed) + } } } #[async_trait] -impl InferencePort for CodexConnectorInferencePort { +impl InferencePort for ConnectorInferencePort { fn prepare(&self, request: InferenceRequest) -> Result { PreparedInference::prepare( &self.caller_runtime_id, @@ -665,7 +778,7 @@ impl InferencePort for CodexConnectorInferencePort { let port = self.clone(); tokio::task::spawn_blocking(move || port.execute(request)) .await - .map_err(|_| InferenceFault::new("the CodexConnector worker task failed"))? + .map_err(|_| InferenceFault::new("the connector worker task failed"))? } } @@ -1712,14 +1825,12 @@ fn prose_request_shape_is_valid(request: &PreparedInference) -> bool { provider.input.len() == 1 && matches!( provider.input.first(), - Some(CodexInputItem::UserText { .. }) + Some(InputItem::UserText { .. }) ) && provider.tools.is_empty() - && provider.tool_choice == CodexToolChoice::Auto + && provider.tool_choice == ToolChoice::Auto && !provider.parallel_tool_calls - && provider.output_format_name.is_none() && provider.output_schema_json.is_none() - && provider.previous_response_id.is_none() } fn persona_request_shape_is_valid(request: &PreparedInference) -> bool { @@ -2552,7 +2663,7 @@ impl ControllerModels { pub enum ControllerOpenError { #[error("controller model IDs must be exact nonempty identifiers without whitespace")] InvalidModels, - #[error("CodexConnector controller transport could not open: {0}")] + #[error("the connector transport could not open: {0}")] Connector(#[from] InferenceFault), #[error("controller work journal could not open: {0}")] WorkStore(String), @@ -2566,13 +2677,15 @@ pub enum ControllerOpenError { HostedEndpointNotHttps, #[error("the hosted inference key file is unreadable, empty, or is not one run of visible ASCII")] HostedKeyUnreadable, + #[error("the SDK sidecar prefix claims the connector model `{model}`")] + SidecarClaimsConnectorModel { model: String }, #[error("two inference transports both claim model prefix `{prefix}`")] SharedModelPrefix { prefix: String }, #[error("the {transport} inference transport's model prefix must not be empty")] EmptyModelPrefix { transport: &'static str }, } -/// Everything the CodexConnector transport needs to open, gathered so +/// Everything the connector transport needs to open, gathered so /// `ControllerRunner::open` takes a port rather than building one. pub struct ConnectorBinding { pub endpoint: SocketAddr, @@ -2580,6 +2693,13 @@ pub struct ConnectorBinding { pub caller_runtime_id: String, } +/// Whether a model name is one claude-connector serves: its allow list is the +/// `claude--5-5` family. The connector owns the list; this reads only the +/// naming shape so an overlapping sidecar prefix is refused at open. +fn names_connector_model(model: &str) -> bool { + model.starts_with("claude-") && model.ends_with("-5-5") +} + /// Builds the one port every lane shares. A lane whose model no configured /// backend claims fails here, at open, rather than at its first tick. `models` /// is every model that must route, not just `ControllerModels`'s own fields, @@ -2593,7 +2713,7 @@ pub fn open_inference( models: &[&str], ) -> Result, ControllerOpenError> { let connector: Option> = match connector { - Some(binding) => Some(Arc::new(CodexConnectorInferencePort::from_secret_file( + Some(binding) => Some(Arc::new(ConnectorInferencePort::from_secret_file( binding.endpoint, binding.key_path, binding.caller_runtime_id, @@ -2657,6 +2777,16 @@ pub fn open_inference( prefix: pair[0].to_owned(), }); } + if connector.is_some() && sdk.is_some() { + if let Some(model) = models + .iter() + .find(|model| names_connector_model(model) && model.starts_with(&sdk_model_prefix)) + { + return Err(ControllerOpenError::SidecarClaimsConnectorModel { + model: (*model).to_owned(), + }); + } + } let routed = RoutedInferencePort::new(connector, sdk, sdk_model_prefix, claims); for &model in models { if routed.route(model).is_none() { @@ -5627,7 +5757,7 @@ pub(super) fn tool_decode_need(name: &str, arguments: &str, detail: &str) -> Con } enum InterpreterLoopEvaluation { - Continue { conversation: Vec }, + Continue { conversation: Vec }, Complete { capture: NarrativeCapture }, } @@ -5811,7 +5941,7 @@ fn evaluate_interpreter_loop( prompt: &str, completed: &[InferenceOutput], ) -> Result { - let mut conversation = vec![CodexInputItem::UserText { + let mut conversation = vec![InputItem::UserText { text: prompt.to_owned(), }]; let mut fold = InterpreterFold::new(source.clone()); @@ -5831,7 +5961,7 @@ fn evaluate_interpreter_loop( match event { InferenceEvent::Text(text) => { if !text.is_empty() { - conversation.push(CodexInputItem::AssistantText { text: text.clone() }); + conversation.push(InputItem::AssistantText { text: text.clone() }); } } InferenceEvent::ToolCall { @@ -5840,13 +5970,13 @@ fn evaluate_interpreter_loop( arguments, } => { called_tool = true; - conversation.push(CodexInputItem::ToolCall { + conversation.push(InputItem::ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone(), }); let result = interpreter_tool_result(&mut fold, name, arguments); - conversation.push(CodexInputItem::ToolResult { + conversation.push(InputItem::ToolResult { call_id: call_id.clone(), output: result, }); @@ -5920,7 +6050,7 @@ fn handle_prefix(handle: usize) -> String { /// decided by which tool was called rather than by an argument the model writes. /// A shared tool with a `subject` argument is the forgeable shape: it would let /// one constituent's turn propose for another. -fn cell_catalog_tools(constituents: &[ConstituentWork]) -> Vec { +fn cell_catalog_tools(constituents: &[ConstituentWork]) -> Vec { constituents .iter() .enumerate() @@ -5962,7 +6092,7 @@ struct GroupedCapture { } enum GroupedLoopEvaluation { - Continue { conversation: Vec }, + Continue { conversation: Vec }, Complete { capture: GroupedCapture }, } @@ -6136,7 +6266,7 @@ fn evaluate_grouped_loop( constituents: &[ConstituentWork], completed: &[InferenceOutput], ) -> Result { - let mut conversation = vec![CodexInputItem::UserText { + let mut conversation = vec![InputItem::UserText { text: prompt.to_owned(), }]; let mut fold = GroupedFold::new(); @@ -6154,7 +6284,7 @@ fn evaluate_grouped_loop( match event { InferenceEvent::Text(text) => { if !text.is_empty() { - conversation.push(CodexInputItem::AssistantText { text: text.clone() }); + conversation.push(InputItem::AssistantText { text: text.clone() }); } } InferenceEvent::ToolCall { @@ -6163,13 +6293,13 @@ fn evaluate_grouped_loop( arguments, } => { called_tool = true; - conversation.push(CodexInputItem::ToolCall { + conversation.push(InputItem::ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone(), }); let result = grouped_tool_result(constituents, &mut fold, name, arguments)?; - conversation.push(CodexInputItem::ToolResult { + conversation.push(InputItem::ToolResult { call_id: call_id.clone(), output: result, }); @@ -6245,7 +6375,7 @@ fn grouped_request( round: usize, model: &str, constituents: &[ConstituentWork], - input: Vec, + input: Vec, ) -> Result { tool_request( command_id, @@ -6281,7 +6411,7 @@ fn grouped_pending(checkpoint: GroupedCheckpoint, reason: ControllerPendingReaso } } enum OperationalLoopEvaluation { - Continue { conversation: Vec }, + Continue { conversation: Vec }, Complete { capture: OperationalCapture }, } @@ -6429,7 +6559,7 @@ fn evaluate_operational_loop( granted: &[AffordanceSnapshot], completed: &[InferenceOutput], ) -> Result { - let mut conversation = vec![CodexInputItem::UserText { + let mut conversation = vec![InputItem::UserText { text: prompt.to_owned(), }]; let mut fold = OperationalFold::new(); @@ -6450,7 +6580,7 @@ fn evaluate_operational_loop( match event { InferenceEvent::Text(text) => { if !text.is_empty() { - conversation.push(CodexInputItem::AssistantText { text: text.clone() }); + conversation.push(InputItem::AssistantText { text: text.clone() }); } } InferenceEvent::ToolCall { @@ -6459,13 +6589,13 @@ fn evaluate_operational_loop( arguments, } => { called_tool = true; - conversation.push(CodexInputItem::ToolCall { + conversation.push(InputItem::ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone(), }); let result = operational_tool_result(granted, &mut fold, name, arguments)?; - conversation.push(CodexInputItem::ToolResult { + conversation.push(InputItem::ToolResult { call_id: call_id.clone(), output: result, }); @@ -6643,8 +6773,8 @@ fn persona_request( // constructor. Its only model-visible input is the dedicated natural-prose // prompt plus the smallest nonempty instruction required by the provider // transport contract. - let input = vec![CodexInputItem::UserText { text: prompt }]; - let mut provider = CodexProviderRequest::new( + let input = vec![InputItem::UserText { text: prompt }]; + let mut provider = ProviderRequest::new( provider_request_id( command_id, InferencePurpose::Persona, @@ -6655,16 +6785,15 @@ fn persona_request( conversation_id(command_id, InferencePurpose::Persona, 0)?, model, PERSONA_PROVIDER_INSTRUCTIONS, + 1_200, ); provider.input = input; - provider.reasoning_effort = Some("low".into()); + provider.reasoning_effort = Some(ReasoningEffort::Low); provider.tools = Vec::new(); - provider.tool_choice = CodexToolChoice::Auto; + provider.tool_choice = ToolChoice::Auto; provider.parallel_tool_calls = false; - provider.output_format_name = None; provider.output_schema_json = None; - provider.max_output_tokens = Some(1_200); - Ok(InferenceRequest { + Ok(InferenceRequest { purpose: InferencePurpose::Persona, provider, }) @@ -6678,26 +6807,24 @@ fn text_request( prompt: String, max_output_tokens: u32, ) -> Result { - let input = vec![CodexInputItem::UserText { text: prompt }]; + let input = vec![InputItem::UserText { text: prompt }]; let request = provider_request_id(command_id, purpose, 0, instructions, &input)?; let conversation = conversation_id(command_id, purpose, 0)?; - let mut provider = CodexProviderRequest::new(request, conversation, model, instructions); + let mut provider = ProviderRequest::new(request, conversation, model, instructions, max_output_tokens); provider.input = input; - provider.reasoning_effort = Some("low".into()); + provider.reasoning_effort = Some(ReasoningEffort::Low); provider.tools = Vec::new(); - provider.tool_choice = CodexToolChoice::Auto; + provider.tool_choice = ToolChoice::Auto; provider.parallel_tool_calls = false; - provider.output_format_name = None; provider.output_schema_json = None; - provider.max_output_tokens = Some(max_output_tokens); - Ok(InferenceRequest { purpose, provider }) + Ok(InferenceRequest { purpose, provider }) } fn interpreter_request( command_id: CommandId, round: usize, model: &str, - input: Vec, + input: Vec, ) -> Result { tool_request( command_id, @@ -6716,7 +6843,7 @@ fn operational_request( round: usize, model: &str, granted: &[AffordanceSnapshot], - input: Vec, + input: Vec, ) -> Result { tool_request( command_id, @@ -6752,28 +6879,27 @@ pub(super) fn tool_request( purpose: InferencePurpose, model: &str, instructions: &str, - input: Vec, - tools: Vec, + input: Vec, + tools: Vec, shape: RequestShape, ) -> Result { - let mut provider = CodexProviderRequest::new( + let mut provider = ProviderRequest::new( provider_request_id(command_id, purpose, round, instructions, &input)?, conversation_id(command_id, purpose, round)?, model, instructions, + shape.max_output_tokens, ); provider.input = input; - provider.reasoning_effort = Some("medium".into()); + provider.reasoning_effort = Some(ReasoningEffort::Medium); provider.tools = tools; - provider.tool_choice = CodexToolChoice::Auto; + provider.tool_choice = ToolChoice::Auto; provider.parallel_tool_calls = shape.parallel_tool_calls; - provider.output_format_name = None; provider.output_schema_json = None; - provider.max_output_tokens = Some(shape.max_output_tokens); - Ok(InferenceRequest { purpose, provider }) + Ok(InferenceRequest { purpose, provider }) } -fn interpreter_tools() -> Vec { +fn interpreter_tools() -> Vec { vec![ tool_schema::tool( INTERPRETER_SPEAK_TOOL, @@ -6846,7 +6972,7 @@ fn interpreter_tools() -> Vec { pub(super) fn catalog_tools( prefix: &str, granted: &[AffordanceSnapshot], -) -> Vec { +) -> Vec { let mut tools = affordance_tools(prefix, granted); tools.push(tool_schema::tool( &format!("{prefix}{RECORD_NEED_TOOL}"), @@ -6874,7 +7000,7 @@ pub(super) fn catalog_tools( pub(super) fn affordance_tools( prefix: &str, granted: &[AffordanceSnapshot], -) -> Vec { +) -> Vec { granted .iter() .map(|entry| { @@ -7079,7 +7205,7 @@ pub(super) fn provider_request_id( purpose: InferencePurpose, round: usize, instructions: &str, - input: &[CodexInputItem], + input: &[InputItem], ) -> Result { let content = request_content_digest(instructions, input)?; Ok(format!( @@ -7091,7 +7217,7 @@ pub(super) fn provider_request_id( fn request_content_digest( instructions: &str, - input: &[CodexInputItem], + input: &[InputItem], ) -> Result { let bytes = serde_json::to_vec(&(instructions, input)) .map_err(|error| ControllerError::Serialization(error.to_string()))?; @@ -7141,13 +7267,13 @@ mod tests { let not_utf8 = directory.path().join(CANARY); std::fs::write(¬_utf8, [0xff_u8, 0xfe]).unwrap(); let faults = [ - CodexConnectorInferencePort::from_secret_file(endpoint, directory.path().join("absent").join(CANARY), "runtime") + ConnectorInferencePort::from_secret_file(endpoint, directory.path().join("absent").join(CANARY), "runtime") .err() .expect("a missing key file opened"), - CodexConnectorInferencePort::from_secret_file(endpoint, ¬_utf8, "runtime") + ConnectorInferencePort::from_secret_file(endpoint, ¬_utf8, "runtime") .err() .expect("a key file that is not UTF-8 opened"), - CodexConnectorInferencePort::new(endpoint, "key".into(), format!(" {CANARY} ")) + ConnectorInferencePort::new(endpoint, "key".into(), format!(" {CANARY} ")) .err() .expect("a runtime identity with whitespace opened"), ]; @@ -7167,6 +7293,360 @@ mod tests { super::super::tool_schema::assert_strict(&schema, &tool.name); } } + + // The connector port on model-connector v4. The wire itself is the + // upstream client's; these pin what Ghostlight decides about what comes + // back: which refusal is retryable, which failure is terminal, and what + // usage and log text survive. + + use model_connector::{ + CacheRetention, StopReason, TransportEvent, TransportReceipt, Usage, + }; + + fn receipt(outcome: TransportOutcome) -> TransportReceipt { + TransportReceipt { + schema_id: "gamecult.model.transport_receipt.v4".into(), + request_id: "request-1".into(), + caller_runtime_id: "runtime".into(), + native_request_sha256: [1; 32], + provider_request_sha256: [2; 32], + model: "claude-haiku-5-5".into(), + provider: "anthropic-messages".into(), + foreign_reasoning_dropped: 0, + outcome, + } + } + + fn result_of(disposition: TransportDisposition) -> TransportResult { + TransportResult { + schema_id: "gamecult.model.transport_result.v4".into(), + request_id: "request-1".into(), + caller_runtime_id: "runtime".into(), + disposition, + } + } + + fn refused_with(reason: Refusal) -> InferenceFault { + lift_result(result_of(TransportDisposition::Refused(reason))) + .err() + .expect("a refusal produced an output") + } + + fn failed_with(kind: FailureKind) -> InferenceFault { + lift_result(result_of(TransportDisposition::Transported { + events: Vec::new(), + receipt: Box::new(receipt(TransportOutcome::Failed { + kind, + message: "provider words".into(), + usage: None, + })), + })) + .err() + .expect("a failed outcome produced an output") + } + + /// One test per v4 refusal: what the flow may do, and the class the play + /// card names. + macro_rules! refusal_maps_to { + ($test:ident, $variant:ident, $disposition:ident, $class:expr) => { + #[test] + fn $test() { + let fault = refused_with(Refusal::$variant); + assert_eq!( + fault.disposition(), + InferenceFaultDisposition::$disposition, + "{fault:?}" + ); + assert_eq!(fault.class(), $class, "{fault:?}"); + } + }; + } + refusal_maps_to!(refusal_in_flight_is_retryable, InFlight, Retryable, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_capacity_is_retryable, Capacity, Retryable, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_expired_needs_recovery, Expired, RecoveryRequired, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_indeterminate_needs_recovery, Indeterminate, RecoveryRequired, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_identity_substitution_is_integrity, IdentitySubstitution, IntegrityViolation, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_digest_substitution_is_integrity, ProviderDigestSubstitution, IntegrityViolation, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_replay_conflict_is_integrity, ReplayConflict, IntegrityViolation, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_malformed_is_integrity, Malformed, IntegrityViolation, InferenceFaultClass::Unclassified); + refusal_maps_to!(refusal_model_not_allowed_is_terminal_and_named, ModelNotAllowed, RecoveryRequired, InferenceFaultClass::ModelNotAllowed); + refusal_maps_to!(refusal_output_bound_is_terminal_and_named, OutputBound, RecoveryRequired, InferenceFaultClass::OutputBound); + refusal_maps_to!(refusal_payload_bound_is_terminal_and_named, PayloadBound, RecoveryRequired, InferenceFaultClass::PayloadBound); + refusal_maps_to!(refusal_foreign_reasoning_state_is_integrity_and_named, ForeignReasoningState, IntegrityViolation, InferenceFaultClass::ForeignReasoningState); + refusal_maps_to!(refusal_provider_rejected_is_terminal_and_named, ProviderRejected, RecoveryRequired, InferenceFaultClass::ProviderRejected); + + macro_rules! failure_maps_to { + ($test:ident, $kind:ident, $disposition:ident, $class:expr) => { + #[test] + fn $test() { + let fault = failed_with(FailureKind::$kind); + assert_eq!( + fault.disposition(), + InferenceFaultDisposition::$disposition, + "{fault:?}" + ); + assert_eq!(fault.class(), $class, "{fault:?}"); + } + }; + } + failure_maps_to!(failure_rate_limited_is_retryable, RateLimited, Retryable, InferenceFaultClass::RateLimited); + failure_maps_to!(failure_unavailable_is_retryable, Unavailable, Retryable, InferenceFaultClass::Unavailable); + failure_maps_to!(failure_timeout_is_retryable, Timeout, Retryable, InferenceFaultClass::Timeout); + failure_maps_to!(failure_invalid_request_is_terminal, InvalidRequest, RecoveryRequired, InferenceFaultClass::InvalidRequest); + failure_maps_to!(failure_authentication_is_terminal, Authentication, RecoveryRequired, InferenceFaultClass::Authentication); + failure_maps_to!(failure_provider_is_terminal, Provider, RecoveryRequired, InferenceFaultClass::ProviderFailed); + failure_maps_to!(failure_result_size_is_terminal, ResultSize, RecoveryRequired, InferenceFaultClass::ProviderFailed); + + /// Collects the events a closure logs, with their fields rendered. + struct LogCapture(Arc>>); + + impl tracing::Subscriber for LogCapture { + fn enabled(&self, _: &tracing::Metadata<'_>) -> bool { + true + } + fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} + fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} + fn event(&self, event: &tracing::Event<'_>) { + struct Fields(String); + impl tracing::field::Visit for Fields { + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { + self.0.push_str(&format!("{}={value:?} ", field.name())); + } + } + let mut fields = Fields(String::new()); + event.record(&mut fields); + self.0.lock().unwrap().push(fields.0); + } + fn enter(&self, _: &tracing::span::Id) {} + fn exit(&self, _: &tracing::span::Id) {} + } + + /// An invalid request is terminal and the provider's own message reaches + /// the operator log, never the fault. + #[test] + fn a_failed_outcome_keeps_the_providers_message_in_the_log_and_out_of_the_fault() { + let lines = Arc::new(Mutex::new(Vec::new())); + let fault = tracing::subscriber::with_default(LogCapture(Arc::clone(&lines)), || { + failed_with(FailureKind::InvalidRequest) + }); + let rendered = format!("{fault} | {fault:?}"); + assert!(!rendered.contains("provider words"), "{rendered}"); + let lines = lines.lock().unwrap(); + assert!( + lines + .iter() + .any(|line| line.contains("provider words") && line.contains("InvalidRequest")), + "the operator log lacks the provider's message: {lines:?}" + ); + } + + /// A completed outcome reports the provider's own counts, never None; the + /// prompt is the whole prompt, cache traffic included. + #[test] + fn a_completed_outcome_reports_the_scripted_usage() { + let output = lift_result(result_of(TransportDisposition::Transported { + events: vec![ + TransportEvent { + sequence: 0, + payload: TransportEventPayload::TextDelta { text: "ok".into() }, + }, + TransportEvent { + sequence: 1, + payload: TransportEventPayload::ReasoningState { state: vec![9] }, + }, + TransportEvent { + sequence: 2, + payload: TransportEventPayload::ToolCall { + call_id: "call-1".into(), + name: "note".into(), + arguments: "{}".into(), + }, + }, + ], + receipt: Box::new(receipt(TransportOutcome::Completed { + provider_response_id: None, + stop_reason: StopReason::ToolUse, + usage: Usage { + input_tokens: 11, + cache_read_tokens: 5, + cache_write_tokens: 3, + output_tokens: 7, + reasoning_tokens: Some(2), + }, + })), + })) + .expect("a completed outcome lifts"); + assert_eq!( + output.usage, + Some(TokenUsage { + prompt: 19, + completion: 7, + cached_prompt: Some(5), + }) + ); + assert_eq!( + output.events, + vec![ + InferenceEvent::Text("ok".into()), + InferenceEvent::ToolCall { + call_id: "call-1".into(), + name: "note".into(), + arguments: "{}".into(), + }, + ], + "reasoning state is opaque and never becomes an event" + ); + assert!(output.receipt_digest.starts_with("sha256:")); + } + + /// A connection that closes before a reply is retryable and named, and a + /// transport that is wrong in itself is an integrity violation. + #[test] + fn a_closed_connection_is_retryable_and_a_broken_exchange_is_not() { + use std::io::{Error, ErrorKind}; + for (kind, class) in [ + (ErrorKind::UnexpectedEof, InferenceFaultClass::NoResponse), + (ErrorKind::ConnectionReset, InferenceFaultClass::NoResponse), + (ErrorKind::TimedOut, InferenceFaultClass::Timeout), + (ErrorKind::ConnectionRefused, InferenceFaultClass::Connect), + ] { + let fault = client_fault(ConnectorClientError::Connection(Error::from(kind))); + assert_eq!(fault.disposition(), InferenceFaultDisposition::Retryable, "{kind:?}"); + assert_eq!(fault.class(), class, "{kind:?}"); + } + for error in [ + ConnectorClientError::InvalidConfig, + ConnectorClientError::FrameSize, + ConnectorClientError::RequestIdTooLong, + ] { + assert!(client_fault(error).integrity_was_violated()); + } + } + + /// The whole port against a peer that accepts and hangs up: the closed + /// connection is the retryable, named fault, not an integrity breach. + #[tokio::test] + async fn the_port_names_a_peer_that_hangs_up() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let endpoint = listener.local_addr().unwrap(); + let peer = std::thread::spawn(move || drop(listener.accept().unwrap())); + let port = ConnectorInferencePort::new(endpoint, "test-key".into(), "runtime").unwrap(); + let request = persona_request(CommandId::new(), "claude-haiku-5-5", "Speak.".into()).unwrap(); + let prepared = port.prepare(request).unwrap(); + let fault = port.infer(prepared).await.expect_err("a hung-up peer answered"); + peer.join().unwrap(); + assert_eq!(fault.disposition(), InferenceFaultDisposition::Retryable, "{fault:?}"); + assert!( + matches!(fault.class(), InferenceFaultClass::NoResponse | InferenceFaultClass::Connect), + "{fault:?}" + ); + } + + /// v4 requests carry a required output allowance and a typed effort, and + /// name no cache retention Ghostlight never chose. + #[test] + fn every_lane_builds_a_bounded_typed_v4_request() { + let persona = persona_request(CommandId::new(), "claude-haiku-5-5", "Speak.".into()).unwrap(); + assert_eq!(persona.provider.max_output_tokens, 1_200); + assert_eq!(persona.provider.reasoning_effort, Some(ReasoningEffort::Low)); + assert_eq!(persona.provider.cache_retention, None::); + let interpreter = + interpreter_request(CommandId::new(), 0, "claude-haiku-5-5", vec![InputItem::UserText { text: "x".into() }]) + .unwrap(); + assert_eq!(interpreter.provider.max_output_tokens, DECISION_REQUEST_SHAPE.max_output_tokens); + assert_eq!(interpreter.provider.reasoning_effort, Some(ReasoningEffort::Medium)); + assert_eq!(interpreter.provider.tool_choice, ToolChoice::Auto); + } + + /// A tool or output schema is held to strict-grammar limits. model-connector + /// documents none, so: at most 24 optional parameters in a schema (the + /// Messages API strict-tool limit), and at most 16 KiB of schema text, a + /// Ghostlight-chosen ceiling at twice the largest schema sent today (8,055 + /// bytes, measured; no upstream byte figure exists). + const MAX_OPTIONAL_PARAMS: usize = 24; + const MAX_SCHEMA_BYTES: usize = 16_384; + + /// Counts the properties a schema does not list as required, anywhere in it. + fn optional_params(schema: &serde_json::Value) -> usize { + match schema { + serde_json::Value::Object(fields) => { + let own = match fields.get("properties") { + Some(serde_json::Value::Object(properties)) => { + let required: BTreeSet<&str> = fields + .get("required") + .and_then(|value| value.as_array()) + .map(|names| names.iter().filter_map(|name| name.as_str()).collect()) + .unwrap_or_default(); + properties + .keys() + .filter(|name| !required.contains(name.as_str())) + .count() + } + _ => 0, + }; + own + fields.values().map(optional_params).sum::() + } + serde_json::Value::Array(items) => items.iter().map(optional_params).sum(), + _ => 0, + } + } + + fn schema_within_limits(schema_json: &str) -> Result<(), String> { + let schema: serde_json::Value = serde_json::from_str(schema_json).map_err(|e| e.to_string())?; + let optional = optional_params(&schema); + if optional > MAX_OPTIONAL_PARAMS { + return Err(format!("{optional} optional parameters, more than {MAX_OPTIONAL_PARAMS}")); + } + if schema_json.len() > MAX_SCHEMA_BYTES { + return Err(format!("{} bytes, more than {MAX_SCHEMA_BYTES}", schema_json.len())); + } + Ok(()) + } + + #[test] + fn every_schema_ghostlight_sends_fits_the_grammar_limits() { + let opportunity = fixture_opportunity(ControllerMode::OperationalAgent); + let granted = vec![speak_snapshot(opportunity.affordance_ids[0])]; + // The interpreter's capture tools, the operational and grouped action + // catalog (which `actor_tools` projects as well), and the patch + // catalog every authoring lane draws from: elaborator, seed and play. + // No lane sets `output_schema_json` today. + let mut tools = interpreter_tools(); + tools.extend(catalog_tools("", &granted)); + tools.extend(catalog_tools("c0__", &granted)); + tools.extend(crate::patch::patch_tools()); + assert!(tools.len() > 10, "the walk saw only {} tools", tools.len()); + let mut worst = (0, 0); + for tool in &tools { + if let Err(reason) = schema_within_limits(&tool.parameters_json) { + panic!("{}: {reason}", tool.name); + } + let schema: serde_json::Value = serde_json::from_str(&tool.parameters_json).unwrap(); + worst = ( + worst.0.max(optional_params(&schema)), + worst.1.max(tool.parameters_json.len()), + ); + } + eprintln!("schema walk: {} tools, worst (optional, bytes) = {worst:?}", tools.len()); + } + + #[test] + fn a_planted_twenty_fifth_optional_parameter_fails_the_limit() { + let properties = |count: usize| -> String { + let fields: Vec = (0..count).map(|n| format!("\"p{n}\":{{\"type\":\"string\"}}")).collect(); + format!("{{\"type\":\"object\",\"required\":[],\"properties\":{{{}}}}}", fields.join(",")) + }; + assert!(schema_within_limits(&properties(MAX_OPTIONAL_PARAMS)).is_ok()); + assert!(schema_within_limits(&properties(MAX_OPTIONAL_PARAMS + 1)).is_err()); + let oversized = format!( + "{{\"type\":\"object\",\"required\":[],\"properties\":{{\"p\":{{\"type\":\"string\",\"description\":\"{}\"}}}}}}", + "x".repeat(MAX_SCHEMA_BYTES) + ); + assert!(schema_within_limits(&oversized).is_err()); + } use super::*; use crate::elaboration::{ElaboratorSession, EvidenceError, EvidenceQuery, EvidenceReceipt}; use crate::tests::{operations, opportunity_for}; @@ -7447,11 +7927,9 @@ mod tests { assert!(request.provider.validate().is_ok()); assert_eq!(request.provider.instructions, PERSONA_PROVIDER_INSTRUCTIONS); assert!(request.provider.tools.is_empty()); - assert_eq!(request.provider.tool_choice, CodexToolChoice::Auto); + assert_eq!(request.provider.tool_choice, ToolChoice::Auto); assert!(!request.provider.parallel_tool_calls); - assert!(request.provider.output_format_name.is_none()); assert!(request.provider.output_schema_json.is_none()); - assert!(request.provider.previous_response_id.is_none()); assert_eq!(request.provider.input.len(), 1); let encoded = serde_json::to_string(&request.provider) .unwrap() @@ -7874,7 +8352,7 @@ mod tests { } } - /// Every `CodexInputItem::UserText` in a captured request's input, + /// Every `InputItem::UserText` in a captured request's input, /// concatenated: what actually reached the provider, independent of how /// many input items carried it. fn request_text(request: &InferenceRequest) -> String { @@ -7883,7 +8361,7 @@ mod tests { .input .iter() .map(|item| match item { - CodexInputItem::UserText { text } => text.clone(), + InputItem::UserText { text } => text.clone(), _ => String::new(), }) .collect::>() @@ -9846,7 +10324,7 @@ mod tests { command_id, 0, "interpreter-model", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "prompt".into(), }], ) @@ -9855,7 +10333,7 @@ mod tests { command_id, 1, "interpreter-model", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "prompt".into(), }], ) @@ -10234,11 +10712,11 @@ mod tests { } } - fn tool_results(conversation: &[CodexInputItem]) -> Vec { + fn tool_results(conversation: &[InputItem]) -> Vec { conversation .iter() .filter_map(|item| match item { - CodexInputItem::ToolResult { output, .. } => Some(output.clone()), + InputItem::ToolResult { output, .. } => Some(output.clone()), _ => None, }) .collect() @@ -10518,7 +10996,7 @@ mod tests { 0, "claude-opus-5", &granted, - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Hold the bridge.".into(), }], ) @@ -10548,7 +11026,7 @@ mod tests { }]; let command_id = CommandId::new(); let prompt = || { - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Hold the bridge.".into(), }] }; @@ -11610,12 +12088,22 @@ mod tests { } #[tokio::test] - #[ignore = "requires a local model server on GHOSTLIGHT_LOCAL_ENDPOINT"] + #[ignore = "requires a local model server on GHOSTLIGHT_LOCAL_ENDPOINT, or a connector at GHOSTLIGHT_ACCEPTANCE_CONNECTOR with its key as the systemd credential `connector-key`"] async fn real_local_model_cognition_modes_commit_speech() { - let local_endpoint: SocketAddr = std::env::var("GHOSTLIGHT_LOCAL_ENDPOINT") - .expect("GHOSTLIGHT_LOCAL_ENDPOINT is required") - .parse() - .expect("GHOSTLIGHT_LOCAL_ENDPOINT must be a socket address"); + // The connector, when named, replaces the local server: the key reaches + // the process only as the credential file systemd mounts, never as a value. + let connector_endpoint: Option = std::env::var("GHOSTLIGHT_ACCEPTANCE_CONNECTOR") + .ok() + .map(|endpoint| endpoint.parse().expect("GHOSTLIGHT_ACCEPTANCE_CONNECTOR must be a socket address")); + let local_endpoint: Option = match connector_endpoint { + Some(_) => None, + None => Some( + std::env::var("GHOSTLIGHT_LOCAL_ENDPOINT") + .expect("GHOSTLIGHT_LOCAL_ENDPOINT is required") + .parse() + .expect("GHOSTLIGHT_LOCAL_ENDPOINT must be a socket address"), + ), + }; let local_model_prefix = std::env::var("GHOSTLIGHT_LOCAL_MODEL_PREFIX") .unwrap_or_else(|_| DEFAULT_LOCAL_MODEL_PREFIX.to_owned()); let runtime_id = std::env::var("GHOSTLIGHT_ACCEPTANCE_RUNTIME_ID") @@ -11789,18 +12277,21 @@ mod tests { .unwrap(); assert!(matches!(seed_receipt, SubmitReceipt::Applied(_))); - let inference = open_inference( - None, - None, - Some(LocalBinding { - endpoint: local_endpoint, - model_prefix: local_model_prefix, - caller_runtime_id: runtime_id, - }), - None, - &models.each(), - ) - .unwrap(); + let connector = connector_endpoint.map(|endpoint| ConnectorBinding { + endpoint, + key_path: PathBuf::from( + std::env::var_os("CREDENTIALS_DIRECTORY") + .expect("a connector run needs the systemd credential directory"), + ) + .join("connector-key"), + caller_runtime_id: runtime_id.clone(), + }); + let local = local_endpoint.map(|endpoint| LocalBinding { + endpoint, + model_prefix: local_model_prefix, + caller_runtime_id: runtime_id, + }); + let inference = open_inference(connector, None, local, None, &models.each()).unwrap(); let work = open_controller_work(directory.path().join("controller-work.cc")).unwrap(); let runner = ControllerRunner::open(mailbox.clone(), inference, work, models).unwrap(); @@ -12956,7 +13447,7 @@ mod tests { 0, &invocation.invocation.request.model, &session.instructions, - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: agent_prompt.clone(), }], ) @@ -13171,17 +13662,17 @@ mod tests { /// refused at open and not migrated; the same payload under the current /// version opens, so the refusal is the version's. #[tokio::test] - async fn a_controller_work_row_from_v17_is_refused_at_open() { + async fn a_controller_work_row_from_v18_is_refused_at_open() { let checkpoint = refused_checkpoint().await; let directory = tempfile::tempdir().unwrap(); let Err(error) = open_with_raw_row( &directory, - "v17.cc", + "v18.cc", &checkpoint, - "controller_work.v17", - "ghostlight.controller_work.v17", + "controller_work.v18", + "ghostlight.controller_work.v18", ) else { - panic!("a v17 row was accepted by the {CONTROLLER_WORK_ROW} store"); + panic!("a v18 row was accepted by the {CONTROLLER_WORK_ROW} store"); }; assert!(matches!(error, ControllerWorkStoreError::Fault { .. })); open_with_raw_row( @@ -13267,7 +13758,7 @@ mod tests { #[tokio::test] async fn the_catalog_takes_no_lens() { let _: fn() -> String = crate::patch::patch_tool_signatures; - let _: fn() -> Vec = crate::patch::patch_tools; + let _: fn() -> Vec = crate::patch::patch_tools; let (_directory, mailbox, task, commons, _roads) = dead_end_mailbox(only(Lens::Numen), &["The Unwalked Road"]).await; let store = fresh_store(); @@ -13282,7 +13773,7 @@ mod tests { let first = &seen[0].invocation.request; assert_eq!(first.instructions, Lens::Numen.instructions()); assert_eq!(first.tools, crate::patch::patch_tools()); - let Some(CodexInputItem::UserText { text }) = first.input.first() else { + let Some(InputItem::UserText { text }) = first.input.first() else { panic!("the first turn is not the prompt"); }; let tools = text @@ -13441,7 +13932,7 @@ mod tests { /// The first user turn of a prepared request: the session's prompt. fn prompt_of(request: &PreparedInference) -> String { match request.invocation.request.input.first() { - Some(CodexInputItem::UserText { text }) => text.clone(), + Some(InputItem::UserText { text }) => text.clone(), other => panic!("the first turn is not the prompt: {other:?}"), } } diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index 0c2c119..c12b733 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -33,7 +33,7 @@ use super::{ SubjectId, SubjectKind, WorldId, WorldPatch, WorldPhase, WorldSnapshot, }; use async_trait::async_trait; -use codex_connector::CodexInputItem; +use model_connector::InputItem; use serde::{Deserialize, Serialize}; use serde_json::Value; use sha2::{Digest, Sha256}; @@ -349,7 +349,7 @@ pub(super) struct ElaborationCapture { } pub(super) enum ElaborationLoopEvaluation { - Continue { conversation: Vec }, + Continue { conversation: Vec }, Complete { capture: ElaborationCapture }, } @@ -1135,7 +1135,7 @@ pub(super) fn evaluate_elaboration_loop( budget: usize, ) -> Result { check_refusals(refusals, completed.len())?; - let mut conversation = vec![CodexInputItem::UserText { + let mut conversation = vec![InputItem::UserText { text: prompt.to_owned(), }]; let mut fold = DraftFold::default(); @@ -1155,7 +1155,7 @@ pub(super) fn evaluate_elaboration_loop( match event { InferenceEvent::Text(text) => { if !text.is_empty() { - conversation.push(CodexInputItem::AssistantText { text: text.clone() }); + conversation.push(InputItem::AssistantText { text: text.clone() }); } } InferenceEvent::ToolCall { @@ -1164,13 +1164,13 @@ pub(super) fn evaluate_elaboration_loop( arguments, } => { called_tool = true; - conversation.push(CodexInputItem::ToolCall { + conversation.push(InputItem::ToolCall { call_id: call_id.clone(), name: name.clone(), arguments: arguments.clone(), }); let result = fold.apply(name, arguments); - conversation.push(CodexInputItem::ToolResult { + conversation.push(InputItem::ToolResult { call_id: call_id.clone(), output: result, }); @@ -1187,7 +1187,7 @@ pub(super) fn evaluate_elaboration_loop( "a refusal follows a round that submitted nothing".into(), )); } - conversation.push(CodexInputItem::UserText { + conversation.push(InputItem::UserText { text: render_refusal(&refusal.mismatches), }); fold = DraftFold::default(); @@ -1439,7 +1439,7 @@ pub(super) fn elaboration_request( round: usize, model: &str, instructions: &str, - input: Vec, + input: Vec, ) -> Result { tool_request( command_id, @@ -2035,7 +2035,7 @@ fn seed_request( command_id: CommandId, round: usize, model: &str, - input: Vec, + input: Vec, ) -> Result { tool_request( command_id, @@ -2213,7 +2213,7 @@ mod tests { let recomputed: Vec = conversation .iter() .filter_map(|item| match item { - CodexInputItem::ToolResult { output, .. } => Some(output.clone()), + InputItem::ToolResult { output, .. } => Some(output.clone()), _ => None, }) .collect(); @@ -2389,13 +2389,13 @@ mod tests { .unwrap() else { panic!("a refused round finalized instead of reopening"); }; - let CodexInputItem::UserText { text } = conversation.last().unwrap() else { + let InputItem::UserText { text } = conversation.last().unwrap() else { panic!("the refusal is not the next user turn"); }; assert!(text.contains("The world refused the patch you submitted")); assert!(text.contains(&render_mismatch(&Mismatch::NoCanonicalChange))); assert!( - matches!(&conversation[1], CodexInputItem::ToolCall { name, .. } if name == "declare_place"), + matches!(&conversation[1], InputItem::ToolCall { name, .. } if name == "declare_place"), "the refused round's calls left the conversation" ); assert_eq!( diff --git a/crates/ghostlight/src/local_inference.rs b/crates/ghostlight/src/local_inference.rs index fd7cdff..a145da7 100644 --- a/crates/ghostlight/src/local_inference.rs +++ b/crates/ghostlight/src/local_inference.rs @@ -17,7 +17,7 @@ use super::controllers::{ call_id_is_valid, tool_name_is_valid, unix_ms, }; use async_trait::async_trait; -use codex_connector::CodexInputItem; +use model_connector::InputItem; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; @@ -334,9 +334,9 @@ fn lower_request(prepared: &PreparedInference, prefix: &str) -> Result json!({"role": "user", "content": text}), - CodexInputItem::AssistantText { text } => json!({"role": "assistant", "content": text}), - CodexInputItem::ToolCall { + InputItem::UserText { text } => json!({"role": "user", "content": text}), + InputItem::AssistantText { text } => json!({"role": "assistant", "content": text}), + InputItem::ToolCall { call_id, name, arguments, @@ -349,11 +349,18 @@ fn lower_request(prepared: &PreparedInference, prefix: &str) -> Result json!({ + InputItem::ToolResult { call_id, output } => json!({ "role": "tool", "tool_call_id": call_id, "content": output, }), + // Ghostlight replays no provider state, and an OpenAI-compatible + // server has no place for one. + InputItem::ReasoningState { .. } => { + return Err(InferenceFault::integrity_violation( + "a local request carried provider reasoning state", + )); + } }); } let mut tools = Vec::with_capacity(request.tools.len()); @@ -379,9 +386,7 @@ fn lower_request(prepared: &PreparedInference, prefix: &str) -> Result::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1119,10 +1124,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1194,10 +1199,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1232,10 +1237,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1400,7 +1405,7 @@ mod tests { InferencePurpose::Elaboration, TEST_MODEL, "Author the shortfall.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Author the shortfall.".into(), }], patch_tools(), @@ -1428,10 +1433,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1460,7 +1465,7 @@ mod tests { InferencePurpose::Elaboration, TEST_MODEL, "Author the shortfall.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Author the shortfall.".into(), }], patch_tools(), @@ -1493,10 +1498,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1526,10 +1531,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1558,10 +1563,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1588,10 +1593,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1624,10 +1629,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Say something true.".into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -2054,8 +2059,8 @@ mod tests { InferencePurpose::Persona, "hosted/deepseek-chat", "Respond only in natural prose.", - vec![CodexInputItem::UserText { text: "Say something true.".into() }], - Vec::::new(), + vec![InputItem::UserText { text: "Say something true.".into() }], + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false }, ) .expect("the request builds"); diff --git a/crates/ghostlight/src/patch.rs b/crates/ghostlight/src/patch.rs index aa50ae6..a838ac0 100644 --- a/crates/ghostlight/src/patch.rs +++ b/crates/ghostlight/src/patch.rs @@ -18,7 +18,7 @@ use super::{ AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, LensWeights, NewController, SubjectId, SubjectKind, SubjectState, WorldId, }; -use codex_connector::CodexToolDefinition; +use model_connector::ToolDefinition; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; @@ -6726,7 +6726,7 @@ pub(crate) const PATCH_TOOLS: &[PatchTool] = &[ /// The catalog. Fixed per build: it reads `PATCH_TOOLS` and nothing else — not /// world state, not a snapshot, not a config. -pub(crate) fn patch_tools() -> Vec { +pub(crate) fn patch_tools() -> Vec { PATCH_TOOLS .iter() .map(|entry| { diff --git a/crates/ghostlight/src/sdk_inference.rs b/crates/ghostlight/src/sdk_inference.rs index d112be3..06f69df 100644 --- a/crates/ghostlight/src/sdk_inference.rs +++ b/crates/ghostlight/src/sdk_inference.rs @@ -12,7 +12,7 @@ use super::controllers::{ tool_name_is_valid, unix_ms, }; use async_trait::async_trait; -use codex_connector::CodexInputItem; +use model_connector::{InputItem, ReasoningEffort}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::BTreeMap; @@ -29,10 +29,6 @@ use tokio::sync::Mutex as AsyncMutex; /// largest request either transport carries is the same grouped cell. pub(super) const MAX_SIDECAR_FRAME_BYTES: usize = 1_052_672; -/// The reasoning-effort values the SDK's own `EffortLevel` admits. A request -/// carrying anything else is refused rather than silently mis-mapped. -const SDK_EFFORT_LEVELS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"]; - #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub(super) enum SidecarFrame { @@ -379,9 +375,9 @@ struct SdkInferenceReceipt { const SDK_RECEIPT_SCHEMA: &str = "ghostlight.sdk_inference_receipt.v1"; /// The model-name prefix that names the SDK transport when nothing configures -/// one. It holds even with no SDK port built, so a `claude-`prefixed lane on a -/// connector-only deployment is refused at open instead of quietly reaching the -/// wrong backend. +/// one. It claims a model only when the sidecar is configured; the connector +/// serves `claude-` models on its own, and `open_inference` refuses a sidecar +/// whose prefix would take a connector model. pub const DEFAULT_SDK_MODEL_PREFIX: &str = "claude"; /// Everything the SDK sidecar needs to open, gathered so `open_inference` takes @@ -551,15 +547,8 @@ pub(super) fn lower_query( turn_cap: u32, ) -> Result { let request = &prepared.invocation.request; - if let Some(effort) = request.reasoning_effort.as_deref() - && !SDK_EFFORT_LEVELS.contains(&effort) - { - return Err(InferenceFault::integrity_violation( - "the requested reasoning effort has no SDK counterpart", - )); - } let mut items = request.input.iter(); - let Some(CodexInputItem::UserText { text: prompt }) = items.next() else { + let Some(InputItem::UserText { text: prompt }) = items.next() else { return Err(InferenceFault::integrity_violation( "an SDK request must open with exactly one user text item", )); @@ -567,17 +556,22 @@ pub(super) fn lower_query( let mut transcript = Vec::new(); for item in items { match item { - CodexInputItem::AssistantText { text } => transcript.push(format!("assistant: {text}")), - CodexInputItem::ToolCall { + InputItem::AssistantText { text } => transcript.push(format!("assistant: {text}")), + InputItem::ToolCall { name, arguments, .. } => transcript.push(format!("tool call {name}: {arguments}")), - CodexInputItem::ToolResult { output, .. } => { + InputItem::ToolResult { output, .. } => { transcript.push(format!("tool result: {output}")) } // A later user turn is a kernel refusal reopening the session; the // transcript is already a textual replay of the conversation, so // it rides there like every other turn. - CodexInputItem::UserText { text } => transcript.push(format!("user: {text}")), + InputItem::UserText { text } => transcript.push(format!("user: {text}")), + InputItem::ReasoningState { .. } => { + return Err(InferenceFault::integrity_violation( + "an SDK request carried provider reasoning state", + )); + } } } Ok(SidecarFrame::Query { @@ -595,8 +589,16 @@ pub(super) fn lower_query( parameters_json: tool.parameters_json.clone(), }) .collect(), - effort: request.reasoning_effort.clone(), - max_output_tokens: request.max_output_tokens, + effort: request.reasoning_effort.map(|effort| { + match effort { + ReasoningEffort::Low => "low", + ReasoningEffort::Medium => "medium", + ReasoningEffort::High => "high", + ReasoningEffort::Max => "max", + } + .to_owned() + }), + max_output_tokens: Some(request.max_output_tokens), turn_cap, }) } @@ -769,8 +771,10 @@ impl RoutedInferencePort { .filter(|(prefix, _)| model.starts_with(prefix.as_str())) .max_by_key(|(prefix, _)| prefix.len()) .map(|(prefix, port)| (prefix.len(), port)); - let sdk_claim = model - .starts_with(&self.sdk_model_prefix) + // The SDK prefix claims only when the sidecar is configured: the + // connector serves `claude-` models too, so an unconfigured sidecar + // must leave them to it. + let sdk_claim = (self.sdk.is_some() && model.starts_with(&self.sdk_model_prefix)) .then_some(self.sdk_model_prefix.len()); match (local_claim, sdk_claim) { (Some((local_len, local_port)), Some(sdk_len)) => { @@ -831,7 +835,7 @@ mod tests { RECORD_GAP_PATCH_TOOL, SUBMIT_PATCH_TOOL, kernel_speak_entry, patch_tools, }; use crate::{AffordanceId, AffordanceSnapshot}; - use codex_connector::CodexToolDefinition; + use model_connector::ToolDefinition; use std::collections::VecDeque; const TEST_RUNTIME: &str = "ghostlight-sdk-test"; @@ -912,7 +916,7 @@ mod tests { InferencePurpose::Elaboration, TEST_MODEL, "Author the shortfall.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: prompt.into(), }], patch_tools(), @@ -932,10 +936,10 @@ mod tests { InferencePurpose::Persona, TEST_MODEL, "Respond only in natural prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: prompt.into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false, @@ -1346,7 +1350,7 @@ mod tests { InferencePurpose::OperationalAgent, TEST_MODEL, "Use only the supplied tools.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: "Hold the bridge.".into(), }], catalog_tools("", &granted), @@ -1442,10 +1446,21 @@ mod tests { open_inference(None, Some(sdk()), None, None, &models("gpt-5.6-terra").each()), Err(ControllerOpenError::UnroutableModel { .. }) )); + // The connector alone serves `claude-` models. + assert!( + open_inference(Some(connector()), None, None, None, &models("claude-haiku-5-5").each()).is_ok() + ); + // A sidecar whose prefix would take a model the connector serves is + // refused at open, not left to steal the route. assert!(matches!( - open_inference(Some(connector()), None, None, None, &models("claude-opus-5").each()), - Err(ControllerOpenError::UnroutableModel { .. }) + open_inference(Some(connector()), Some(sdk()), None, None, &models("claude-haiku-5-5").each()), + Err(ControllerOpenError::SidecarClaimsConnectorModel { .. }) )); + // The same sidecar beside the connector is fine for a model the + // connector does not serve. + assert!( + open_inference(Some(connector()), Some(sdk()), None, None, &models("claude-opus-5").each()).is_ok() + ); assert!(matches!( open_inference( None, @@ -1795,13 +1810,6 @@ mod tests { assert_names_no(&fault, CANARY); } - // An effort the SDK has no counterpart for. - let port = SdkInferencePort::new(ScriptedLink::new(Vec::new()), TEST_RUNTIME); - let mut prepared = prose_prepared(&port, "Say something true."); - prepared.invocation.request.reasoning_effort = Some(CANARY.into()); - let fault = lower_query(1, &prepared, 1).expect_err("an unmapped effort lowered"); - assert_names_no(&fault, CANARY); - // A model no backend claims, prepared and inferred through the router. let directory = tempfile::tempdir().unwrap(); let entry = directory.path().join("main.js"); @@ -1824,8 +1832,8 @@ mod tests { InferencePurpose::Persona, CANARY, "Respond only in natural prose.", - vec![CodexInputItem::UserText { text: "Say something true.".into() }], - Vec::::new(), + vec![InputItem::UserText { text: "Say something true.".into() }], + Vec::::new(), RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false }, ) .expect("the request builds"); @@ -1840,25 +1848,27 @@ mod tests { // `lower_query` reads the provider request off the prepared value, so // the shapes it must refuse are written there directly. Nothing here // asserts a digest; the identity tests own that. - let build = |input: Vec, effort: Option<&str>| { + let build = |input: Vec, effort: Option| { let mut prepared = prose_prepared(&port, "Say something true."); prepared.invocation.request.input = input; - prepared.invocation.request.reasoning_effort = effort.map(str::to_owned); + prepared.invocation.request.reasoning_effort = effort; prepared }; - let user = |text: &str| CodexInputItem::UserText { text: text.into() }; + let user = |text: &str| InputItem::UserText { text: text.into() }; - // Every effort the SDK admits passes; anything else is refused. - for effort in SDK_EFFORT_LEVELS { + // Every typed effort lowers. + for effort in [ + ReasoningEffort::Low, + ReasoningEffort::Medium, + ReasoningEffort::High, + ReasoningEffort::Max, + ] { assert!(lower_query(1, &build(vec![user("go")], Some(effort)), 1).is_ok()); } - let fault = lower_query(1, &build(vec![user("go")], Some("blistering")), 1) - .expect_err("an unmapped effort lowered"); - assert!(fault.integrity_was_violated(), "{fault:?}"); // The first item must be user text. for input in [ - vec![CodexInputItem::AssistantText { text: "no".into() }], + vec![InputItem::AssistantText { text: "no".into() }], Vec::new(), ] { let fault = lower_query(1, &build(input, None), 1) @@ -1881,20 +1891,20 @@ mod tests { &build( vec![ user("go"), - CodexInputItem::AssistantText { + InputItem::AssistantText { text: "thinking".into(), }, - CodexInputItem::ToolCall { + InputItem::ToolCall { call_id: "call-0".into(), name: "record_gap".into(), arguments: "{}".into(), }, - CodexInputItem::ToolResult { + InputItem::ToolResult { call_id: "call-0".into(), output: "gap recorded".into(), }, ], - Some("medium"), + Some(ReasoningEffort::Medium), ), 4, ) @@ -1930,15 +1940,27 @@ mod tests { #[tokio::test] async fn soul_routing_refuses_rather_than_falling_back() { assert_eq!(DEFAULT_SDK_MODEL_PREFIX, "claude"); - let connector_only = RoutedInferencePort::new( - Some(Arc::new(SdkInferencePort::new( + let stand_in = || { + Arc::new(SdkInferencePort::new( ScriptedLink::new(Vec::new()), TEST_RUNTIME, - )) as Arc), + )) as Arc + }; + // A connector with no sidecar serves `claude-` models itself. + let connector = stand_in(); + let connector_only = RoutedInferencePort::new( + Some(Arc::clone(&connector)), None, DEFAULT_SDK_MODEL_PREFIX, Vec::new(), ); + assert!(Arc::ptr_eq( + connector_only.route(TEST_MODEL).unwrap(), + &connector + )); + // A sidecar on a prefix that does not match, and no connector: the + // model has no owner and routes nowhere. + let connector_only = RoutedInferencePort::new(None, Some(stand_in()), "sdk/", Vec::new()); assert!(connector_only.route(TEST_MODEL).is_none()); let prepared = PreparedInference::prepare(TEST_RUNTIME, 4_102_444_800_000, prose_request("Say it.")).unwrap(); diff --git a/crates/ghostlight/src/table.rs b/crates/ghostlight/src/table.rs index b4049f0..1eccbb5 100644 --- a/crates/ghostlight/src/table.rs +++ b/crates/ghostlight/src/table.rs @@ -26,7 +26,7 @@ use super::{ DecisionOpportunity, EntityId, KernelError, Mismatch, RefKind, Statement, SubjectId, SubjectKind, Target, WorldPatch, WorldSnapshot, }; -use codex_connector::{CodexInputItem, CodexToolDefinition}; +use model_connector::{InputItem, ToolDefinition}; use serde_json::Value; use thiserror::Error; @@ -44,7 +44,7 @@ pub enum TableError { /// `PATCH_TOOLS`; which names a particular agent gets is policy, and policy /// belongs to the caller — `PLAY_TOOLS` is Dungeon's, pinned in Cut 8, not /// this module's. -pub fn authoring_tools(names: &[&str]) -> Result, TableError> { +pub fn authoring_tools(names: &[&str]) -> Result, TableError> { let catalog = patch::patch_tools(); names .iter() @@ -220,7 +220,7 @@ fn subject_opportunity<'a>( /// turn; that is the controller lane's own vocabulary, and /// `decode_actor_call` has no arm for either, so offering them here would /// hand the play agent a tool `decode_actor_call` always refuses (PA.f55). -pub fn actor_tools(prefix: &str, snapshot: &WorldSnapshot, subject: SubjectId) -> Vec { +pub fn actor_tools(prefix: &str, snapshot: &WorldSnapshot, subject: SubjectId) -> Vec { match subject_opportunity(snapshot, subject) { Some((_, granted)) => controllers::affordance_tools(prefix, &granted), None => Vec::new(), @@ -1038,8 +1038,8 @@ impl InferenceRequest { round: usize, model: &str, instructions: &str, - input: Vec, - tools: Vec, + input: Vec, + tools: Vec, max_output_tokens: u32, ) -> Result { tool_request( diff --git a/crates/ghostlight/src/tool_schema.rs b/crates/ghostlight/src/tool_schema.rs index ce15274..8ce081b 100644 --- a/crates/ghostlight/src/tool_schema.rs +++ b/crates/ghostlight/src/tool_schema.rs @@ -6,11 +6,11 @@ //! own vocabulary. Both spell a property the same way because both spell it //! here. Nothing in this module reads world state, a snapshot, or a config. -use codex_connector::CodexToolDefinition; +use model_connector::ToolDefinition; use serde_json::{Value, json}; -pub(super) fn tool(name: &str, description: &str, schema: Value) -> CodexToolDefinition { - CodexToolDefinition { +pub(super) fn tool(name: &str, description: &str, schema: Value) -> ToolDefinition { + ToolDefinition { name: name.into(), description: description.into(), parameters_json: serde_json::to_string(&schema) diff --git a/crates/ghostlight/src/verse/calls.rs b/crates/ghostlight/src/verse/calls.rs index 079fa44..22bfe31 100644 --- a/crates/ghostlight/src/verse/calls.rs +++ b/crates/ghostlight/src/verse/calls.rs @@ -26,7 +26,7 @@ use crate::controllers::{ }; use async_trait::async_trait; use chrono::Utc; -use codex_connector::CodexProviderRequest; +use model_connector::ProviderRequest; use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -197,10 +197,10 @@ fn hex(digest: &[u8]) -> String { /// id from the world it ran in, so keying on them would tie a recorded run to /// one world's random identity. Everything else the provider is sent /// (model, instructions, input, tools, shape) is in the digest. -fn content_digest(request: &CodexProviderRequest) -> Result { +fn content_digest(request: &ProviderRequest) -> Result { // Exhaustive on purpose: a field added upstream must be placed in the key // or left out here by name before this compiles. - let CodexProviderRequest { + let ProviderRequest { schema_id, request_id: _request_id, // names the call, not what it asks conversation_id: _conversation_id, // names the call, not what it asks @@ -208,16 +208,12 @@ fn content_digest(request: &CodexProviderRequest) -> Result Result Result { - let allowance = request - .invocation - .request - .max_output_tokens - .ok_or_else(InferenceFault::budget_exhausted)?; + let allowance = request.invocation.request.max_output_tokens; let payload = serde_json::to_vec(&request.invocation.request) .map_err(|_| InferenceFault::new("a provider request could not be measured"))?; Ok((payload.len() as u64).saturating_add(u64::from(allowance))) diff --git a/crates/ghostlight/src/verse/calls/tests.rs b/crates/ghostlight/src/verse/calls/tests.rs index 02131ae..201b6f7 100644 --- a/crates/ghostlight/src/verse/calls/tests.rs +++ b/crates/ghostlight/src/verse/calls/tests.rs @@ -3,7 +3,7 @@ use crate::CommandId; use crate::controllers::{ InferenceFaultClass, InferenceFaultDisposition, RequestShape, tool_request, }; -use codex_connector::{CodexInputItem, CodexToolDefinition}; +use model_connector::{InputItem, ToolDefinition}; use std::sync::atomic::{AtomicUsize, Ordering}; const MODEL: &str = "hosted/test-model"; @@ -73,10 +73,10 @@ fn request_for(command: CommandId, prompt: &str, max_output_tokens: u32) -> Infe InferencePurpose::Persona, MODEL, "Respond only in prose.", - vec![CodexInputItem::UserText { + vec![InputItem::UserText { text: prompt.into(), }], - Vec::::new(), + Vec::::new(), RequestShape { max_output_tokens, parallel_tool_calls: false, @@ -100,13 +100,7 @@ fn bound_of(prepared: &PreparedInference) -> u64 { .expect("a provider request serializes") .len() as u64; payload - + u64::from( - prepared - .invocation - .request - .max_output_tokens - .expect("an allowance"), - ) + + u64::from(prepared.invocation.request.max_output_tokens) } fn reply(text: &str, receipt: &str) -> InferenceOutput { @@ -276,17 +270,6 @@ async fn cap_refuses_before_the_provider_is_called() { .await .expect("a call that fits the cap is made"); assert_eq!(inner.calls(), 1); - - // A request with no output allowance has no bound and is refused. - let mut open_ended = prepared_for("open ended", 1_200); - open_ended.invocation.request.max_output_tokens = None; - let unbounded = recording(&inner, &store, "run-open", u64::MAX); - let fault = unbounded - .infer(open_ended) - .await - .expect_err("no allowance, no bound"); - assert_eq!(fault.class(), InferenceFaultClass::BudgetExhausted); - assert_eq!(inner.calls(), 1); } #[tokio::test] @@ -969,20 +952,20 @@ async fn usage_one_token_over_the_bound_faults_and_stores_no_record() { #[test] fn the_replay_key_covers_what_the_request_asks_and_not_what_names_it() { let base = prepared_for("key", 1_200).invocation.request.clone(); - let digest = |edit: &dyn Fn(&mut CodexProviderRequest)| { + let digest = |edit: &dyn Fn(&mut ProviderRequest)| { let mut request = base.clone(); edit(&mut request); content_digest(&request).unwrap() }; let same = digest(&|_| {}); assert_eq!(same, content_digest(&base).unwrap()); - let changes: Vec<(&str, Box)> = vec![ + let changes: Vec<(&str, Box)> = vec![ ("model", Box::new(|r| r.model.push('x'))), ("instructions", Box::new(|r| r.instructions.push('x'))), ( "tools", Box::new(|r| { - r.tools.push(CodexToolDefinition { + r.tools.push(ToolDefinition { name: "t".into(), description: "d".into(), parameters_json: "{}".into(), @@ -991,57 +974,41 @@ fn the_replay_key_covers_what_the_request_asks_and_not_what_names_it() { ), ( "input", - Box::new(|r| r.input.push(CodexInputItem::UserText { text: "x".into() })), + Box::new(|r| r.input.push(InputItem::UserText { text: "x".into() })), ), ( "max_output_tokens", - Box::new(|r| r.max_output_tokens = Some(1)), + Box::new(|r| r.max_output_tokens = 1), ), ( "reasoning_effort", - Box::new(|r| r.reasoning_effort = Some("low".into())), - ), - ( - "service_tier", - Box::new(|r| r.service_tier = Some("flex".into())), + Box::new(|r| r.reasoning_effort = Some(model_connector::ReasoningEffort::High)), ), ( "output_schema_json", Box::new(|r| r.output_schema_json = Some("{}".into())), ), - ( - "previous_response_id", - Box::new(|r| r.previous_response_id = Some("p".into())), - ), ( "parallel_tool_calls", Box::new(|r| r.parallel_tool_calls = !r.parallel_tool_calls), ), ("schema_id", Box::new(|r| r.schema_id.push_str(".v2"))), - ( - "reasoning_summary", - Box::new(|r| r.reasoning_summary = Some("auto".into())), - ), - ( - "output_format_name", - Box::new(|r| r.output_format_name = Some("persona_reply".into())), - ), ( "tool_choice", Box::new(|r| { r.tool_choice = match r.tool_choice { - codex_connector::CodexToolChoice::Auto => { - codex_connector::CodexToolChoice::Required + model_connector::ToolChoice::Auto => { + model_connector::ToolChoice::Required } - codex_connector::CodexToolChoice::Required => { - codex_connector::CodexToolChoice::Auto + model_connector::ToolChoice::Required => { + model_connector::ToolChoice::Auto } } }), ), ( - "prompt_cache_key", - Box::new(|r| r.prompt_cache_key = Some("ghostlight-persona-1".into())), + "cache_retention", + Box::new(|r| r.cache_retention = Some(model_connector::CacheRetention::Short)), ), ]; for (field, change) in changes { diff --git a/crates/ghostlight/src/verse/run/tests.rs b/crates/ghostlight/src/verse/run/tests.rs index a5f00f8..ff4236a 100644 --- a/crates/ghostlight/src/verse/run/tests.rs +++ b/crates/ghostlight/src/verse/run/tests.rs @@ -141,7 +141,7 @@ impl InferencePort for ScriptedPort { let sequence = self.calls.fetch_add(1, Ordering::SeqCst); let wire = &request.invocation.request; let bound = serde_json::to_vec(wire).unwrap().len() as u64 - + u64::from(wire.max_output_tokens.unwrap()); + + u64::from(wire.max_output_tokens); self.bounds.lock().unwrap().push(bound); if let Some(fault) = self.faults.lock().unwrap().pop_front() { return Err(fault); From 569794fda9a3992dcc63b4528fed321b45f7c959 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 18:11:58 +0100 Subject: [PATCH 06/12] Ignored live check: Ghostlight's own connector port completes plain, tool and schema requests Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/controllers.rs | 74 ++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 19df3df..7165200 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -7647,6 +7647,80 @@ mod tests { ); assert!(schema_within_limits(&oversized).is_err()); } + + /// The live check, run by hand on the host that carries claude-connector: + /// Ghostlight's own port completes a plain, a tool and an output-schema + /// request on haiku and a plain request on sonnet, with usage reported. + /// The key reaches the process only as the systemd credential + /// `connector-key`, for example + /// `systemd-run -p LoadCredential=connector-key: ...`. + #[tokio::test] + #[ignore = "needs claude-connector at 127.0.0.1:4110 and its key as the systemd credential connector-key"] + async fn live_connector_v4_completes_plain_tool_and_schema_requests() { + let key_path = PathBuf::from( + std::env::var_os("CREDENTIALS_DIRECTORY").expect("the systemd credential directory"), + ) + .join("connector-key"); + let port = ConnectorInferencePort::from_secret_file( + "127.0.0.1:4110".parse().unwrap(), + key_path, + "ghostlight", + ) + .expect("the port opens"); + let stamp = unix_ms().unwrap(); + let build = |label: &str, model: &str, edit: &dyn Fn(&mut ProviderRequest)| { + let mut provider = ProviderRequest::new( + format!("live-{label}-{stamp}"), + format!("live-{label}-{stamp}-c"), + model, + "Answer briefly.", + 300, + ); + provider.input = vec![InputItem::UserText { + text: "Say the word ok.".into(), + }]; + provider.reasoning_effort = Some(ReasoningEffort::Low); + edit(&mut provider); + InferenceRequest { + purpose: InferencePurpose::Persona, + provider, + } + }; + let tool = |provider: &mut ProviderRequest| { + provider.tools = vec![ToolDefinition { + name: "note".into(), + description: "Record a note.".into(), + parameters_json: + r#"{"type":"object","additionalProperties":false,"required":["text"],"properties":{"text":{"type":"string"}}}"# + .into(), + }]; + provider.input = vec![InputItem::UserText { + text: "Call the note tool with text ok.".into(), + }]; + }; + let schema = |provider: &mut ProviderRequest| { + provider.output_schema_json = Some( + r#"{"type":"object","additionalProperties":false,"required":["ok"],"properties":{"ok":{"type":"boolean"}}}"# + .into(), + ); + }; + let cases = [ + build("plain", "claude-haiku-5-5", &|_| {}), + build("tool", "claude-haiku-5-5", &tool), + build("schema", "claude-haiku-5-5", &schema), + build("sonnet", "claude-sonnet-5-5", &|_| {}), + ]; + for (label, request) in ["plain", "tool", "schema", "sonnet"].into_iter().zip(cases) { + let prepared = port.prepare(request).expect("the request prepares"); + let output = port.infer(prepared).await.unwrap_or_else(|fault| { + panic!("{label}: the connector faulted: {fault:?}"); + }); + let usage = output.usage.expect("the connector reports usage"); + assert!(usage.prompt > 0 && usage.completion > 0, "{label}: {usage:?}"); + assert!(!output.events.is_empty(), "{label}: no events"); + eprintln!("live {label}: {usage:?}, {} events", output.events.len()); + } + } use super::*; use crate::elaboration::{ElaboratorSession, EvidenceError, EvidenceQuery, EvidenceReceipt}; use crate::tests::{operations, opportunity_for}; From 3fc3110edb751789a05348ef287f76f277bf4acb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 18:25:06 +0100 Subject: [PATCH 07/12] Smoke note: the connector is claude-connector v4 with a systemd-credential key; the sidecar no longer owns claude-prefixed models by default Co-Authored-By: Claude Sonnet 5.5 --- notes/local-live-smoke.md | 95 ++++++++++++++++----------------------- 1 file changed, 38 insertions(+), 57 deletions(-) diff --git a/notes/local-live-smoke.md b/notes/local-live-smoke.md index 7170047..757d944 100644 --- a/notes/local-live-smoke.md +++ b/notes/local-live-smoke.md @@ -1,69 +1,50 @@ # Connector And Claude SDK Sidecar Bring-Up -No live smoke exists in this tree. The ignored test this file once documented, -`runtime::tests::live_smoke_seeds_then_ticks_a_world_against_the_connector`, -ran the production tick driver and the Active elaboration sweep against a real -CodexConnector; the play agent's Cut 1 (`d69e9d4`) deleted both, and the test -with them. A command that names it now matches nothing and exits 0. No -replacement exists. The recipe that once gated a deploy on a real model is -gone from main, and so is its `accept-real-persona-membrane` step. The one real-model test -left is the ignored `controllers::tests::real_local_model_cognition_modes_commit_speech` -(`crates/ghostlight/src/controllers.rs`). It has no automated run: it needs a model server -on `GHOSTLIGHT_LOCAL_ENDPOINT` plus the `GHOSTLIGHT_CONTROLLER_*_MODEL`, +No automated live smoke exists in this tree. The one real-model test left is the +ignored `controllers::tests::real_local_model_cognition_modes_commit_speech` +(`crates/ghostlight/src/controllers.rs`), and a person runs it by hand with +`cargo test -p ghostlight -- --ignored real_local_model_cognition_modes_commit_speech`. +It needs either a local model server (`GHOSTLIGHT_LOCAL_ENDPOINT`) or the +connector (`GHOSTLIGHT_ACCEPTANCE_CONNECTOR=` plus the systemd +credential below), and the `GHOSTLIGHT_CONTROLLER_*_MODEL`, `GHOSTLIGHT_ACCEPTANCE_RUNTIME_ID` and `GHOSTLIGHT_ACCEPTANCE_PERSONA_PROSE_LOG` -variables, and a person runs it by hand with `cargo test -p ghostlight -- --ignored -real_local_model_cognition_modes_commit_speech`. +variables. The release gate passes if one of three attempts commits; every +failed attempt's prose is kept. -What remains true and stays here: bringing up a real CodexConnector and a -built Claude SDK sidecar. The seed lane (`world.seed`) still runs real -inference through `ControllerRunner`, and both transports below are how a -session gets real model responses instead of a fixture inference port. +## The connector -## Substrate +Ghostlight's connector lane speaks model-connector v4 to claude-connector, which +Eureka owns and runs on Yggdrasil at `127.0.0.1:4110`. Ghostlight is one of its +callers, identified as `ghostlight`. Connector models are `claude-haiku-5-5`, +`claude-sonnet-5-5` and `claude-opus-5-5`; any other name is refused +`ModelNotAllowed`. A required tool choice on `claude-sonnet-5-5` is refused as +an invalid request, and Ghostlight sends only `Auto`. -Machine-local, outside the repo: `F:\Projects\Ghostlight-smoke\`. +The connection key is never copied, printed or put in an environment variable. +`ConnectorBinding::key_path` names a file, read once when the port opens. Under +systemd that file is the credential the unit mounts: -- `codex-home\auth.json`: a copy of `~/.codex/auth.json`. The connector spawns - the official `codex app-server` child against this home and may refresh it. -- `connector\ghostlight.key`: 64 hex characters, no trailing newline; the - shared connection secret. Both sides read the same file. -- `connector\connector.cc`: the daemon's single-caller config. -- `logs\`: connector stdout/stderr and pid. - -The connector binary is `F:\Projects\CodexConnector\target\debug\codex-connector.exe` -built from the repo head with the `daemon` feature. Ghostlight's `Cargo.lock` -pins the connector library at an older revision whose daemon does not build -against its own lockfile; the head daemon speaks the same wire law. - -## Bring-up - -Initialize the config once (the codex executable path and SHA-256 are the -newest `codex.exe` under `%LOCALAPPDATA%\OpenAI\Codex\bin\`): - -```powershell -F:\Projects\CodexConnector\target\debug\codex-connector.exe --initialize-single-caller-config F:\Projects\Ghostlight-smoke\connector\connector.cc 127.0.0.1:4103 F:\Projects\Ghostlight-smoke\codex-home F:\Projects\Ghostlight-smoke\connector\replay.cc ghostlight-smoke F:\Projects\Ghostlight-smoke\connector\ghostlight.key 1 gpt-5.6-luna,gpt-5.6-sol,gpt-5.6-terra 4 1052672 16000 +```bash +sudo systemd-run --wait --pipe \ + -p LoadCredential=connector-key:/etc/gamecult/claude-connector/connection-ghostlight.key \ + -E GHOSTLIGHT_ACCEPTANCE_CONNECTOR=127.0.0.1:4110 ... --ignored ``` -Start the daemon detached; it prints one ready line to stderr: +The ignored `live_connector_v4_completes_plain_tool_and_schema_requests` runs the +same way (it needs only `CREDENTIALS_DIRECTORY`) and checks a plain, a tool and +an output-schema request on haiku and a plain request on sonnet. -```powershell -$R='F:\Projects\Ghostlight-smoke'; $p = Start-Process -FilePath 'F:\Projects\CodexConnector\target\debug\codex-connector.exe' -ArgumentList @('--config', "$R\connector\connector.cc") -RedirectStandardOutput "$R\logs\connector.stdout.log" -RedirectStandardError "$R\logs\connector.stderr.log" -PassThru -WindowStyle Hidden; $p.Id | Out-File "$R\logs\connector.pid" -``` - -Stop it with `Stop-Process -Id (Get-Content F:\Projects\Ghostlight-smoke\logs\connector.pid)`. - -A session that wants the connector reads -`GHOSTLIGHT_CONTROLLER_CONNECTOR=127.0.0.1:4103` and -`GHOSTLIGHT_CONTROLLER_CREDENTIAL='F:\Projects\Ghostlight-smoke\connector\ghostlight.key'`, -the same variables the deleted harness read. +Ghostlight's port is one shot +and returns a typed fault (`InferenceFaultClass`) whose disposition says whether +the owning flow may try again. ## Claude SDK route `crates/ghostlight/src/sdk_inference.rs`'s `SdkInferencePort` gives any lane whose configured model is `claude`-prefixed (matching `GHOSTLIGHT_SDK_MODEL_PREFIX`, default `claude`) a second transport: a Node sidecar on the Claude Agent SDK instead of -the CodexConnector, so a session can run on the Claude subscription with no -Codex budget. +the connector, so a session can run on the Claude subscription with no +connector budget. **Operator prerequisites, none of which Ghostlight performs:** @@ -92,10 +73,10 @@ GHOSTLIGHT_SDK_SIDECAR='F:\Projects\Ghostlight\sidecar\claude-sdk\dist\main.js' GHOSTLIGHT_SDK_MODEL_PREFIX=claude # optional; this is already the default ``` -`GHOSTLIGHT_SDK_SIDECAR`'s absence means no SDK binding at all — a -`claude`-prefixed lane model then fails at open with `UnroutableModel` rather -than silently reaching the connector. Any of the five -`GHOSTLIGHT_CONTROLLER_*_MODEL` variables can be set to a `claude`-prefixed -model (for example `claude-opus-5`) to route that lane through the sidecar; -the connector variables are only required for lanes that still route to the -connector, and an all-`claude` configuration needs neither. + +`GHOSTLIGHT_SDK_SIDECAR`'s absence means no SDK binding at all: a +`claude`-prefixed lane model then routes to the connector, which serves the +`claude-*-5-5` models itself. With both bound, a model the connector serves +(`claude--5-5`) under the sidecar's prefix is refused at open +(`SidecarClaimsConnectorModel`) rather than stolen by the sidecar; a model +such as `claude-opus-5` still reaches the sidecar. From 7670d02a6c03227dd7b76a99bebd7b4b73101ecd Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 18:44:12 +0100 Subject: [PATCH 08/12] Pin the prose-shape gate and the trace render against mutation survivors Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/controllers.rs | 80 ++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 7165200..b6131ee 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -7633,6 +7633,86 @@ mod tests { eprintln!("schema walk: {} tools, worst (optional, bytes) = {worst:?}", tools.len()); } + + /// The prose-only gate refuses every deviation from one user text, no + /// tools, automatic choice, serial calls and no output schema. + #[test] + fn the_prose_shape_gate_refuses_each_deviation() { + let request = persona_request(CommandId::new(), "claude-haiku-5-5", "Speak.".into()).unwrap(); + let valid = PreparedInference::prepare("runtime", 4_102_444_800_000, request).unwrap(); + assert!(prose_request_shape_is_valid(&valid)); + assert!(persona_request_shape_is_valid(&valid)); + let deviations: Vec<(&str, Box)> = vec![ + ( + "a second input item", + Box::new(|r| r.input.push(InputItem::UserText { text: "more".into() })), + ), + ( + "an assistant opening", + Box::new(|r| r.input = vec![InputItem::AssistantText { text: "no".into() }]), + ), + ( + "a tool", + Box::new(|r| { + r.tools.push(ToolDefinition { + name: "t".into(), + description: "d".into(), + parameters_json: "{}".into(), + }) + }), + ), + ("a required tool choice", Box::new(|r| r.tool_choice = ToolChoice::Required)), + ("parallel calls", Box::new(|r| r.parallel_tool_calls = true)), + ( + "an output schema", + Box::new(|r| r.output_schema_json = Some("{}".into())), + ), + ]; + for (name, deviate) in deviations { + let mut prepared = valid.clone(); + deviate(&mut prepared.invocation.request); + assert!(!prose_request_shape_is_valid(&prepared), "{name} passed the gate"); + } + } + + /// The trace file renders what the provider is sent, every input kind + /// included. + #[test] + fn the_trace_renders_every_input_kind_and_the_tools() { + let mut provider = ProviderRequest::new("r", "c", "claude-haiku-5-5", "Be brief.", 100); + provider.input = vec![ + InputItem::UserText { text: "u-text".into() }, + InputItem::AssistantText { text: "a-text".into() }, + InputItem::ToolCall { + call_id: "k".into(), + name: "t-name".into(), + arguments: "{\"a\":1}".into(), + }, + InputItem::ToolResult { call_id: "k".into(), output: "t-out".into() }, + InputItem::ReasoningState { + provider: "p".into(), + model: "m".into(), + state: vec![1], + }, + ]; + provider.tools = vec![ToolDefinition { + name: "t-name".into(), + description: "t-desc".into(), + parameters_json: "{}".into(), + }]; + let prepared = PreparedInference::prepare( + "runtime", + 4_102_444_800_000, + InferenceRequest { purpose: InferencePurpose::Persona, provider }, + ) + .unwrap(); + let rendered = TracingInferencePort::render_request(&prepared); + for needle in [ + "Be brief.", "u-text", "a-text", "t-name", "{\"a\":1}", "t-out", "[reasoning state]", "t-desc", + ] { + assert!(rendered.contains(needle), "the trace lacks {needle}: {rendered}"); + } + } #[test] fn a_planted_twenty_fifth_optional_parameter_fails_the_limit() { let properties = |count: usize| -> String { From a5ddfb9d76182f6d0b3ddd193f77425c3d1e1995 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:00:02 +0100 Subject: [PATCH 09/12] vault: file and glob excludes, machinery files never lore, CRLF folded before hashing, backslash patterns refused Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/vault.rs | 221 +++++++++++++++++++++++++++++++-- 1 file changed, 208 insertions(+), 13 deletions(-) diff --git a/crates/ghostlight/src/vault.rs b/crates/ghostlight/src/vault.rs index ae6901b..fb2a79f 100644 --- a/crates/ghostlight/src/vault.rs +++ b/crates/ghostlight/src/vault.rs @@ -56,6 +56,8 @@ pub enum VaultError { 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")] @@ -69,7 +71,12 @@ pub enum VaultError { /// 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. +/// `.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 @@ -79,10 +86,14 @@ pub enum VaultError { 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. + /// Vault-relative directories to admit notes from, no wildcards; empty + /// admits everything under `scope` that is not excluded. pub include: Vec, - /// Vault-relative directories not entered at all. + /// 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`. @@ -126,7 +137,7 @@ struct SnapshotNote { /// 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. + /// Of the file's text with CRLF folded to LF, lowercase hex. sha256: String, /// Frontmatter title, else the filename stem. title: String, @@ -180,8 +191,8 @@ impl VaultSnapshot { let canonical = VaultProfile { name: profile.name.clone(), root: PathBuf::new(), - include: canonical_dirs(&profile.include)?, - exclude: canonical_dirs(&profile.exclude)?, + include: canonical_dirs(&profile.include, false)?, + exclude: canonical_dirs(&profile.exclude, true)?, scope: scope.clone(), }; let start = if scope.is_empty() { @@ -216,6 +227,9 @@ impl VaultSnapshot { 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()) @@ -351,9 +365,12 @@ fn relative_dir(text: &str) -> Option { ) } -fn canonical_dirs(dirs: &[String]) -> Result, VaultError> { +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())), @@ -367,6 +384,30 @@ 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. @@ -394,7 +435,7 @@ fn collect_notes( }; if metadata.is_dir() { if name.starts_with('.') - || profile.exclude.iter().any(|dir| is_under(&child, dir)) + || 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))) { @@ -408,6 +449,8 @@ fn collect_notes( } 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 { @@ -1256,6 +1299,140 @@ mod tests { assert!(VaultSnapshot::build(&VaultProfile { exclude: vec!["/abs".into()], ..profile(vault.path()) }).is_err()); } + 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] @@ -1263,10 +1440,21 @@ mod tests { 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![]), + ( + "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 { @@ -1279,6 +1467,13 @@ mod tests { 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()); } } From 48f24f94df1ba0d82b06a45b6e5c297e45d31f7e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:01:52 +0100 Subject: [PATCH 10/12] vault import: unique temp name, poisoned entries replaced, load copies instead of opening the store Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/vault.rs | 246 +++++++++++++++++++++++++++++---- 1 file changed, 222 insertions(+), 24 deletions(-) diff --git a/crates/ghostlight/src/vault.rs b/crates/ghostlight/src/vault.rs index fb2a79f..7b17ab9 100644 --- a/crates/ghostlight/src/vault.rs +++ b/crates/ghostlight/src/vault.rs @@ -182,6 +182,11 @@ impl VaultSnapshot { /// 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() { @@ -256,46 +261,83 @@ impl VaultSnapshot { }) } - /// Writes this snapshot as `.cc` under `directory`, unless that file is - /// already there, in which case nothing is touched. The file appears whole - /// or not at all. + /// 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 path = directory.join(format!("{}.cc", self.id)); - if path.exists() { + 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 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()), + 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)?; + .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), } - std::fs::rename(&partial, &path).map_err(|_| VaultError::Store)?; - // The store leaves its lock sidecar beside the file it created. - let _ = std::fs::remove_file(directory.join(format!("{}.cc.partial.lock", self.id))); - Ok(ImportOutcome::Imported(self.id.clone())) + } + + 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 store = OwnedRedbMessagePackBackingStore::new(&path).map_err(|_| VaultError::Store)?; - let rows = store.pull_all().map_err(|_| VaultError::Store)?; + 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); }; @@ -313,6 +355,20 @@ impl VaultSnapshot { } } +/// 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) { @@ -1299,6 +1355,148 @@ mod tests { 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()) + ); + } + } + + #[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()); + } + fn references(snapshot: &VaultSnapshot) -> Vec<&str> { snapshot.notes.iter().map(|note| note.reference.as_str()).collect() } From b1a2d05976a91df587dec6349fbeecc2a7ab52bf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:03:17 +0100 Subject: [PATCH 11/12] vault tests: scope refusals and trimmed names Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/vault.rs | 40 ++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/crates/ghostlight/src/vault.rs b/crates/ghostlight/src/vault.rs index 7b17ab9..b312be2 100644 --- a/crates/ghostlight/src/vault.rs +++ b/crates/ghostlight/src/vault.rs @@ -1497,6 +1497,46 @@ mod tests { 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() } From 03fb33fb9317f4947efa847d59a77cce2583e849 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:55:23 +0100 Subject: [PATCH 12/12] vault: relative_dir drops the redundant is_absolute arm; test an import that cannot publish Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/vault.rs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/crates/ghostlight/src/vault.rs b/crates/ghostlight/src/vault.rs index b312be2..c545deb 100644 --- a/crates/ghostlight/src/vault.rs +++ b/crates/ghostlight/src/vault.rs @@ -406,10 +406,9 @@ fn hex(bytes: &[u8]) -> String { /// when it is absolute or holds anything but plain components. fn relative_dir(text: &str) -> Option { let path = Path::new(text.trim()); - if path.is_absolute() - || path - .components() - .any(|part| !matches!(part, Component::Normal(_))) + if path + .components() + .any(|part| !matches!(part, Component::Normal(_))) { return None; } @@ -1482,6 +1481,19 @@ mod tests { } } + /// 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();