Rebuild Ghostlight around explicit world authority

This commit is contained in:
Meta Vens 2026-09-02 07:21:11 +02:00
commit 6bb6869810
61 changed files with 10666 additions and 105981 deletions

1
.gitignore vendored
View file

@ -2,6 +2,7 @@ __pycache__/
*.pyc
.venv/
node_modules/
web/dist/
state/scratch-compaction-*.md
experiments/images/
target/

2
Cargo.lock generated
View file

@ -322,7 +322,7 @@ dependencies = [
[[package]]
name = "codex-connector"
version = "0.1.0"
source = "git+https://github.com/GameCult/CodexConnector.git?rev=6dc80f6d266db4d82566d2434adcc55a48e8ecad#6dc80f6d266db4d82566d2434adcc55a48e8ecad"
source = "git+https://github.com/GameCult/CodexConnector.git?rev=68fe94b9475823de92ed766a97ea962d48723708#68fe94b9475823de92ed766a97ea962d48723708"
dependencies = [
"aes-gcm",
"base64 0.23.1",

View file

@ -22,18 +22,16 @@ async-stream = "0.3"
axum = { version = "0.8", features = ["macros"] }
chrono = { version = "0.4", features = ["serde"] }
base64 = "0.22"
codex-connector = { git = "https://github.com/GameCult/CodexConnector.git", rev = "6dc80f6d266db4d82566d2434adcc55a48e8ecad" }
codex-connector = { git = "https://github.com/GameCult/CodexConnector.git", rev = "68fe94b9475823de92ed766a97ea962d48723708" }
cultcache-legacy = { package = "cultcache-rs", git = "https://github.com/GameCult/cultcache-rs.git", rev = "0ba87453115e3d44e8fcb7419866cd7dd70fb096" }
cultcache-rs = { path = "vendor/cultcache-rs" }
cultnet-rs = { path = "vendor/cultnet-rs" }
cultmesh-rs = { path = "vendor/cultmesh-rs" }
jsonschema = { version = "0.49", default-features = false }
jsonwebtoken = "9"
hmac = "0.12"
rand = "0.9"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }
rmp-serde = "1.3"
schemars = { version = "1", features = ["chrono04", "uuid1"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
@ -43,5 +41,4 @@ tower-http = { version = "0.6", features = ["fs", "trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
uuid = { version = "1", features = ["v4", "serde"] }
windows = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Cryptography"] }
zeroize = "1.8"

View file

@ -3,6 +3,11 @@ name = "ghostlight-dungeon"
version.workspace = true
edition.workspace = true
license.workspace = true
autobins = false
[[bin]]
name = "ghostlight-dungeon"
path = "src/main.rs"
[dependencies]
anyhow.workspace = true
@ -17,14 +22,12 @@ cultcache-legacy.workspace = true
cultcache-rs.workspace = true
cultnet-rs.workspace = true
cultmesh-rs.workspace = true
jsonschema.workspace = true
jsonwebtoken.workspace = true
hmac.workspace = true
ghostlight-persona-projection = { path = "../ghostlight-persona-projection" }
rand.workspace = true
reqwest.workspace = true
rmp-serde.workspace = true
schemars.workspace = true
serde.workspace = true
serde_json.workspace = true
serde_bytes = "0.11"
@ -37,9 +40,6 @@ tracing-subscriber.workspace = true
uuid.workspace = true
zeroize.workspace = true
[target.'cfg(windows)'.dependencies]
windows.workspace = true
[dev-dependencies]
tempfile = "3"
tower = { version = "0.5", features = ["util"] }

View file

@ -1,635 +0,0 @@
use crate::transition::{
ActionMeans, AgencyAdmissionExpectation, AgencyAttemptCase, AgencyResolutionLane,
MutationIntent, SubjectKind, SubjectRef, WorldComponentKind, WorldMutationOperation,
};
use std::collections::BTreeSet;
#[derive(Clone)]
struct Candidate<'a> {
id: &'a str,
domain: &'a str,
scenario: &'a str,
means: &'a str,
desired: &'a str,
target_kind: SubjectKind,
component: WorldComponentKind,
admission: AgencyAdmissionExpectation,
required: &'a [WorldMutationOperation],
forbidden: &'a [WorldMutationOperation],
bargain: Option<&'a str>,
}
pub fn seed_agency_attempt_cases() -> Vec<AgencyAttemptCase> {
use AgencyAdmissionExpectation::{Admissible, BargainRequired, Impossible};
use SubjectKind::{Actor, Institution, Place, Population, Resource};
use WorldComponentKind::{
Commitment, Condition, Custody, Identity, Knowledge, Occupancy, PopulationMembership,
Posture, Relationship, ResourceState, Topology,
};
use WorldMutationOperation as Op;
let candidates = [
Candidate {
id: "social-persuade-guard",
domain: "social",
scenario: "A traveler asks a wary gate guard to admit them before curfew.",
means: "Present a valid trade letter and explain the delayed caravan.",
desired: "The guard chooses to admit the traveler.",
target_kind: Actor,
component: Posture,
admission: Admissible,
required: &[Op::PostureChange],
forbidden: &[Op::KnowledgeAcquire],
bargain: None,
},
Candidate {
id: "social-promise-repayment",
domain: "social",
scenario: "A refugee asks a medic for scarce treatment and promises later repayment.",
means: "State the promise directly to the medic while both are present.",
desired: "Create an obligation to repay the medic.",
target_kind: Actor,
component: Commitment,
admission: Admissible,
required: &[Op::CommitmentCreate],
forbidden: &[Op::TransferCustody],
bargain: None,
},
Candidate {
id: "social-command-stranger",
domain: "social",
scenario: "A stranger declares that a veteran now serves them.",
means: "Issue a confident order without rank, leverage, consent, or coercive control.",
desired: "Make the veteran accept a binding service obligation.",
target_kind: Actor,
component: Commitment,
admission: BargainRequired,
required: &[],
forbidden: &[Op::CommitmentCreate],
bargain: Some("gain consent, recognized command authority, or concrete leverage"),
},
Candidate {
id: "physical-climb-wall",
domain: "physical",
scenario: "A climber tries to scale a wet stone wall using a rope and pitons.",
means: "Anchor the rope and climb the reachable wall with the available kit.",
desired: "Reach the parapet.",
target_kind: Place,
component: Occupancy,
admission: Admissible,
required: &[Op::Relocate],
forbidden: &[Op::TopologyAdd],
bargain: None,
},
Candidate {
id: "physical-break-door",
domain: "physical",
scenario: "A trapped actor tries to break a damaged wooden door with a pry bar.",
means: "Apply the pry bar at the split latch while standing beside the door.",
desired: "Damage the door enough to pass.",
target_kind: Resource,
component: ResourceState,
admission: Admissible,
required: &[Op::ResourceDamage],
forbidden: &[Op::Relocate],
bargain: None,
},
Candidate {
id: "physical-jump-orbit",
domain: "physical",
scenario: "An unaugmented person on Mars tries to jump into orbit.",
means: "Jump upward using only ordinary musculature.",
desired: "Reach an orbital station.",
target_kind: Place,
component: Occupancy,
admission: Impossible,
required: &[],
forbidden: &[Op::Relocate],
bargain: Some(
"obtain a launch vehicle, teleport permission, or another means with orbital reach",
),
},
Candidate {
id: "investigate-panel",
domain: "investigative",
scenario: "A technician inspects a reachable coolant panel with a multimeter.",
means: "Measure the exposed contacts and compare them with the known service range.",
desired: "Learn whether the fault is electrical.",
target_kind: Resource,
component: Knowledge,
admission: Admissible,
required: &[Op::KnowledgeAcquire],
forbidden: &[Op::ResourceRepair],
bargain: None,
},
Candidate {
id: "investigate-witness",
domain: "investigative",
scenario: "An investigator asks a willing witness what they saw.",
means: "Conduct a private interview through a shared language and channel.",
desired: "Learn the witness's exact account.",
target_kind: Actor,
component: Knowledge,
admission: Admissible,
required: &[Op::KnowledgeCommunicate],
forbidden: &[Op::KnowledgeAcquire],
bargain: None,
},
Candidate {
id: "investigate-remote-secret",
domain: "investigative",
scenario: "A player announces they know a sealed archive's contents without access or a source.",
means: "Infer the exact contents from vibes while nowhere near the archive.",
desired: "Acquire the archive's private proposition.",
target_kind: Institution,
component: Knowledge,
admission: Impossible,
required: &[],
forbidden: &[Op::KnowledgeAcquire],
bargain: Some(
"gain archive access, recruit a knowledgeable source, or intercept an information channel",
),
},
Candidate {
id: "economic-buy-medicine",
domain: "economic",
scenario: "A buyer purchases an exact medicine lot from a willing clinic.",
means: "Exchange the agreed credits while both parties can transfer custody.",
desired: "Receive custody of the medicine lot.",
target_kind: Resource,
component: Custody,
admission: Admissible,
required: &[Op::TransferCustody],
forbidden: &[Op::ResourceCreate],
bargain: None,
},
Candidate {
id: "economic-split-rations",
domain: "economic",
scenario: "A quartermaster divides a ration lot and gives half to another camp.",
means: "Measure an exact portion from a lot under the quartermaster's custody.",
desired: "Create a conserved sub-lot and transfer it.",
target_kind: Resource,
component: ResourceState,
admission: Admissible,
required: &[Op::ResourceSplit, Op::TransferCustody],
forbidden: &[Op::ResourceCreate],
bargain: None,
},
Candidate {
id: "economic-spend-absent-credit",
domain: "economic",
scenario: "A debtor tries to pay with credits they do not possess or control.",
means: "Declare that the payment happened.",
desired: "Transfer nonexistent credits.",
target_kind: Resource,
component: Custody,
admission: Impossible,
required: &[],
forbidden: &[Op::TransferCustody, Op::ResourceCreate],
bargain: Some(
"obtain funds, secure a loan, or offer a different admitted consideration",
),
},
Candidate {
id: "political-petition",
domain: "political",
scenario: "Residents petition a council to reopen a ration depot.",
means: "Present signatures and testimony through the council's recognized hearing.",
desired: "Shift the council toward reopening the depot.",
target_kind: Institution,
component: Posture,
admission: Admissible,
required: &[Op::PostureChange],
forbidden: &[Op::TransferCustody],
bargain: None,
},
Candidate {
id: "political-treaty",
domain: "political",
scenario: "Two authorized envoys negotiate a mutual non-aggression obligation.",
means: "Exchange exact terms while holding delegated authority for both institutions.",
desired: "Create reciprocal obligations and alter their relationship.",
target_kind: Institution,
component: Relationship,
admission: Admissible,
required: &[Op::CommitmentCreate, Op::RelationshipAlter],
forbidden: &[Op::PostureChange],
bargain: None,
},
Candidate {
id: "political-declare-throne",
domain: "political",
scenario: "A visitor declares themselves ruler of an institution whose members reject the claim.",
means: "Announce the title without succession, consent, force, or legal authority.",
desired: "Acquire command posture and custody over the institution.",
target_kind: Institution,
component: Posture,
admission: BargainRequired,
required: &[],
forbidden: &[Op::PostureChange, Op::TransferCustody],
bargain: Some(
"win recognized succession, member consent, or actual control through admitted play",
),
},
Candidate {
id: "technology-repair-drone",
domain: "technological",
scenario: "An engineer repairs a damaged drone using the specified replacement actuator.",
means: "Install the compatible actuator with the correct tools and service knowledge.",
desired: "Restore the drone's integrity.",
target_kind: Resource,
component: ResourceState,
admission: Admissible,
required: &[Op::ResourceRepair, Op::ResourceConsume],
forbidden: &[Op::CapabilityGrant],
bargain: None,
},
Candidate {
id: "technology-fabricate-key",
domain: "technological",
scenario: "A fabricator produces a replacement key from an authorized pattern and feedstock.",
means: "Run the exact pattern on a compatible fabricator while consuming feedstock.",
desired: "Create a key resource under the operator's custody.",
target_kind: Resource,
component: ResourceState,
admission: Admissible,
required: &[Op::ResourceConsume, Op::ResourceCreate],
forbidden: &[Op::AdmitEntity],
bargain: None,
},
Candidate {
id: "technology-hack-airgap",
domain: "technological",
scenario: "A hacker tries to rewrite an air-gapped computer they cannot physically or electronically reach.",
means: "Type commands into an unrelated terminal with no route to the target.",
desired: "Alter the remote computer.",
target_kind: Resource,
component: Condition,
admission: Impossible,
required: &[],
forbidden: &[Op::ConditionApply, Op::KnowledgeAcquire],
bargain: Some("establish a physical, network, supply-chain, or social access path"),
},
Candidate {
id: "extraordinary-costly-teleport",
domain: "extraordinary",
scenario: "A permitted teleporter crosses a known route at the accepted cost.",
means: "Invoke the approved teleport capability and pay its exact exposure cost.",
desired: "Relocate to the known destination.",
target_kind: Place,
component: Occupancy,
admission: Admissible,
required: &[Op::Relocate, Op::ConditionApply],
forbidden: &[Op::TopologyAdd],
bargain: None,
},
Candidate {
id: "extraordinary-heal",
domain: "extraordinary",
scenario: "A healer uses an admitted gift to reduce a present ally's injury within its effect ceiling.",
means: "Touch the consenting ally and invoke the gift while accepting its fatigue cost.",
desired: "Reduce the injury and apply fatigue to the healer.",
target_kind: Actor,
component: Condition,
admission: Admissible,
required: &[Op::ConditionAlter, Op::ConditionApply],
forbidden: &[Op::CapabilityGrant],
bargain: None,
},
Candidate {
id: "extraordinary-omniscience",
domain: "extraordinary",
scenario: "A novice claims to read every private mind in the setting without such permission.",
means: "Concentrate and assert universal access.",
desired: "Acquire every actor's private knowledge.",
target_kind: Population,
component: Knowledge,
admission: Impossible,
required: &[],
forbidden: &[Op::KnowledgeAcquire],
bargain: Some(
"negotiate a narrowly scoped capability, exact targets, resistance, exposure, and an effect ceiling",
),
},
Candidate {
id: "collective-evacuation",
domain: "collective",
scenario: "A village council organizes a voluntary evacuation along an open road.",
means: "Broadcast the plan, assign transport, and coordinate willing households.",
desired: "Move the population to the refuge.",
target_kind: Population,
component: Occupancy,
admission: Admissible,
required: &[Op::Relocate],
forbidden: &[Op::PopulationTransfer],
bargain: None,
},
Candidate {
id: "collective-strike",
domain: "collective",
scenario: "Workers vote to strike and withdraw labor from their employer.",
means: "Use their recognized assembly and communication channels to coordinate refusal.",
desired: "Change the workforce posture and increase production pressure.",
target_kind: Population,
component: Posture,
admission: Admissible,
required: &[Op::PostureChange, Op::PressureAdvance],
forbidden: &[Op::RelationshipAlter],
bargain: None,
},
Candidate {
id: "collective-arena-command",
domain: "collective",
scenario: "Rival factions share one low-budget arena cell and the arena proposes a unified decree.",
means: "Speak as if the simulation cell itself were a sovereign actor.",
desired: "Change both rivals' posture as one collective.",
target_kind: Population,
component: Posture,
admission: Impossible,
required: &[],
forbidden: &[Op::PostureChange],
bargain: Some(
"attribute separate proposals to exact constituents or establish a real collective authority",
),
},
Candidate {
id: "identity-sable-disclosure",
domain: "identity_privacy",
scenario: "A named refugee tells Ash which personal handle Ash may use.",
means: "Sable speaks the exact self-presentation to Ash in a private, reachable conversation.",
desired: "Disclose Sable's existing handle to Ash without globally renaming the actor.",
target_kind: Actor,
component: Identity,
admission: Admissible,
required: &[Op::IdentityDisclose],
forbidden: &[Op::IdentityAdopt],
bargain: None,
},
Candidate {
id: "identity-adopt-alias",
domain: "identity_privacy",
scenario: "An actor deliberately adopts a new operational alias for a mission.",
means: "Choose the alias under self-authority and disclose it to the team.",
desired: "Add the alias and reveal it to exact teammates.",
target_kind: Actor,
component: Identity,
admission: Admissible,
required: &[Op::IdentityAdopt, Op::IdentityDisclose],
forbidden: &[Op::KnowledgeAcquire],
bargain: None,
},
Candidate {
id: "identity-erase-memory",
domain: "identity_privacy",
scenario: "A speaker demands that a witness forget a disclosed secret without memory-altering power.",
means: "Tell the witness to forget what they heard.",
desired: "Remove the witness's private memory and knowledge.",
target_kind: Actor,
component: Knowledge,
admission: Impossible,
required: &[],
forbidden: &[Op::MemoryRetire, Op::KnowledgeInvalidate],
bargain: Some(
"gain consent for a mundane concealment plan or an admitted memory-altering capability with resistance and cost",
),
},
Candidate {
id: "population-join-refugees",
domain: "population_migration",
scenario: "A displaced actor is accepted into a refugee population at its current camp.",
means: "Ask to join, receive acceptance, and take on the population's ordinary obligations.",
desired: "Join the population without losing individual identity.",
target_kind: Population,
component: PopulationMembership,
admission: Admissible,
required: &[Op::PopulationJoin],
forbidden: &[Op::AdmitEntity],
bargain: None,
},
Candidate {
id: "population-dispersal",
domain: "population_migration",
scenario: "A refugee population disperses its exact members among several destination populations.",
means: "Coordinate destination placements and travel for consenting members.",
desired: "Transfer memberships and relocate the exact people.",
target_kind: Population,
component: PopulationMembership,
admission: Admissible,
required: &[Op::PopulationTransfer, Op::Relocate],
forbidden: &[Op::PopulationMerge],
bargain: None,
},
Candidate {
id: "population-return-callback",
domain: "population_migration",
scenario: "A previously helped refugee later appears after settling in a destination town.",
means: "The same actor travels from their destination population into the player's scene.",
desired: "Relocate the stable actor while preserving identity, memory, and relationship.",
target_kind: Actor,
component: Occupancy,
admission: Admissible,
required: &[Op::Relocate],
forbidden: &[Op::AdmitEntity, Op::IdentityAdopt],
bargain: None,
},
Candidate {
id: "infrastructure-open-bridge",
domain: "infrastructure_logistics",
scenario: "Engineers finish repairing a bridge and reopen its existing route.",
means: "Complete the admitted repair and pass structural inspection.",
desired: "Restore the bridge resource and open the route.",
target_kind: Place,
component: Topology,
admission: Admissible,
required: &[Op::ResourceRepair, Op::TopologyOpen],
forbidden: &[Op::TopologyAdd],
bargain: None,
},
Candidate {
id: "infrastructure-reroute-convoy",
domain: "infrastructure_logistics",
scenario: "A convoy uses a known alternate route around a blockade.",
means: "Follow the open alternate road with sufficient fuel and route knowledge.",
desired: "Move the convoy population to the next waypoint.",
target_kind: Population,
component: Occupancy,
admission: Admissible,
required: &[Op::Relocate, Op::ResourceConsume],
forbidden: &[Op::TopologyAdd],
bargain: None,
},
Candidate {
id: "infrastructure-adjacent-city",
domain: "infrastructure_logistics",
scenario: "A traveler claims a faraway city is adjacent despite persistent topology.",
means: "Walk through an invented shortcut that has never been admitted.",
desired: "Arrive instantly without traversing or changing topology.",
target_kind: Place,
component: Occupancy,
admission: Impossible,
required: &[],
forbidden: &[Op::Relocate, Op::TopologyAdd],
bargain: Some(
"travel along existing routes or compile an evidence-grounded branch-local connection",
),
},
Candidate {
id: "medical-treat-wound",
domain: "medical_body",
scenario: "A medic cleans and dresses a present patient's moderate wound with available supplies.",
means: "Use sterile dressing and supported clinical capability with consent.",
desired: "Reduce the wound condition while consuming the dressing.",
target_kind: Actor,
component: Condition,
admission: Admissible,
required: &[Op::ConditionAlter, Op::ResourceConsume],
forbidden: &[Op::ConditionClear],
bargain: None,
},
Candidate {
id: "medical-administer-dose",
domain: "medical_body",
scenario: "A clinician gives an exact medicine dose from a lot under clinic custody.",
means: "Measure and administer the dose to the consenting patient.",
desired: "Consume the dose and apply its supported treatment condition.",
target_kind: Actor,
component: Condition,
admission: Admissible,
required: &[Op::ResourceSplit, Op::ResourceConsume, Op::ConditionApply],
forbidden: &[Op::ResourceCreate],
bargain: None,
},
Candidate {
id: "medical-instant-resurrection",
domain: "medical_body",
scenario: "An ordinary first-aider tries to resurrect someone whose death is established.",
means: "Perform basic first aid without an extraordinary permission or viable body state.",
desired: "Retire death and restore life instantly.",
target_kind: Actor,
component: Condition,
admission: Impossible,
required: &[],
forbidden: &[Op::ConditionClear, Op::CapabilityGrant],
bargain: Some(
"establish a setting-supported resurrection capability, prerequisites, costs, opposition, and effect ceiling",
),
},
];
candidates.into_iter().map(materialize_candidate).collect()
}
fn materialize_candidate(candidate: Candidate<'_>) -> AgencyAttemptCase {
let actor = SubjectRef {
kind: SubjectKind::Actor,
id: format!("case:{}:actor", candidate.id),
};
let target = SubjectRef {
kind: candidate.target_kind,
id: format!("case:{}:target", candidate.id),
};
AgencyAttemptCase {
schema: "ghostlight.agency_attempt_case.v1".into(),
id: candidate.id.into(),
domain: candidate.domain.into(),
scenario: candidate.scenario.into(),
world_fixture_ids: vec![format!("agency-fixture:{}", candidate.id)],
means: ActionMeans {
schema: "ghostlight.action_means.v1".into(),
actor,
description: candidate.means.into(),
targets: vec![target.clone()],
instruments: vec![],
places: vec![],
route_ids: BTreeSet::new(),
channels: vec![],
speech: None,
state_references: vec![],
},
intended_effects: vec![MutationIntent {
schema: "ghostlight.mutation_intent.v1".into(),
component: candidate.component,
targets: vec![target],
desired_change: candidate.desired.into(),
}],
expected_admission: candidate.admission,
expected_mutation_operations: candidate.required.iter().copied().collect(),
forbidden_mutation_operations: candidate.forbidden.iter().copied().collect(),
expected_bargains: candidate.bargain.into_iter().map(str::to_owned).collect(),
equivalent_lanes: BTreeSet::from([
AgencyResolutionLane::Foreground,
AgencyResolutionLane::Npc,
AgencyResolutionLane::StrategicActor,
]),
invariant_witnesses: vec![
"means never commits the intended effect".into(),
"the exact authority envelope bounds every committed mutation".into(),
],
review_status: "candidate".into(),
missing_primitive: None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::persistence::CampaignStore;
#[test]
fn seed_spans_every_required_domain_and_round_trips_through_cultcache() {
let cases = seed_agency_attempt_cases();
assert_eq!(cases.len(), 36);
let domains = cases
.iter()
.map(|case| case.domain.as_str())
.collect::<BTreeSet<_>>();
assert_eq!(domains.len(), 12);
assert!(
cases
.iter()
.any(|case| case.id == "identity-sable-disclosure")
);
assert!(
cases
.iter()
.any(|case| case.id == "population-return-callback")
);
let path = std::env::temp_dir().join(format!(
"ghostlight-agency-corpus-{}.cc",
uuid::Uuid::new_v4().simple()
));
let store = CampaignStore::open(&path).unwrap();
for case in &cases {
store
.insert(
"agency_attempt_case.v1",
"ghostlight.agency_attempt_case.v1",
&case.id,
case,
)
.unwrap();
}
let loaded = store
.load_all::<AgencyAttemptCase>("agency_attempt_case.v1")
.unwrap();
assert_eq!(loaded.len(), cases.len());
drop(store);
std::fs::remove_file(path).unwrap();
}
#[test]
fn impossible_cases_never_require_a_committed_mutation() {
for case in seed_agency_attempt_cases() {
if case.expected_admission == AgencyAdmissionExpectation::Impossible {
assert!(case.expected_mutation_operations.is_empty(), "{}", case.id);
assert!(
!case.forbidden_mutation_operations.is_empty(),
"{}",
case.id
);
}
}
}
}

View file

@ -1,865 +0,0 @@
use crate::model::{
ModelInputItem, ModelPort, ModelStageReceipt, ModelStageRequest,
mark_model_receipt_semantic_invalid, render_model_input, run_validated_conversation_stage,
};
use async_trait::async_trait;
use serde::{Serialize, de::DeserializeOwned};
use std::collections::BTreeSet;
pub struct ModelAgentSpec {
pub stage: String,
pub model: String,
pub snapshot_binding: String,
pub instructions: String,
pub source_receipt_ids: Vec<String>,
pub temperature: Option<f64>,
pub max_output_tokens: Option<u32>,
pub max_steps: usize,
}
#[derive(Debug)]
pub struct ModelAgentRun<Output> {
pub output: Output,
pub receipts: Vec<ModelStageReceipt>,
}
#[derive(Debug)]
pub enum ModelAgentProgress<Output> {
Accepted(ModelAgentRun<Output>),
Exhausted(ModelAgentExhausted),
}
#[derive(Debug)]
pub struct ModelAgentExhausted {
pub stage: String,
pub max_steps: usize,
pub final_observation: Option<serde_json::Value>,
pub receipts: Vec<ModelStageReceipt>,
}
impl ModelAgentExhausted {
pub fn message(&self) -> String {
format!(
"model agent {} exhausted {} semantic steps; final tool observation: {}",
self.stage,
self.max_steps,
self.final_observation
.as_ref()
.map(serde_json::Value::to_string)
.unwrap_or_else(|| "none".into()),
)
}
fn into_failure(self) -> ModelAgentFailure {
ModelAgentFailure {
message: self.message(),
receipts: self.receipts,
}
}
}
#[derive(Debug)]
pub struct ModelAgentFailure {
pub message: String,
pub receipts: Vec<ModelStageReceipt>,
}
impl std::fmt::Display for ModelAgentFailure {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.message)
}
}
impl std::error::Error for ModelAgentFailure {}
pub struct ModelAgentToolContext {
/// Causal model/tool receipt ancestry for this action. These IDs prove how
/// the action was produced; they are not source evidence for canonical
/// world facts or profiles.
pub source_receipt_ids: Vec<String>,
/// The receipt for the model action currently being executed. Tools that
/// admit a narrower semantic object may rebind this receipt to that exact
/// object and return the rebound receipt with their accepted output.
pub current_model_receipt: Option<ModelStageReceipt>,
}
pub enum ModelAgentToolOutcome<Output, Finding> {
/// The typed action was applied to the tool's private workbench, but the
/// agent has not yet produced a terminal result. Canonical state remains
/// untouched; the observation describes the updated draft or next need.
Continue {
observation: Finding,
receipts: Vec<ModelStageReceipt>,
},
Accepted {
output: Output,
receipts: Vec<ModelStageReceipt>,
},
Rejected {
finding: Finding,
receipts: Vec<ModelStageReceipt>,
},
Failed {
message: String,
receipts: Vec<ModelStageReceipt>,
},
}
#[async_trait]
pub trait ModelAgentTool: Send {
type Action: DeserializeOwned + Serialize + Send;
type Output: Send;
type Finding: Serialize + Send;
/// The tool owns the action space that is legal at its current private
/// workbench state. The agent loop asks again before every model step so a
/// rejected action can narrow the next call to the exact repair surface.
fn action_schema(&self) -> std::result::Result<serde_json::Value, String>;
/// Projects the private workbench state needed for the next semantic step.
/// Tools that return a snapshot replace accumulated model chatter and old
/// observations with this bounded state. The harness preserves the stable
/// instruction prefix, while the tool remains the owner of what working
/// memory the agent actually needs.
fn context_snapshot(&self) -> Option<serde_json::Value> {
None
}
/// Projects the dynamic private workbench before the first semantic step.
/// This is deliberately separate from the stable agent instructions so a
/// recurring agent can keep one cacheable identity prefix while each task
/// supplies only its bounded current assignment. Tools opt in explicitly;
/// existing agents keep their original one-message first request.
fn initial_context_snapshot(&self) -> Option<serde_json::Value> {
None
}
async fn invoke(
&mut self,
action: Self::Action,
context: &ModelAgentToolContext,
) -> ModelAgentToolOutcome<Self::Output, Self::Finding>;
}
pub async fn run_model_agent<Tool: ModelAgentTool>(
port: &dyn ModelPort,
spec: &ModelAgentSpec,
tool: &mut Tool,
) -> std::result::Result<ModelAgentRun<Tool::Output>, ModelAgentFailure> {
match run_model_agent_progress(port, spec, tool).await? {
ModelAgentProgress::Accepted(run) => Ok(run),
ModelAgentProgress::Exhausted(exhausted) => Err(exhausted.into_failure()),
}
}
pub async fn run_model_agent_progress<Tool: ModelAgentTool>(
port: &dyn ModelPort,
spec: &ModelAgentSpec,
tool: &mut Tool,
) -> std::result::Result<ModelAgentProgress<Tool::Output>, ModelAgentFailure> {
if spec.max_steps == 0 {
return Err(ModelAgentFailure {
message: format!("model agent {} has no semantic step budget", spec.stage),
receipts: Vec::new(),
});
}
let mut receipts = Vec::new();
let mut input = vec![ModelInputItem::user(format!(
"{}\n\nAGENT STEP: 1 of {}. Choose one typed tool action admitted by the current output schema. The harness will execute it against the frozen state and return the real tool observation. Do not claim success yourself; only an accepted tool result can end the task.",
spec.instructions, spec.max_steps
))];
if let Some(snapshot) = tool.initial_context_snapshot() {
input.push(ModelInputItem::user(format!(
"CURRENT WORKBENCH STATE:\n{}",
serde_json::to_string(&snapshot).unwrap_or_else(|_| "null".into()),
)));
}
let mut last_observation = None;
for step in 0..spec.max_steps {
let action_schema = match tool.action_schema() {
Ok(schema) => schema,
Err(message) => {
return Err(ModelAgentFailure {
message: format!(
"model agent {} tool could not publish its current action schema: {message}",
spec.stage
),
receipts,
});
}
};
let source_receipt_ids = causal_source_ids(&spec.source_receipt_ids, &receipts);
let request = ModelStageRequest {
stage: spec.stage.clone(),
model: spec.model.clone(),
snapshot_binding: spec.snapshot_binding.clone(),
lived_stream: render_model_input(&input),
output_schema: Some(action_schema),
source_receipt_ids,
temperature: spec.temperature,
max_output_tokens: spec.max_output_tokens,
};
let mut stage = match run_validated_conversation_stage(port, &request, &input).await {
Ok(stage) => stage,
Err(error) => {
return Err(ModelAgentFailure {
message: format!(
"model agent {} transport or schema stage failed: {error}",
spec.stage
),
receipts,
});
}
};
let action_value = match stage.structured.take() {
Some(value) => value,
None => {
let finding = serde_json::json!({
"kind":"action_decode_error",
"message":"agent returned no typed action",
});
mark_model_receipt_semantic_invalid(&mut stage.receipt, &finding);
append_agent_observation(
&mut input,
&stage.narrative,
step,
spec.max_steps,
"rejected",
&finding,
);
last_observation = Some(finding);
receipts.push(stage.receipt);
continue;
}
};
let action = match serde_json::from_value::<Tool::Action>(action_value.clone()) {
Ok(action) => action,
Err(error) => {
let finding = serde_json::json!({
"kind":"action_decode_error",
"message":error.to_string(),
});
mark_model_receipt_semantic_invalid(&mut stage.receipt, &finding);
append_agent_observation(
&mut input,
&stage.narrative,
step,
spec.max_steps,
"rejected",
&finding,
);
last_observation = Some(finding);
receipts.push(stage.receipt);
continue;
}
};
let tool_context = ModelAgentToolContext {
source_receipt_ids: causal_source_ids(
&spec.source_receipt_ids,
&receipts
.iter()
.cloned()
.chain(std::iter::once(stage.receipt.clone()))
.collect::<Vec<_>>(),
),
current_model_receipt: Some(stage.receipt.clone()),
};
match tool.invoke(action, &tool_context).await {
ModelAgentToolOutcome::Continue {
observation,
receipts: tool_receipts,
} => {
let observation = match serde_json::to_value(observation) {
Ok(observation) => observation,
Err(error) => {
let message = format!(
"model agent {} could not serialize its typed tool observation: {error}",
spec.stage
);
mark_model_receipt_semantic_invalid(&mut stage.receipt, &message);
receipts.push(stage.receipt);
receipts.extend(tool_receipts);
return Err(ModelAgentFailure { message, receipts });
}
};
update_agent_context(
&mut input,
&stage.narrative,
step,
spec.max_steps,
"continued",
&observation,
tool.context_snapshot(),
);
last_observation = Some(observation);
receipts.push(stage.receipt);
receipts.extend(tool_receipts);
}
ModelAgentToolOutcome::Accepted {
output,
receipts: tool_receipts,
} => {
receipts.push(stage.receipt);
receipts.extend(tool_receipts);
return Ok(ModelAgentProgress::Accepted(ModelAgentRun {
output,
receipts,
}));
}
ModelAgentToolOutcome::Rejected {
finding,
receipts: tool_receipts,
} => {
let finding = match serde_json::to_value(finding) {
Ok(finding) => finding,
Err(error) => {
let message = format!(
"model agent {} could not serialize its typed tool finding: {error}",
spec.stage
);
mark_model_receipt_semantic_invalid(&mut stage.receipt, &message);
receipts.push(stage.receipt);
receipts.extend(tool_receipts);
return Err(ModelAgentFailure { message, receipts });
}
};
mark_model_receipt_semantic_invalid(&mut stage.receipt, &finding);
update_agent_context(
&mut input,
&stage.narrative,
step,
spec.max_steps,
"rejected",
&finding,
tool.context_snapshot(),
);
last_observation = Some(finding);
receipts.push(stage.receipt);
receipts.extend(tool_receipts);
}
ModelAgentToolOutcome::Failed {
message,
receipts: tool_receipts,
} => {
mark_model_receipt_semantic_invalid(&mut stage.receipt, &message);
receipts.push(stage.receipt);
receipts.extend(tool_receipts);
return Err(ModelAgentFailure { message, receipts });
}
}
}
Ok(ModelAgentProgress::Exhausted(ModelAgentExhausted {
stage: spec.stage.clone(),
max_steps: spec.max_steps,
final_observation: last_observation,
receipts,
}))
}
/// Builds one deterministic causal ancestry set for every model stage. This is
/// model/tool provenance only; callers must not reuse it as canonical world
/// evidence.
pub(crate) fn causal_source_ids(base: &[String], receipts: &[ModelStageReceipt]) -> Vec<String> {
base.iter()
.cloned()
.chain(
receipts
.iter()
.map(|receipt| receipt.storage_key().to_owned()),
)
.collect::<BTreeSet<_>>()
.into_iter()
.collect()
}
fn append_agent_observation(
input: &mut Vec<ModelInputItem>,
assistant_output: &str,
step: usize,
max_steps: usize,
status: &str,
observation: &serde_json::Value,
) {
input.push(ModelInputItem::assistant(assistant_output));
if step + 1 < max_steps {
input.push(ModelInputItem::user(format!(
"TOOL OBSERVATION AFTER AGENT STEP {} ({status}):\n{}\n\nAGENT STEP: {} of {max_steps}. Return the next complete typed tool action. Preserve frozen identity and useful valid draft work; change only what the observation actually rejects or requests.",
step + 1,
serde_json::to_string(observation).unwrap_or_else(|_| "null".into()),
step + 2,
)));
}
}
fn update_agent_context(
input: &mut Vec<ModelInputItem>,
assistant_output: &str,
step: usize,
max_steps: usize,
status: &str,
observation: &serde_json::Value,
context_snapshot: Option<serde_json::Value>,
) {
match context_snapshot {
Some(snapshot) if step + 1 < max_steps => {
input.truncate(1);
input.push(ModelInputItem::user(format!(
"AGENT STEP: {} of {max_steps}. Return the next complete typed tool action. The private workbench has replaced prior model chatter with its current bounded state. Preserve frozen identity and useful admitted work; change only what the latest observation actually rejects or requests.\n\nCURRENT WORKBENCH STATE:\n{}\n\nLATEST TOOL OBSERVATION AFTER AGENT STEP {} ({status}):\n{}",
step + 2,
serde_json::to_string(&snapshot).unwrap_or_else(|_| "null".into()),
step + 1,
serde_json::to_string(observation).unwrap_or_else(|_| "null".into()),
)));
}
_ => append_agent_observation(
input,
assistant_output,
step,
max_steps,
status,
observation,
),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{MODEL_BALANCED, ModelProviderOutput};
use anyhow::Result;
use async_trait::async_trait;
use schemars::{JsonSchema, schema_for};
use serde::{Deserialize, Serialize};
use std::sync::Mutex;
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
struct CandidateAction {
value: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum ExactFinding {
DraftStored { value: String },
WrongValue { received: String },
}
struct ScriptedModel {
outputs: Mutex<Vec<String>>,
requests: Mutex<Vec<ModelStageRequest>>,
}
#[async_trait]
impl ModelPort for ScriptedModel {
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
self.requests.lock().unwrap().push(request.clone());
Ok(self.outputs.lock().unwrap().remove(0))
}
async fn run_observed(&self, request: &ModelStageRequest) -> Result<ModelProviderOutput> {
Ok(ModelProviderOutput {
content: self.run(request).await?,
resolved_model: Some("gpt-5.6-terra".into()),
..Default::default()
})
}
fn provider(&self) -> &'static str {
"fixture"
}
}
struct ExactTool;
#[async_trait]
impl ModelAgentTool for ExactTool {
type Action = CandidateAction;
type Output = String;
type Finding = ExactFinding;
fn action_schema(&self) -> std::result::Result<serde_json::Value, String> {
serde_json::to_value(schema_for!(CandidateAction)).map_err(|error| error.to_string())
}
async fn invoke(
&mut self,
action: Self::Action,
_context: &ModelAgentToolContext,
) -> ModelAgentToolOutcome<Self::Output, Self::Finding> {
if action.value == "accepted" {
ModelAgentToolOutcome::Accepted {
output: action.value,
receipts: Vec::new(),
}
} else if action.value == "drafted" {
ModelAgentToolOutcome::Continue {
observation: ExactFinding::DraftStored {
value: action.value,
},
receipts: Vec::new(),
}
} else {
ModelAgentToolOutcome::Rejected {
finding: ExactFinding::WrongValue {
received: action.value.clone(),
},
receipts: vec![fixture_tool_receipt(&action.value)],
}
}
}
}
struct NarrowingTool {
draft_stored: bool,
}
struct SnapshotTool {
step: usize,
}
#[async_trait]
impl ModelAgentTool for SnapshotTool {
type Action = CandidateAction;
type Output = String;
type Finding = ExactFinding;
fn action_schema(&self) -> std::result::Result<serde_json::Value, String> {
serde_json::to_value(schema_for!(CandidateAction)).map_err(|error| error.to_string())
}
fn initial_context_snapshot(&self) -> Option<serde_json::Value> {
Some(serde_json::json!({"assignment":"immutable facts", "step":self.step}))
}
fn context_snapshot(&self) -> Option<serde_json::Value> {
Some(serde_json::json!({"assignment":"immutable facts", "step":self.step}))
}
async fn invoke(
&mut self,
action: Self::Action,
_context: &ModelAgentToolContext,
) -> ModelAgentToolOutcome<Self::Output, Self::Finding> {
self.step += 1;
if action.value == "accepted" {
ModelAgentToolOutcome::Accepted {
output: action.value,
receipts: Vec::new(),
}
} else {
ModelAgentToolOutcome::Continue {
observation: ExactFinding::DraftStored {
value: action.value,
},
receipts: Vec::new(),
}
}
}
}
#[async_trait]
impl ModelAgentTool for NarrowingTool {
type Action = CandidateAction;
type Output = String;
type Finding = ExactFinding;
fn action_schema(&self) -> std::result::Result<serde_json::Value, String> {
let value = if self.draft_stored {
"accepted"
} else {
"drafted"
};
Ok(serde_json::json!({
"type":"object",
"additionalProperties":false,
"required":["value"],
"properties":{"value":{"const":value}}
}))
}
async fn invoke(
&mut self,
action: Self::Action,
_context: &ModelAgentToolContext,
) -> ModelAgentToolOutcome<Self::Output, Self::Finding> {
if self.draft_stored {
assert_eq!(action.value, "accepted");
ModelAgentToolOutcome::Accepted {
output: action.value,
receipts: Vec::new(),
}
} else {
assert_eq!(action.value, "drafted");
self.draft_stored = true;
ModelAgentToolOutcome::Continue {
observation: ExactFinding::DraftStored {
value: action.value,
},
receipts: Vec::new(),
}
}
}
}
fn fixture_tool_receipt(value: &str) -> ModelStageReceipt {
ModelStageReceipt {
schema: "ghostlight.model_stage_receipt.v1".into(),
receipt_hash: String::new(),
provider: "fixture-tool".into(),
model: "deterministic".into(),
stage: "fixture_tool_validation".into(),
snapshot_binding: "snapshot:1".into(),
request_hash: format!("request:{value}"),
output_hash: format!("tool:{value}"),
source_receipt_ids: Vec::new(),
latency_ms: 0,
validation_result: "semantic_invalid".into(),
local_validation_error: Some(format!("rejected {value}")),
input_chars: 0,
output_chars: 0,
provider_attempts: Vec::new(),
}
}
#[tokio::test]
async fn semantic_tool_observation_drives_a_causally_receipted_second_action() {
let model = ScriptedModel {
outputs: Mutex::new(vec![
r#"{"value":"rejected"}"#.into(),
r#"{"value":"accepted"}"#.into(),
]),
requests: Mutex::new(Vec::new()),
};
let spec = ModelAgentSpec {
stage: "fixture_agent".into(),
model: MODEL_BALANCED.into(),
snapshot_binding: "snapshot:1".into(),
instructions: "Use the tool.".into(),
source_receipt_ids: vec!["source:one".into()],
temperature: Some(0.0),
max_output_tokens: Some(128),
max_steps: 2,
};
let run = run_model_agent(&model, &spec, &mut ExactTool)
.await
.unwrap();
assert_eq!(run.output, "accepted");
assert_eq!(run.receipts.len(), 3);
assert_eq!(run.receipts[0].validation_result, "semantic_invalid");
assert_eq!(run.receipts[1].stage, "fixture_tool_validation");
assert_eq!(run.receipts[2].validation_result, "valid");
assert!(
run.receipts[2]
.source_receipt_ids
.contains(&run.receipts[0].storage_key().to_owned())
);
assert!(
run.receipts[2]
.source_receipt_ids
.contains(&run.receipts[1].storage_key().to_owned())
);
let requests = model.requests.lock().unwrap();
assert!(requests[1].lived_stream.contains("wrong_value"));
assert!(requests[1].lived_stream.contains("ASSISTANT:"));
assert!(
requests[1]
.lived_stream
.starts_with(&requests[0].lived_stream)
);
assert_eq!(requests[0].output_schema, requests[1].output_schema);
}
#[tokio::test]
async fn successful_nonterminal_tool_action_preserves_draft_progress() {
let model = ScriptedModel {
outputs: Mutex::new(vec![
r#"{"value":"drafted"}"#.into(),
r#"{"value":"accepted"}"#.into(),
]),
requests: Mutex::new(Vec::new()),
};
let spec = ModelAgentSpec {
stage: "fixture_agent".into(),
model: MODEL_BALANCED.into(),
snapshot_binding: "snapshot:1".into(),
instructions: "Use the tool.".into(),
source_receipt_ids: vec!["source:one".into()],
temperature: Some(0.0),
max_output_tokens: Some(128),
max_steps: 2,
};
let run = run_model_agent(&model, &spec, &mut ExactTool)
.await
.unwrap();
assert_eq!(run.output, "accepted");
assert_eq!(run.receipts.len(), 2);
assert_eq!(run.receipts[0].validation_result, "valid");
assert_eq!(run.receipts[1].validation_result, "valid");
let requests = model.requests.lock().unwrap();
assert!(requests[1].lived_stream.contains("continued"));
assert!(requests[1].lived_stream.contains("draft_stored"));
assert!(
requests[1]
.source_receipt_ids
.contains(&run.receipts[0].storage_key().to_owned())
);
}
#[tokio::test]
async fn dynamic_workbench_state_does_not_pollute_the_stable_agent_prefix() {
let model = ScriptedModel {
outputs: Mutex::new(vec![
r#"{"value":"drafted"}"#.into(),
r#"{"value":"accepted"}"#.into(),
]),
requests: Mutex::new(Vec::new()),
};
let spec = ModelAgentSpec {
stage: "fixture_agent".into(),
model: MODEL_BALANCED.into(),
snapshot_binding: "snapshot:1".into(),
instructions: "A stable recurring identity.".into(),
source_receipt_ids: Vec::new(),
temperature: Some(0.0),
max_output_tokens: Some(128),
max_steps: 2,
};
let run = run_model_agent(&model, &spec, &mut SnapshotTool { step: 0 })
.await
.unwrap();
assert_eq!(run.output, "accepted");
let requests = model.requests.lock().unwrap();
let stable_prefix = requests[0]
.lived_stream
.split("\n\nUSER:\nCURRENT WORKBENCH STATE")
.next()
.unwrap();
assert!(stable_prefix.contains("A stable recurring identity."));
assert!(!stable_prefix.contains("immutable facts"));
assert!(requests[0].lived_stream.contains(r#""step":0"#));
assert!(requests[1].lived_stream.starts_with(stable_prefix));
assert!(requests[1].lived_stream.contains(r#""step":1"#));
}
#[tokio::test]
async fn tool_state_owns_each_steps_exact_action_schema() {
let model = ScriptedModel {
outputs: Mutex::new(vec![
r#"{"value":"drafted"}"#.into(),
r#"{"value":"accepted"}"#.into(),
]),
requests: Mutex::new(Vec::new()),
};
let spec = ModelAgentSpec {
stage: "fixture_agent".into(),
model: MODEL_BALANCED.into(),
snapshot_binding: "snapshot:1".into(),
instructions: "Use the current tool contract.".into(),
source_receipt_ids: vec!["source:one".into()],
temperature: Some(0.0),
max_output_tokens: Some(128),
max_steps: 2,
};
let mut tool = NarrowingTool {
draft_stored: false,
};
let run = run_model_agent(&model, &spec, &mut tool).await.unwrap();
assert_eq!(run.output, "accepted");
let requests = model.requests.lock().unwrap();
assert_eq!(
requests[0].output_schema.as_ref().unwrap()["properties"]["value"]["const"],
"drafted"
);
assert_eq!(
requests[1].output_schema.as_ref().unwrap()["properties"]["value"]["const"],
"accepted"
);
assert!(
!requests[1]
.lived_stream
.contains("CURRENT LEGAL TOOL ACTION SCHEMA")
);
}
#[tokio::test]
async fn exhausted_agent_preserves_every_action_and_tool_receipt() {
let model = ScriptedModel {
outputs: Mutex::new(vec![
r#"{"value":"first"}"#.into(),
r#"{"value":"second"}"#.into(),
]),
requests: Mutex::new(Vec::new()),
};
let spec = ModelAgentSpec {
stage: "fixture_agent".into(),
model: MODEL_BALANCED.into(),
snapshot_binding: "snapshot:1".into(),
instructions: "Use the tool.".into(),
source_receipt_ids: vec!["source:one".into()],
temperature: Some(0.0),
max_output_tokens: Some(128),
max_steps: 2,
};
let failure = run_model_agent(&model, &spec, &mut ExactTool)
.await
.unwrap_err();
assert!(failure.message.contains("exhausted 2 semantic steps"));
assert_eq!(failure.receipts.len(), 4);
assert_eq!(failure.receipts[0].validation_result, "semantic_invalid");
assert_eq!(failure.receipts[1].stage, "fixture_tool_validation");
assert_eq!(failure.receipts[2].validation_result, "semantic_invalid");
assert_eq!(failure.receipts[3].stage, "fixture_tool_validation");
assert!(
failure.receipts[2]
.source_receipt_ids
.contains(&failure.receipts[0].storage_key().to_owned())
);
assert!(
failure.receipts[2]
.source_receipt_ids
.contains(&failure.receipts[1].storage_key().to_owned())
);
}
#[tokio::test]
async fn progress_api_returns_exhaustion_as_resumable_state() {
let model = ScriptedModel {
outputs: Mutex::new(vec![r#"{"value":"still-wrong"}"#.into()]),
requests: Mutex::new(Vec::new()),
};
let spec = ModelAgentSpec {
stage: "fixture_agent".into(),
model: MODEL_BALANCED.into(),
snapshot_binding: "snapshot:1".into(),
instructions: "Use the tool.".into(),
source_receipt_ids: vec!["source:one".into()],
temperature: Some(0.0),
max_output_tokens: Some(128),
max_steps: 1,
};
let progress = run_model_agent_progress(&model, &spec, &mut ExactTool)
.await
.unwrap();
let ModelAgentProgress::Exhausted(exhausted) = progress else {
panic!("one rejected action must remain resumable")
};
assert_eq!(exhausted.stage, "fixture_agent");
assert_eq!(exhausted.max_steps, 1);
assert_eq!(exhausted.receipts.len(), 2);
assert_eq!(exhausted.final_observation.unwrap()["kind"], "wrong_value");
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -1,34 +0,0 @@
use ghostlight_dungeon::{agency_corpus::seed_agency_attempt_cases, persistence::CampaignStore};
use std::path::PathBuf;
fn main() -> anyhow::Result<()> {
let path = std::env::args_os()
.nth(1)
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("target/ghostlight-agency-corpus.cc"));
if path.exists() {
anyhow::bail!(
"agency corpus target already exists; choose a fresh path: {}",
path.display()
);
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let store = CampaignStore::open(&path)?;
let cases = seed_agency_attempt_cases();
for case in &cases {
store.insert(
"agency_attempt_case.v1",
"ghostlight.agency_attempt_case.v1",
&case.id,
case,
)?;
}
println!(
"materialized {} typed agency cases at {}",
cases.len(),
path.display()
);
Ok(())
}

View file

@ -1,262 +0,0 @@
use anyhow::{Context, Result};
use ghostlight_dungeon::{
domain::{
Campaign, CellAppraisal, GestaltMaterializationReceipt, RejectedProposalReceipt,
ResolutionCover, RollReceipt, StrategicActivityOutcome, StrategicTickReceipt,
WorldCommitReceipt,
},
model::ModelStageReceipt,
persistence::CampaignStore,
};
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
fn main() -> Result<()> {
let store_path = std::env::args()
.nth(1)
.context("usage: ghostlight-campaign-inspect <campaign.cc>")?;
let store = CampaignStore::open(store_path)?;
let campaign_key = store
.keys("campaign.v1")?
.into_iter()
.next()
.context("store contains no campaign.v1 state")?;
let (_, campaign) = store
.load::<Campaign>("campaign.v1", &campaign_key)?
.context("campaign.v1 row disappeared during inspection")?;
let mut ticks = store.load_all::<StrategicTickReceipt>("strategic_tick.v1")?;
ticks.sort_by_key(|tick| tick.revision);
let latest_tick = ticks.last();
let resolution_epoch = latest_tick.and_then(|tick| tick.resolution_epoch);
let snapshot_revision = latest_tick.map(|tick| tick.previous_revision);
let cover = match (snapshot_revision, resolution_epoch) {
(Some(revision), Some(epoch)) => store
.load_all::<ResolutionCover>("resolution_cover.v1")?
.into_iter()
.find(|cover| cover.world_revision == revision && cover.resolution_epoch == epoch),
_ => None,
};
let appraisals = match (snapshot_revision, resolution_epoch) {
(Some(revision), Some(epoch)) => store
.load_all::<CellAppraisal>("cell_appraisal.v1")?
.into_iter()
.filter(|appraisal| {
appraisal.world_revision == revision && appraisal.resolution_epoch == epoch
})
.collect::<Vec<_>>(),
_ => Vec::new(),
};
let outcomes = match (latest_tick, resolution_epoch) {
(Some(tick), Some(epoch)) => {
let prefix = format!("{}:{epoch}:", tick.revision);
let mut outcomes = Vec::new();
for key in store.keys("strategic_activity_outcome.v1")? {
if key.starts_with(&prefix)
&& let Some((_, outcome)) = store
.load::<StrategicActivityOutcome>("strategic_activity_outcome.v1", &key)?
{
outcomes.push(outcome);
}
}
outcomes.sort_by(|left, right| left.action_digest.cmp(&right.action_digest));
outcomes
}
_ => Vec::new(),
};
let mut rejected = store.load_all::<RejectedProposalReceipt>("rejected_proposal_receipt.v1")?;
rejected.sort_by_key(|receipt| (receipt.revision, receipt.rejected_at));
let rejected = rejected
.into_iter()
.rev()
.take(16)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect::<Vec<_>>();
let mut presence =
store.load_all::<GestaltMaterializationReceipt>("gestalt_materialization_receipt.v1")?;
presence.sort_by_key(|receipt| receipt.revision);
let presence = presence.into_iter().rev().take(16).collect::<Vec<_>>();
let receipt_hashes = latest_tick
.map(|tick| tick.model_receipt_hashes.iter().cloned().collect())
.unwrap_or_else(BTreeSet::new);
let mut model_receipts = Vec::new();
for hash in &receipt_hashes {
if let Some((_, receipt)) =
store.load::<ModelStageReceipt>("persona_stage_receipt.v1", hash)?
{
model_receipts.push(json!({
"receiptHash": receipt.storage_key(),
"stage": receipt.stage,
"provider": receipt.provider,
"model": receipt.model,
"snapshotBinding": receipt.snapshot_binding,
"latencyMs": receipt.latency_ms,
"validationResult": receipt.validation_result,
"inputChars": receipt.input_chars,
"outputChars": receipt.output_chars,
"attempts": receipt.provider_attempts.iter().map(|attempt| json!({
"finishReason": attempt.finish_reason,
"latencyMs": attempt.latency_ms,
"tokenUsage": attempt.token_usage,
"localValidationResult": attempt.local_validation_result,
})).collect::<Vec<_>>(),
}));
}
}
let recent_revision_bindings = (campaign.revision.saturating_sub(3)..=campaign.revision)
.map(|revision| format!("campaign:{}:revision:{revision}", campaign.id))
.collect::<Vec<_>>();
let mut recent_model_receipts = store
.load_all::<ModelStageReceipt>("persona_stage_receipt.v1")?
.into_iter()
.filter(|receipt| {
recent_revision_bindings
.iter()
.any(|binding| receipt.snapshot_binding.contains(binding))
})
.collect::<Vec<_>>();
recent_model_receipts.sort_by(|left, right| left.storage_key().cmp(right.storage_key()));
let mut newspaper_model_receipts = store
.load_all::<ModelStageReceipt>("persona_stage_receipt.v1")?
.into_iter()
.filter(|receipt| receipt.stage.starts_with("newspaper_"))
.collect::<Vec<_>>();
newspaper_model_receipts.sort_by(|left, right| left.storage_key().cmp(right.storage_key()));
let assessment_mutation_scopes =
store.load_all::<serde_json::Value>("assessment_mutation_scope_cache.v1")?;
let mut roll_receipts = store.load_all::<RollReceipt>("roll_receipt.v1")?;
roll_receipts.reverse();
roll_receipts.truncate(16);
let mut commit_receipts = store.load_all::<WorldCommitReceipt>("world_commit_receipt.v1")?;
commit_receipts.sort_by_key(|receipt| receipt.revision);
let commit_receipts = commit_receipts
.into_iter()
.rev()
.take(16)
.collect::<Vec<_>>();
let mut subjects = BTreeMap::new();
for actor in campaign.actors.values() {
let profile = campaign.agency_profiles.get(&actor.id);
subjects.insert(
actor.id.clone(),
json!({
"kind": "actor",
"name": actor.name,
"locationId": actor.location_id,
"simulationEligible": profile.is_none_or(|profile| profile.simulation_eligible),
"goals": actor.goals,
"obligations": actor.obligations,
"relationships": actor.relationships,
"memories": actor.memories,
"knowledge": actor.knowledge,
}),
);
}
for institution in campaign.institutions.values() {
subjects.insert(
institution.id.clone(),
json!({ "kind": "institution", "name": institution.name }),
);
}
for gestalt in campaign.gestalts.values() {
let profile = campaign.agency_profiles.get(&gestalt.id);
subjects.insert(
gestalt.id.clone(),
json!({
"kind": "gestalt",
"name": gestalt.name,
"homeLocationId": gestalt.home_location_id,
"activeLeaf": profile.is_some_and(|profile| profile.active_leaf),
"simulationEligible": profile.is_some_and(|profile| profile.simulation_eligible),
"locationIds": profile.map(|profile| &profile.location_ids),
"parentSubjectId": profile.and_then(|profile| profile.parent_subject_id.as_deref()),
"goals": gestalt.goals,
"pressures": gestalt.pressures,
"knowledge": gestalt.shared_knowledge,
}),
);
}
for member in campaign.gestalt_members.values() {
subjects.insert(
member.id.clone(),
json!({
"kind": "gestalt_member",
"name": member.name,
"gestaltId": member.gestalt_id,
"goals": member.goals,
"obligations": member.obligations,
"relationships": member.relationships,
"memories": member.memories,
"knowledge": ghostlight_dungeon::resolution::effective_member_knowledge(
&campaign,
&member.id,
)?,
}),
);
}
let event_ids = latest_tick
.map(|tick| tick.event_ids.iter().cloned().collect::<BTreeSet<_>>())
.unwrap_or_default();
let events = campaign
.events
.iter()
.filter(|event| event_ids.contains(&event.id))
.collect::<Vec<_>>();
let news = campaign
.news
.iter()
.filter(|issue| issue.event_ids.iter().any(|id| event_ids.contains(id)))
.collect::<Vec<_>>();
println!(
"{}",
serde_json::to_string_pretty(&json!({
"schema": "ghostlight.campaign_inspection.v1",
"campaign": {
"id": campaign.id,
"name": campaign.name,
"revision": campaign.revision,
"worldTime": campaign.world_time,
"strategicTickCount": campaign.strategic_tick_count,
"resolutionEpoch": campaign.resolution_policy.resolution_epoch,
"configuredBudget": campaign.resolution_policy.active_cell_budget,
"subjectCounts": {
"actors": campaign.actors.len(),
"institutions": campaign.institutions.len(),
"gestalts": campaign.gestalts.len(),
"gestaltMembers": campaign.gestalt_members.len(),
},
},
"subjectDirectory": subjects,
"locations": campaign.locations,
"civicSystems": campaign.civic_systems,
"agencyRelations": campaign.agency_relations,
"latestStrategicTick": latest_tick,
"cover": cover,
"appraisals": appraisals,
"activityOutcomes": outcomes,
"rejectedProposals": rejected,
"recentPresenceReceipts": presence,
"recentTranscript": campaign.transcript.iter().rev().take(24).collect::<Vec<_>>(),
"recentWorldEvents": campaign.events.iter().rev().take(24).collect::<Vec<_>>(),
"pendingWorldProposals": campaign.pending_world_proposals,
"recentModelReceipts": recent_model_receipts,
"newspaperModelReceipts": newspaper_model_receipts,
"assessmentMutationScopes": assessment_mutation_scopes,
"recentRollReceipts": roll_receipts,
"recentCommitReceipts": commit_receipts,
"events": events,
"news": news,
"modelReceipts": model_receipts,
"missingModelReceiptHashes": receipt_hashes.into_iter().filter(|hash| {
!model_receipts.iter().any(|receipt| receipt["receiptHash"] == *hash)
}).collect::<Vec<_>>(),
}))?
);
Ok(())
}

View file

@ -1,25 +0,0 @@
use anyhow::{Context, Result};
use ghostlight_dungeon::mesh::MeshPublisher;
use uuid::Uuid;
fn main() -> Result<()> {
let mut args = std::env::args().skip(1);
let store_path = args
.next()
.context("usage: ghostlight-mesh-inspect <copied-mesh.cc> <campaign-id>")?;
let campaign_id = args
.next()
.context("usage: ghostlight-mesh-inspect <copied-mesh.cc> <campaign-id>")?
.parse::<Uuid>()
.context("campaign-id must be a UUID")?;
if args.next().is_some() {
anyhow::bail!("usage: ghostlight-mesh-inspect <copied-mesh.cc> <campaign-id>");
}
let mesh = MeshPublisher::open(store_path, None)?;
let surface = mesh
.operator_surface(campaign_id)
.context("copied mesh contains no operator projection for this campaign")?;
println!("{}", serde_json::to_string_pretty(&surface)?);
Ok(())
}

View file

@ -1,483 +0,0 @@
use anyhow::{Context, Result, bail};
use base64::{Engine, engine::general_purpose::STANDARD};
use chrono::Utc;
use cultnet_rs::{
CULTNET_OPERATION_CONNECTION_ID, CultNetMessage, CultNetRudpSocketTransportConnection,
CultNetRudpSocketTransportOptions,
};
use ghostlight_dungeon::persistence::CampaignStore;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::json;
use std::{
io::Read,
net::{SocketAddr, UdpSocket},
path::{Path, PathBuf},
time::{Duration, Instant},
};
const SERVICE_ID: &str = "ghostlight.native.player";
const TARGET_RUNTIME_ID: &str = "ghostlight-dungeon-yggdrasil";
const DEFAULT_ENDPOINT: &str = "127.0.0.1:4102";
const CONNECTION_TIMEOUT: Duration = Duration::from_secs(120);
const DEFAULT_OPERATION_TIMEOUT: Duration = Duration::from_secs(120);
const EVE_INVOCATION_TIMEOUT: Duration = Duration::from_secs(600);
const NATIVE_OPERATION_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(5);
#[derive(Clone, Debug, Serialize, Deserialize)]
struct NativeClientState {
schema: String,
pending_handle: Option<String>,
session_token: Option<String>,
refresh_expires_at: Option<String>,
updated_at: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AuthBeginReceipt {
status: String,
handle: String,
expires_at: String,
navigation: AuthNavigation,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AuthNavigation {
url: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AuthCompletionReceipt {
status: String,
message: String,
session_token: Option<String>,
refresh_expires_at: Option<String>,
}
struct ClientStore {
store: CampaignStore,
row: Option<cultcache_legacy::CultCacheEnvelope>,
state: NativeClientState,
path: PathBuf,
}
impl ClientStore {
fn open(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref().to_path_buf();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let store = CampaignStore::open(&path)?;
let loaded = store.load::<NativeClientState>("native_client_state.v1", "primary")?;
let (row, state) = loaded.map_or_else(
|| {
(
None,
NativeClientState {
schema: "ghostlight.native_client_state.v1".into(),
pending_handle: None,
session_token: None,
refresh_expires_at: None,
updated_at: Utc::now().to_rfc3339(),
},
)
},
|(row, state)| (Some(row), state),
);
let client = Self {
store,
row,
state,
path,
};
client.restrict_permissions()?;
Ok(client)
}
fn commit(&mut self) -> Result<()> {
self.state.updated_at = Utc::now().to_rfc3339();
self.row = Some(match &self.row {
Some(row) => {
self.store
.replace(row, "ghostlight.native_client_state.v1", &self.state)?
}
None => self.store.insert(
"native_client_state.v1",
"ghostlight.native_client_state.v1",
"primary",
&self.state,
)?,
});
self.restrict_permissions()
}
fn restrict_permissions(&self) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for path in [&self.path, &self.path.with_extension("cc.lock")] {
if path.exists() {
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
}
}
}
Ok(())
}
}
fn main() -> Result<()> {
let (endpoint, state_path, command, rest) = parse_args()?;
let mut state = ClientStore::open(state_path)?;
match command.as_str() {
"auth-begin" => {
if state.state.pending_handle.is_some() {
bail!(
"A native authentication attempt is already pending. Run auth-complete before starting another."
);
}
let receipt: AuthBeginReceipt = invoke(
endpoint,
"ghostlight.auth.begin",
"ghostlight.native_auth_begin.v1",
&json!({"schema":"ghostlight.native_auth_begin.v1"}),
)?;
if receipt.status != "pending" || receipt.handle.is_empty() {
bail!("Ghostlight returned an invalid native authentication attempt");
}
state.state.pending_handle = Some(receipt.handle);
state.state.session_token = None;
state.state.refresh_expires_at = None;
state.commit()?;
println!(
"{}",
serde_json::to_string_pretty(&json!({
"status":"pending",
"authorizationUrl":receipt.navigation.url,
"expiresAt":receipt.expires_at
}))?
);
}
"auth-complete" => {
let handle = state
.state
.pending_handle
.clone()
.context("No pending native authentication attempt. Run auth-begin first.")?;
complete_authentication(endpoint, &mut state, &handle)?;
}
"auth-complete-stdin" => {
let mut handle = String::new();
std::io::stdin().read_to_string(&mut handle)?;
let handle = handle.trim();
if handle.is_empty() || handle.len() > 8_192 {
bail!("stdin did not contain one bounded opaque Heimdall attempt handle");
}
complete_authentication(endpoint, &mut state, handle)?;
}
"surface" => {
let session = state
.state
.session_token
.as_deref()
.context("Native Ghostlight client is not authenticated")?;
let value: serde_json::Value = invoke(
endpoint,
"ghostlight.surface.get",
"ghostlight.native_surface_get.v1",
&json!({"schema":"ghostlight.native_surface_get.v1","sessionToken":session,"invite":null}),
)?;
println!("{}", serde_json::to_string_pretty(&value)?);
}
"invoke" => {
if rest.len() != 3 {
bail!("invoke requires <operation> <payload-schema> <source-version>");
}
let session = state
.state
.session_token
.as_deref()
.context("Native Ghostlight client is not authenticated")?;
let source_version = rest[2].parse::<u64>()?;
let mut input = String::new();
std::io::stdin().read_to_string(&mut input)?;
let payload: serde_json::Value = if input.trim().is_empty() {
json!({})
} else {
serde_json::from_str(&input).context("decode invocation payload from stdin")?
};
let invocation = json!({
"schema":"gamecult.eve.command_invocation.v1",
"providerId":"gamecult.ghostlight.dungeon",
"surfaceId":"ghostlight.play",
"operation":{
"operationId":rest[0],
"schemaId":rest[1],
"idempotencyKey":uuid::Uuid::new_v4().to_string(),
"routeHint":{"sourceVersion":source_version,"transport":"cultnet-rudp"}
},
"payload":payload,
"issuedAt":Utc::now().to_rfc3339(),
"clientId":"ghostlight-native-client",
"commandBoundary":"ghostlight.eve.commands",
"receiptSchema":"gamecult.eve.command_result.v1"
});
let value: serde_json::Value = invoke(
endpoint,
"ghostlight.eve.invoke",
"ghostlight.native_eve_invocation.v1",
&json!({
"schema":"ghostlight.native_eve_invocation.v1",
"sessionToken":session,
"invocation":invocation
}),
)?;
if rest[0] == "app.auth.logout" && value["receipt"]["state"] == "accepted" {
state.state.session_token = None;
state.state.refresh_expires_at = None;
state.commit()?;
}
println!("{}", serde_json::to_string_pretty(&value)?);
}
_ => bail!("unknown native client command {command}"),
}
Ok(())
}
fn parse_args() -> Result<(SocketAddr, PathBuf, String, Vec<String>)> {
let mut args = std::env::args().skip(1).collect::<Vec<_>>();
let mut endpoint = DEFAULT_ENDPOINT.parse()?;
let mut state = None;
let mut index = 0;
while index < args.len() {
match args[index].as_str() {
"--endpoint" => {
let value = args.get(index + 1).context("--endpoint requires a value")?;
endpoint = value.parse()?;
args.drain(index..=index + 1);
}
"--state" => {
let value = args.get(index + 1).context("--state requires a value")?;
state = Some(PathBuf::from(value));
args.drain(index..=index + 1);
}
_ => index += 1,
}
}
let state = state.context("--state <path.cc> is required")?;
let command = args.first().cloned().context(
"usage: ghostlight-native-client --state <path.cc> [--endpoint host:port] auth-begin|auth-complete|auth-complete-stdin|surface|invoke",
)?;
Ok((endpoint, state, command, args.into_iter().skip(1).collect()))
}
fn complete_authentication(
endpoint: SocketAddr,
state: &mut ClientStore,
handle: &str,
) -> Result<()> {
let receipt: AuthCompletionReceipt = invoke(
endpoint,
"ghostlight.auth.complete",
"ghostlight.native_auth_complete.v1",
&json!({"schema":"ghostlight.native_auth_complete.v1","handle":handle}),
)?;
if apply_auth_completion(&mut state.state, handle, &receipt)? {
state.commit()?;
}
println!(
"{}",
serde_json::to_string_pretty(&json!({
"status":receipt.status,
"message":receipt.message,
"refreshExpiresAt":state.state.refresh_expires_at
}))?
);
Ok(())
}
fn apply_auth_completion(
state: &mut NativeClientState,
handle: &str,
receipt: &AuthCompletionReceipt,
) -> Result<bool> {
if receipt.status == "authenticated" {
state.session_token = Some(
receipt
.session_token
.clone()
.context("Authenticated native receipt omitted its session token")?,
);
state.refresh_expires_at = receipt.refresh_expires_at.clone();
state.pending_handle = None;
return Ok(true);
}
if receipt.status != "pending" && state.pending_handle.as_deref() == Some(handle) {
state.pending_handle = None;
return Ok(true);
}
Ok(false)
}
fn invoke<T: DeserializeOwned>(
endpoint: SocketAddr,
operation: &str,
payload_schema: &str,
payload: &impl Serialize,
) -> Result<T> {
let socket = UdpSocket::bind("127.0.0.1:0")?;
socket.set_read_timeout(Some(Duration::from_millis(25)))?;
let runtime_id = format!("ghostlight-native-client:{}", std::process::id());
let mut options = CultNetRudpSocketTransportOptions::client(
runtime_id.clone(),
socket,
endpoint,
CULTNET_OPERATION_CONNECTION_ID,
);
options.max_fragment_bytes = Some(2_048);
options.max_pending_reliable_packets = Some(4_096);
let mut transport = CultNetRudpSocketTransportConnection::new(options)?;
transport.connect(Vec::new())?;
let connection_deadline = Instant::now() + CONNECTION_TIMEOUT;
while !transport.connected() && Instant::now() < connection_deadline {
let _ = transport.receive_once()?;
transport.poll_resends()?;
}
if !transport.connected() {
bail!("Ghostlight native CultNet connection timed out");
}
let message_id = uuid::Uuid::new_v4().to_string();
transport.send_schema_message(&CultNetMessage::OperationRequest {
message_id: message_id.clone(),
service_id: SERVICE_ID.into(),
operation: operation.into(),
payload_schema: payload_schema.into(),
payload_encoding: "messagepack-base64".into(),
payload: STANDARD.encode(rmp_serde::to_vec_named(payload)?),
source_runtime_id: Some(runtime_id),
target_runtime_id: Some(TARGET_RUNTIME_ID.into()),
})?;
let operation_deadline = Instant::now() + operation_timeout(operation);
let mut next_keepalive = Instant::now() + NATIVE_OPERATION_KEEPALIVE_INTERVAL;
while Instant::now() < operation_deadline {
if let Some(response) = transport.receive_schema_message_once()? {
let CultNetMessage::OperationResponse {
message_id: response_id,
status,
payload_encoding,
payload,
diagnostics,
..
} = response
else {
continue;
};
if response_id != message_id {
continue;
}
if status != "accepted" {
bail!(
"Ghostlight denied the native operation: {}",
diagnostics.join("; ")
);
}
if payload_encoding != "messagepack-base64" {
bail!("Ghostlight returned an unsupported native payload encoding");
}
return Ok(rmp_serde::from_slice(&STANDARD.decode(payload)?)?);
}
if Instant::now() >= next_keepalive {
transport.ping(message_id.as_bytes().to_vec())?;
next_keepalive = Instant::now() + NATIVE_OPERATION_KEEPALIVE_INTERVAL;
}
transport.poll_resends()?;
}
let stats = transport.stats();
bail!(
"Ghostlight native operation timed out while connected={}; transport sent {} bytes/{} frames and received {} bytes/{} frames",
transport.connected(),
stats.bytes_sent,
stats.frames_sent,
stats.bytes_received,
stats.frames_received,
)
}
fn operation_timeout(operation: &str) -> Duration {
if operation == "ghostlight.eve.invoke" {
EVE_INVOCATION_TIMEOUT
} else {
DEFAULT_OPERATION_TIMEOUT
}
}
#[cfg(test)]
mod tests {
use super::*;
fn state(handle: Option<&str>) -> NativeClientState {
NativeClientState {
schema: "ghostlight.native_client_state.v1".into(),
pending_handle: handle.map(str::to_owned),
session_token: None,
refresh_expires_at: None,
updated_at: "2026-08-23T00:00:00Z".into(),
}
}
fn receipt(status: &str) -> AuthCompletionReceipt {
AuthCompletionReceipt {
status: status.into(),
message: status.into(),
session_token: (status == "authenticated").then(|| "session".into()),
refresh_expires_at: (status == "authenticated").then(|| "2026-09-23T00:00:00Z".into()),
}
}
#[test]
fn pending_completion_preserves_the_attempt() {
let mut state = state(Some("owned"));
assert!(!apply_auth_completion(&mut state, "owned", &receipt("pending")).unwrap());
assert_eq!(state.pending_handle.as_deref(), Some("owned"));
}
#[test]
fn terminal_completion_clears_only_its_owned_attempt() {
let mut owned = state(Some("owned"));
assert!(apply_auth_completion(&mut owned, "owned", &receipt("denied")).unwrap());
assert!(owned.pending_handle.is_none());
let mut other = state(Some("current"));
assert!(!apply_auth_completion(&mut other, "old", &receipt("denied")).unwrap());
assert_eq!(other.pending_handle.as_deref(), Some("current"));
}
#[test]
fn recovered_authenticated_attempt_supersedes_pending_state() {
let mut state = state(Some("current"));
assert!(
apply_auth_completion(&mut state, "completed-old", &receipt("authenticated")).unwrap()
);
assert!(state.pending_handle.is_none());
assert_eq!(state.session_token.as_deref(), Some("session"));
assert_eq!(
state.refresh_expires_at.as_deref(),
Some("2026-09-23T00:00:00Z")
);
}
#[test]
fn eve_invocation_wait_budget_is_separate_from_connection_and_authentication() {
assert_eq!(
operation_timeout("ghostlight.eve.invoke"),
Duration::from_secs(600)
);
assert_eq!(
operation_timeout("ghostlight.surface.get"),
Duration::from_secs(120)
);
assert_eq!(CONNECTION_TIMEOUT, Duration::from_secs(120));
assert!(NATIVE_OPERATION_KEEPALIVE_INTERVAL < DEFAULT_OPERATION_TIMEOUT);
}
}

View file

@ -1,35 +0,0 @@
use anyhow::{Result, bail};
use cultnet_rs::{
GameCultProviderHealthIdentity, enroll_service_identity_at, open_service_identity_at,
};
use std::path::PathBuf;
fn main() -> Result<()> {
let mut args = std::env::args().skip(1);
let action = args.next().unwrap_or_default();
let path = args.next().map(PathBuf::from);
if args.next().is_some()
|| path.is_none()
|| !matches!(action.as_str(), "enroll" | "public-key-hex")
{
bail!("Usage: ghostlight-provider-health-identity enroll|public-key-hex <private-store>");
}
let path = path.expect("validated above");
let signer = if action == "enroll" {
enroll_service_identity_at::<GameCultProviderHealthIdentity>(&path)?
} else {
open_service_identity_at::<GameCultProviderHealthIdentity>(&path)?
};
println!("{}", hex(&signer.entry().public_key));
Ok(())
}
fn hex(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut output = String::with_capacity(bytes.len() * 2);
for byte in bytes {
output.push(DIGITS[(byte >> 4) as usize] as char);
output.push(DIGITS[(byte & 0x0f) as usize] as char);
}
output
}

View file

@ -1,88 +0,0 @@
use anyhow::{Context, Result, bail};
use ghostlight_dungeon::{persistence::CampaignStore, session_zero::SessionZeroState};
use serde_json::json;
use std::collections::BTreeMap;
fn main() -> Result<()> {
let mut arguments = std::env::args().skip(1);
let store_path = arguments
.next()
.context("usage: ghostlight-session-zero-inspect <session-zero.cc> [receipt-limit]")?;
let limit = arguments
.next()
.map(|value| value.parse::<usize>())
.transpose()
.context("receipt limit must be a positive integer")?
.unwrap_or(8);
if limit == 0 {
bail!("receipt limit must be greater than zero");
}
let store = CampaignStore::open(store_path)?;
let key = store
.keys("session_zero.v1")?
.into_iter()
.next()
.context("store contains no session_zero.v1 state")?;
let (_, session) = store
.load::<SessionZeroState>("session_zero.v1", &key)?
.context("session_zero.v1 row disappeared during inspection")?;
let legacy_receipt_layout =
session.model_receipts.is_empty() && !session.preview_model_receipts.is_empty();
let audit_receipts = if legacy_receipt_layout {
&session.preview_model_receipts
} else {
&session.model_receipts
};
let first = audit_receipts.len().saturating_sub(limit);
let mut receipt_key_counts = BTreeMap::new();
for receipt in audit_receipts {
*receipt_key_counts
.entry(receipt.storage_key().to_owned())
.or_insert(0usize) += 1;
}
let duplicate_receipt_keys = receipt_key_counts
.into_iter()
.filter(|(_, count)| *count > 1)
.collect::<BTreeMap<_, _>>();
let receipts = audit_receipts[first..]
.iter()
.map(|receipt| {
json!({
"storageKey": receipt.storage_key(),
"stage": receipt.stage,
"provider": receipt.provider,
"model": receipt.model,
"snapshotBinding": receipt.snapshot_binding,
"requestHash": receipt.request_hash,
"outputHash": receipt.output_hash,
"latencyMs": receipt.latency_ms,
"validationResult": receipt.validation_result,
"inputChars": receipt.input_chars,
"outputChars": receipt.output_chars,
"attempts": receipt.provider_attempts.iter().map(|attempt| json!({
"finishReason": attempt.finish_reason,
"latencyMs": attempt.latency_ms,
"tokenUsage": attempt.token_usage,
"localValidationResult": attempt.local_validation_result,
})).collect::<Vec<_>>(),
})
})
.collect::<Vec<_>>();
println!(
"{}",
serde_json::to_string_pretty(&json!({
"schema": "ghostlight.session_zero_receipt_inspection.v1",
"sessionId": session.id,
"revision": session.revision,
"status": session.status,
"receiptCount": audit_receipts.len(),
"activePreviewReceiptCount": session.preview_model_receipts.len(),
"legacyReceiptLayout": legacy_receipt_layout,
"duplicateReceiptKeys": duplicate_receipt_keys,
"receipts": receipts,
}))?
);
Ok(())
}

File diff suppressed because it is too large Load diff

View file

@ -1,739 +0,0 @@
use crate::{
agent::{ModelAgentSpec, ModelAgentTool, ModelAgentToolContext, ModelAgentToolOutcome},
domain::{Campaign, Event, WorldEventScope},
model::{MODEL_BALANCED, ModelPort, ModelStageReceipt},
};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use schemars::{JsonSchema, schema_for};
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
use uuid::Uuid;
pub const CLOCK_CONSEQUENCE_BINDING_STAGE: &str = "clock_consequence_binding_agent_action";
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ClockConsequenceBinding {
pub clock_id: String,
pub scope: WorldEventScope,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ClockConsequenceBindingAdmission {
pub schema: String,
pub campaign_id: Uuid,
pub expected_revision: u64,
pub snapshot_binding: String,
pub binding_batch_digest: String,
pub bindings: Vec<ClockConsequenceBinding>,
pub accepted_model_receipt_id: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ClockConsequenceBindingReceipt {
pub schema: String,
pub campaign_id: Uuid,
pub previous_revision: u64,
pub revision: u64,
pub snapshot_binding: String,
pub binding_batch_digest: String,
pub bindings: Vec<ClockConsequenceBinding>,
pub model_receipt_ids: Vec<String>,
pub accepted_model_receipt_id: String,
pub emitted_event_ids: Vec<String>,
pub emitted_news_ids: Vec<String>,
pub news_count_before: usize,
pub next_wave_index: usize,
pub committed_at: DateTime<Utc>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ClockConsequenceBindingAction {
bindings: Vec<ClockConsequenceBinding>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(deny_unknown_fields)]
struct ClockConsequenceBindingFinding {
diagnostic: String,
}
struct ClockConsequenceBindingTool<'a> {
campaign: &'a Campaign,
schema: serde_json::Value,
}
#[async_trait]
impl ModelAgentTool for ClockConsequenceBindingTool<'_> {
type Action = ClockConsequenceBindingAction;
type Output = ClockConsequenceBindingAdmission;
type Finding = ClockConsequenceBindingFinding;
fn action_schema(&self) -> std::result::Result<serde_json::Value, String> {
Ok(self.schema.clone())
}
async fn invoke(
&mut self,
action: Self::Action,
context: &ModelAgentToolContext,
) -> ModelAgentToolOutcome<Self::Output, Self::Finding> {
match validate_clock_consequence_bindings(self.campaign, &action.bindings) {
Ok(()) => {
let Some(mut accepted_receipt) = context.current_model_receipt.clone() else {
return ModelAgentToolOutcome::Failed {
message: "clock binding tool lacks the current model receipt".into(),
receipts: Vec::new(),
};
};
let snapshot_binding = match clock_consequence_binding_snapshot(self.campaign) {
Ok(binding) => binding,
Err(error) => {
return ModelAgentToolOutcome::Failed {
message: error.to_string(),
receipts: Vec::new(),
};
}
};
let binding_batch_digest =
match clock_consequence_binding_batch_digest(self.campaign, &action.bindings) {
Ok(digest) => digest,
Err(error) => {
return ModelAgentToolOutcome::Failed {
message: error.to_string(),
receipts: Vec::new(),
};
}
};
accepted_receipt.rebind_snapshot(clock_consequence_admission_binding(
&snapshot_binding,
&binding_batch_digest,
));
let accepted_model_receipt_id = accepted_receipt.storage_key().to_owned();
ModelAgentToolOutcome::Accepted {
output: ClockConsequenceBindingAdmission {
schema: "ghostlight.clock_consequence_binding_admission.v1".into(),
campaign_id: self.campaign.id,
expected_revision: self.campaign.revision,
snapshot_binding,
binding_batch_digest,
bindings: action.bindings,
accepted_model_receipt_id,
},
receipts: vec![accepted_receipt],
}
}
Err(error) => ModelAgentToolOutcome::Rejected {
finding: ClockConsequenceBindingFinding {
diagnostic: error.to_string(),
},
receipts: Vec::new(),
},
}
}
}
pub fn clock_consequence_binding_snapshot(campaign: &Campaign) -> Result<String> {
crate::legacy_transition::digest_serializable(&serde_json::json!({
"campaign_id":campaign.id,
"revision":campaign.revision,
"clocks":campaign.clocks,
"actor_ids":campaign.actors.keys().collect::<Vec<_>>(),
"institution_ids":campaign.institutions.keys().collect::<Vec<_>>(),
"gestalt_ids":campaign.gestalts.keys().collect::<Vec<_>>(),
"locations":campaign.locations.iter().map(|(id, location)| serde_json::json!({
"id":id,
"name":location.name,
})).collect::<Vec<_>>(),
"public_channels":admitted_public_channels(campaign),
}))
}
pub async fn propose_clock_consequence_bindings(
model: &dyn ModelPort,
campaign: &Campaign,
) -> std::result::Result<
crate::agent::ModelAgentRun<ClockConsequenceBindingAdmission>,
crate::agent::ModelAgentFailure,
> {
let unbound = campaign
.clocks
.values()
.filter(|clock| clock.consequence_scope.is_unbound())
.collect::<Vec<_>>();
if unbound.is_empty() {
return Err(crate::agent::ModelAgentFailure {
message: "clock binding agent was invoked without unbound clocks".into(),
receipts: Vec::new(),
});
}
let projection = serde_json::json!({
"clocks":unbound,
"actors":campaign.actors.values().filter(|actor| stable_simulation_actor(campaign, &actor.id)).map(|actor| serde_json::json!({
"id":actor.id,
"name":actor.name,
"location_id":actor.location_id,
})).collect::<Vec<_>>(),
"institutions":campaign.institutions.values().filter(|institution| simulation_eligible_subject(campaign, &institution.id)).map(|institution| serde_json::json!({
"id":institution.id,
"name":institution.name,
"posture":institution.posture,
})).collect::<Vec<_>>(),
"gestalts":campaign.gestalts.values().filter(|gestalt| simulation_eligible_subject(campaign, &gestalt.id)).map(|gestalt| serde_json::json!({
"id":gestalt.id,
"name":gestalt.name,
"home_location_id":gestalt.home_location_id,
"pressures":gestalt.pressures,
})).collect::<Vec<_>>(),
"locations":campaign.locations.values().map(|location| serde_json::json!({
"id":location.id,
"name":location.name,
})).collect::<Vec<_>>(),
"public_channels":admitted_public_channels(campaign),
});
let instructions = format!(
"You are the autonomous clock-consequence binding worker. The world and each clock's consequence are frozen. Bind every supplied clock exactly once to the existing people, institutions, populations, places, and public information routes that would actually experience or learn its declared consequence. This is scope reconciliation, not invention: do not rewrite consequences, add entities, include the player-controlled subject, or indiscriminately select the whole world. Choose the smallest causally sufficient scope. A public material crisis should normally include at least one exact place, one affected or responsible subject, and one supplied public channel so subsequent autonomous cells can perceive and respond to it. Return the complete binding batch through the typed tool. The deterministic tool will reject unknown, duplicate, empty, or overbroad references.\n\nFROZEN WORLD PROJECTION:\n{}",
serde_json::to_string(&projection).map_err(|error| crate::agent::ModelAgentFailure {
message: error.to_string(),
receipts: Vec::new(),
})?
);
let mut schema =
serde_json::to_value(schema_for!(ClockConsequenceBindingAction)).map_err(|error| {
crate::agent::ModelAgentFailure {
message: error.to_string(),
receipts: Vec::new(),
}
})?;
crate::model_connector::project_strict_responses_schema(&mut schema).map_err(|error| {
crate::agent::ModelAgentFailure {
message: error.to_string(),
receipts: Vec::new(),
}
})?;
let binding = clock_consequence_binding_snapshot(campaign).map_err(|error| {
crate::agent::ModelAgentFailure {
message: error.to_string(),
receipts: Vec::new(),
}
})?;
let spec = ModelAgentSpec {
stage: CLOCK_CONSEQUENCE_BINDING_STAGE.into(),
model: MODEL_BALANCED.into(),
snapshot_binding: binding,
instructions,
source_receipt_ids: Vec::new(),
temperature: Some(0.1),
max_output_tokens: Some(3_000),
max_steps: 3,
};
let mut tool = ClockConsequenceBindingTool { campaign, schema };
crate::agent::run_model_agent(model, &spec, &mut tool).await
}
pub fn clock_consequence_binding_batch_digest(
campaign: &Campaign,
bindings: &[ClockConsequenceBinding],
) -> Result<String> {
crate::legacy_transition::digest_serializable(&serde_json::json!({
"schema":"ghostlight.clock_consequence_binding_batch.v1",
"campaign_id":campaign.id,
"expected_revision":campaign.revision,
"bindings":bindings,
}))
}
pub fn clock_consequence_admission_binding(
snapshot_binding: &str,
binding_batch_digest: &str,
) -> String {
format!("{snapshot_binding}:clock-consequence-binding-batch:{binding_batch_digest}")
}
pub fn validate_clock_consequence_bindings(
campaign: &Campaign,
bindings: &[ClockConsequenceBinding],
) -> Result<()> {
let expected = campaign
.clocks
.values()
.filter(|clock| clock.consequence_scope.is_unbound())
.map(|clock| clock.id.as_str())
.collect::<BTreeSet<_>>();
let supplied = bindings
.iter()
.map(|binding| binding.clock_id.as_str())
.collect::<BTreeSet<_>>();
if supplied.len() != bindings.len() || supplied != expected {
return Err(anyhow!(
"clock consequence bindings must name every unbound clock exactly once; expected {expected:?}, received {supplied:?}"
));
}
for binding in bindings {
validate_clock_consequence_scope(campaign, &binding.scope)?;
}
Ok(())
}
pub fn validate_clock_consequence_scope(
campaign: &Campaign,
scope: &WorldEventScope,
) -> Result<()> {
if scope.is_unbound() || scope.location_ids.is_empty() {
return Err(anyhow!(
"a clock consequence requires an exact affected location and observable scope"
));
}
if scope.actor_ids.is_empty()
&& scope.institution_ids.is_empty()
&& scope.gestalt_ids.is_empty()
{
return Err(anyhow!(
"a clock consequence requires at least one affected actor, institution, or population"
));
}
for (kind, values, maximum) in [
("actor", &scope.actor_ids, 8usize),
("institution", &scope.institution_ids, 8usize),
("population", &scope.gestalt_ids, 8usize),
("location", &scope.location_ids, 8usize),
("public channel", &scope.public_channels, 8usize),
] {
if values.len() > maximum || values.iter().collect::<BTreeSet<_>>().len() != values.len() {
return Err(anyhow!(
"clock consequence {kind} scope is duplicate or overbroad"
));
}
}
if scope
.actor_ids
.iter()
.any(|id| !stable_simulation_actor(campaign, id))
|| scope
.institution_ids
.iter()
.any(|id| !simulation_eligible_subject(campaign, id))
|| scope
.gestalt_ids
.iter()
.any(|id| !simulation_eligible_subject(campaign, id))
{
return Err(anyhow!(
"clock consequence scope cannot bind an externally controlled or ephemeral subject"
));
}
if scope
.actor_ids
.iter()
.any(|id| !campaign.actors.contains_key(id))
|| scope
.institution_ids
.iter()
.any(|id| !campaign.institutions.contains_key(id))
|| scope
.gestalt_ids
.iter()
.any(|id| !campaign.gestalts.contains_key(id))
|| scope
.location_ids
.iter()
.any(|id| !campaign.locations.contains_key(id))
{
return Err(anyhow!(
"clock consequence scope references an unknown subject or place"
));
}
let channels = admitted_public_channels(campaign);
if scope
.public_channels
.iter()
.any(|channel| !channels.contains(channel))
{
return Err(anyhow!(
"clock consequence scope references an unadmitted public channel"
));
}
Ok(())
}
fn simulation_eligible_subject(campaign: &Campaign, subject_id: &str) -> bool {
campaign
.agency_profiles
.get(subject_id)
.is_none_or(|profile| profile.simulation_eligible)
}
fn stable_simulation_actor(campaign: &Campaign, actor_id: &str) -> bool {
actor_id != campaign.player_actor_id
&& simulation_eligible_subject(campaign, actor_id)
&& !campaign
.gestalt_members
.values()
.any(|member| member.materialized_actor_id.as_deref() == Some(actor_id))
}
pub fn apply_clock_consequence_bindings(
campaign: &mut Campaign,
bindings: &[ClockConsequenceBinding],
) -> Result<Vec<String>> {
validate_clock_consequence_bindings(campaign, bindings)?;
for binding in bindings {
campaign
.clocks
.get_mut(&binding.clock_id)
.expect("binding set was validated")
.consequence_scope = binding.scope.clone();
}
materialize_due_clock_consequences(campaign)
}
/// Deterministically derives the once-only canonical event owned by a clock's
/// first threshold crossing. Callers invoke this after any admitted mutation
/// batch so every command path shares the same trigger behavior.
pub fn materialize_due_clock_consequences(campaign: &mut Campaign) -> Result<Vec<String>> {
let mut events = Vec::new();
for clock in campaign.clocks.values() {
if clock.progress < clock.threshold || clock.consequence_scope.is_unbound() {
continue;
}
validate_clock_consequence_scope(campaign, &clock.consequence_scope)?;
let event_id = format!("clock-consequence:{}", clock.id);
if campaign.events.iter().any(|event| event.id == event_id) {
continue;
}
let event = Event {
id: event_id.clone(),
at: campaign.world_time,
kind: "clock_consequence".into(),
summary: clock.consequence.trim().to_owned(),
actor_ids: clock.consequence_scope.actor_ids.clone(),
institution_ids: clock.consequence_scope.institution_ids.clone(),
gestalt_ids: clock.consequence_scope.gestalt_ids.clone(),
location_ids: clock.consequence_scope.location_ids.clone(),
public_channels: clock.consequence_scope.public_channels.clone(),
};
events.push(event);
}
let emitted = events
.iter()
.map(|event| event.id.clone())
.collect::<Vec<_>>();
for event in events {
crate::domain::append_event_with_publications(campaign, event);
}
Ok(emitted)
}
fn admitted_public_channels(campaign: &Campaign) -> BTreeSet<String> {
campaign
.agency_profiles
.values()
.flat_map(|profile| profile.information_channels.iter().cloned())
.chain(campaign.news.iter().map(|issue| issue.channel.clone()))
.filter(|channel| crate::resolution::information_channel_is_concrete(channel))
.collect()
}
pub fn validate_binding_receipts(
campaign: &Campaign,
admission: &ClockConsequenceBindingAdmission,
receipts: &[ModelStageReceipt],
) -> Result<()> {
let snapshot = clock_consequence_binding_snapshot(campaign)?;
let binding_batch_digest =
clock_consequence_binding_batch_digest(campaign, &admission.bindings)?;
if admission.schema != "ghostlight.clock_consequence_binding_admission.v1"
|| admission.campaign_id != campaign.id
|| admission.expected_revision != campaign.revision
|| admission.snapshot_binding != snapshot
|| admission.binding_batch_digest != binding_batch_digest
{
return Err(anyhow!(
"clock consequence binding admission does not match the frozen campaign and exact batch"
));
}
validate_clock_consequence_bindings(campaign, &admission.bindings)?;
let expected_receipt_binding =
clock_consequence_admission_binding(&snapshot, &binding_batch_digest);
let accepted = receipts
.iter()
.find(|receipt| receipt.storage_key() == admission.accepted_model_receipt_id)
.ok_or_else(|| anyhow!("clock consequence binding lacks its accepted model receipt"))?;
let mut rebound = accepted.clone();
rebound.rebind_snapshot(accepted.snapshot_binding.clone());
if accepted.schema != "ghostlight.persona_stage_receipt.v1"
|| accepted.stage != CLOCK_CONSEQUENCE_BINDING_STAGE
|| accepted.snapshot_binding != expected_receipt_binding
|| accepted.validation_result != "valid"
|| accepted.local_validation_error.is_some()
|| rebound.storage_key() != accepted.storage_key()
{
return Err(anyhow!(
"clock consequence binding accepted-model receipt is invalid or not bound to the exact batch"
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use sha2::{Digest, Sha256};
#[test]
fn binding_agent_schema_is_provider_strict() {
let mut schema = serde_json::to_value(schema_for!(ClockConsequenceBindingAction)).unwrap();
crate::model_connector::project_strict_responses_schema(&mut schema).unwrap();
}
fn bound_scope() -> WorldEventScope {
WorldEventScope {
actor_ids: Vec::new(),
institution_ids: vec!["court".into()],
gestalt_ids: Vec::new(),
location_ids: vec!["room".into()],
public_channels: vec!["court broadsheet".into()],
}
}
fn accepted_admission(
campaign: &Campaign,
bindings: Vec<ClockConsequenceBinding>,
) -> (ClockConsequenceBindingAdmission, ModelStageReceipt) {
let snapshot_binding = clock_consequence_binding_snapshot(campaign).unwrap();
let binding_batch_digest =
clock_consequence_binding_batch_digest(campaign, &bindings).unwrap();
let mut receipt = ModelStageReceipt {
schema: "ghostlight.persona_stage_receipt.v1".into(),
receipt_hash: String::new(),
provider: "fixture".into(),
model: "fixture-terra".into(),
stage: CLOCK_CONSEQUENCE_BINDING_STAGE.into(),
snapshot_binding: String::new(),
request_hash: format!("sha256:{:x}", Sha256::digest(b"request")),
output_hash: format!("sha256:{:x}", Sha256::digest(b"output")),
source_receipt_ids: Vec::new(),
latency_ms: 1,
validation_result: "valid".into(),
local_validation_error: None,
input_chars: 1,
output_chars: 1,
provider_attempts: Vec::new(),
};
receipt.rebind_snapshot(clock_consequence_admission_binding(
&snapshot_binding,
&binding_batch_digest,
));
let admission = ClockConsequenceBindingAdmission {
schema: "ghostlight.clock_consequence_binding_admission.v1".into(),
campaign_id: campaign.id,
expected_revision: campaign.revision,
snapshot_binding,
binding_batch_digest,
bindings,
accepted_model_receipt_id: receipt.storage_key().to_owned(),
};
(admission, receipt)
}
#[test]
fn due_clock_emits_exactly_one_grounded_public_event() {
let mut campaign = crate::kernel::tests::campaign();
campaign.institutions.insert(
"court".into(),
crate::domain::InstitutionState {
id: "court".into(),
name: "Court".into(),
resources: Vec::new(),
goals: Vec::new(),
posture: "watching".into(),
},
);
crate::resolution::ensure_agency_profiles(&mut campaign);
campaign
.agency_profiles
.get_mut("court")
.unwrap()
.information_channels
.insert("court broadsheet".into());
campaign.clocks.insert(
"coup".into(),
crate::domain::WorldClock {
id: "coup".into(),
label: "Coup".into(),
progress: 3,
threshold: 3,
consequence: "The palace guard arrests the regent at breakfast.".into(),
consequence_scope: bound_scope(),
},
);
assert_eq!(
materialize_due_clock_consequences(&mut campaign).unwrap(),
vec!["clock-consequence:coup"]
);
assert!(
materialize_due_clock_consequences(&mut campaign)
.unwrap()
.is_empty()
);
assert_eq!(
campaign
.events
.iter()
.filter(|event| event.kind == "clock_consequence")
.count(),
1
);
assert_eq!(
campaign.news.last().unwrap().event_ids,
["clock-consequence:coup"]
);
}
#[test]
fn shared_mutation_application_owns_threshold_crossing() {
let mut campaign = crate::kernel::tests::campaign();
campaign.institutions.insert(
"court".into(),
crate::domain::InstitutionState {
id: "court".into(),
name: "Court".into(),
resources: Vec::new(),
goals: Vec::new(),
posture: "watching".into(),
},
);
crate::resolution::ensure_agency_profiles(&mut campaign);
campaign
.agency_profiles
.get_mut("court")
.unwrap()
.information_channels
.insert("court broadsheet".into());
campaign.clocks.insert(
"coup".into(),
crate::domain::WorldClock {
id: "coup".into(),
label: "Coup".into(),
progress: 0,
threshold: 1,
consequence: "The palace guard arrests the regent at breakfast.".into(),
consequence_scope: bound_scope(),
},
);
let transition = crate::legacy_transition::lower_strategic_wave(
&campaign,
&crate::domain::StrategicTickPlan::default(),
"test-wave",
chrono::Utc::now() + chrono::Duration::minutes(1),
)
.unwrap()
.unwrap();
let receipt = crate::legacy_transition::apply_lowered_transition(
&mut campaign,
&transition,
chrono::Utc::now(),
)
.unwrap();
assert_eq!(campaign.clocks["coup"].progress, 1);
assert_eq!(receipt.derived_event_ids, ["clock-consequence:coup"]);
assert!(campaign.events.iter().any(|event| {
event.id == "clock-consequence:coup" && event.kind == "clock_consequence"
}));
assert!(
campaign
.news
.iter()
.any(|news| news.event_ids == ["clock-consequence:coup"])
);
}
#[test]
fn accepted_receipt_cannot_authorize_a_different_binding_batch() {
let mut campaign = crate::kernel::tests::campaign();
campaign.institutions.insert(
"court".into(),
crate::domain::InstitutionState {
id: "court".into(),
name: "Court".into(),
resources: Vec::new(),
goals: Vec::new(),
posture: "watching".into(),
},
);
crate::resolution::ensure_agency_profiles(&mut campaign);
campaign
.agency_profiles
.get_mut("court")
.unwrap()
.information_channels
.extend(["court broadsheet".into(), "court gazette".into()]);
campaign.clocks.insert(
"coup".into(),
crate::domain::WorldClock {
id: "coup".into(),
label: "Coup".into(),
progress: 0,
threshold: 1,
consequence: "The palace guard arrests the regent at breakfast.".into(),
consequence_scope: WorldEventScope::default(),
},
);
let bindings = vec![ClockConsequenceBinding {
clock_id: "coup".into(),
scope: bound_scope(),
}];
let (mut admission, receipt) = accepted_admission(&campaign, bindings);
validate_binding_receipts(&campaign, &admission, std::slice::from_ref(&receipt)).unwrap();
admission.bindings[0].scope.public_channels = vec!["court gazette".into()];
assert!(
validate_binding_receipts(&campaign, &admission, &[receipt])
.unwrap_err()
.to_string()
.contains("exact batch")
);
}
#[test]
fn consequence_scope_rejects_externally_controlled_subjects() {
let mut campaign = crate::kernel::tests::campaign();
campaign.institutions.insert(
"greathold".into(),
crate::domain::InstitutionState {
id: "greathold".into(),
name: "Greathold".into(),
resources: Vec::new(),
goals: Vec::new(),
posture: "player controlled".into(),
},
);
crate::resolution::ensure_agency_profiles(&mut campaign);
campaign
.agency_profiles
.get_mut("greathold")
.unwrap()
.simulation_eligible = false;
let scope = WorldEventScope {
actor_ids: Vec::new(),
institution_ids: vec!["greathold".into()],
gestalt_ids: Vec::new(),
location_ids: vec!["room".into()],
public_channels: Vec::new(),
};
assert!(
validate_clock_consequence_scope(&campaign, &scope)
.unwrap_err()
.to_string()
.contains("externally controlled")
);
}
}

File diff suppressed because one or more lines are too long

View file

@ -1,441 +0,0 @@
use crate::domain::{
ActorState, AgencyProfile, AgencyRelation, AgencySubjectKind, BranchOrigin, Campaign,
CanonCandidate, CellActionProposal, GestaltLineage, GestaltMemberDelta, GestaltPersonaState,
InstitutionState, Location, ResolutionPolicy, StrategicCellEffect, WorldClock, WorldFact,
};
use anyhow::{Result, anyhow};
use chrono::{DateTime, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use uuid::Uuid;
pub const WORLD_CONSUMER_SERVICE_ID: &str = "ghostlight.world.consumer";
pub const ADMIT_WORLD_OPERATION: &str = "ghostlight.world.seed.admit";
pub const APPLY_EXTERNAL_SNAPSHOT_OPERATION: &str = "ghostlight.world.external.snapshot.apply";
pub const LIST_EXTERNAL_PROPOSALS_OPERATION: &str = "ghostlight.world.external.proposals.list";
pub const ACKNOWLEDGE_EXTERNAL_PROPOSAL_OPERATION: &str =
"ghostlight.world.external.proposal.acknowledge";
pub const COMPOSE_NEWSPAPER_OPERATION: &str = "ghostlight.world.newspaper.compose";
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum WorldSeedProducerKind {
Compiler,
Consumer,
}
/// Initial canonical world state before runtime-only revision, transcript,
/// scheduling, and cover state exist.
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct WorldSeed {
pub schema: String,
pub id: Uuid,
pub name: String,
pub branch_origin: BranchOrigin,
pub world_time: DateTime<Utc>,
pub tick_hours: u32,
/// One subject protected from Ghostlight agency. Dungeon supplies its host
/// actor. A world consumer may supply an externally owned institution.
pub primary_controlled_subject_id: String,
pub locations: BTreeMap<String, Location>,
pub actors: BTreeMap<String, ActorState>,
pub institutions: BTreeMap<String, InstitutionState>,
pub clocks: BTreeMap<String, WorldClock>,
pub facts: BTreeMap<String, WorldFact>,
#[serde(default)]
pub canon_candidates: BTreeMap<String, CanonCandidate>,
#[serde(default)]
pub gestalts: BTreeMap<String, GestaltPersonaState>,
#[serde(default)]
pub gestalt_members: BTreeMap<String, GestaltMemberDelta>,
#[serde(default)]
pub agency_profiles: BTreeMap<String, AgencyProfile>,
#[serde(default)]
pub agency_relations: BTreeMap<String, AgencyRelation>,
#[serde(default)]
pub gestalt_lineages: BTreeMap<String, GestaltLineage>,
#[serde(default)]
pub resolution_policy: ResolutionPolicy,
}
impl WorldSeed {
pub fn from_campaign(campaign: &Campaign) -> Result<Self> {
if campaign.revision != 0
|| !campaign.transcript.is_empty()
|| !campaign.events.is_empty()
|| !campaign.news.is_empty()
|| !campaign.civic_systems.is_empty()
|| !campaign.pending_world_proposals.is_empty()
|| campaign.pending_ticks != 0
|| campaign.away_ticks_processed != 0
|| !campaign.resolution_pins.is_empty()
|| campaign.resolution_cover.is_some()
|| campaign.strategic_tick_count != 0
{
return Err(anyhow!(
"world seed cannot contain already-authoritative runtime or civic state"
));
}
Ok(Self {
schema: "ghostlight.world_seed.v1".into(),
id: campaign.id,
name: campaign.name.clone(),
branch_origin: campaign.branch_origin.clone(),
world_time: campaign.world_time,
tick_hours: campaign.tick_hours,
primary_controlled_subject_id: campaign.player_actor_id.clone(),
locations: campaign.locations.clone(),
actors: campaign.actors.clone(),
institutions: campaign.institutions.clone(),
clocks: campaign.clocks.clone(),
facts: campaign.facts.clone(),
canon_candidates: campaign.canon_candidates.clone(),
gestalts: campaign.gestalts.clone(),
gestalt_members: campaign.gestalt_members.clone(),
agency_profiles: campaign.agency_profiles.clone(),
agency_relations: campaign.agency_relations.clone(),
gestalt_lineages: campaign.gestalt_lineages.clone(),
resolution_policy: campaign.resolution_policy.clone(),
})
}
pub fn into_campaign(self) -> Campaign {
Campaign {
schema: "ghostlight.campaign.v1".into(),
id: self.id,
name: self.name,
revision: 0,
branch_origin: self.branch_origin,
world_time: self.world_time,
tick_hours: self.tick_hours,
player_actor_id: self.primary_controlled_subject_id,
locations: self.locations,
actors: self.actors,
institutions: self.institutions,
clocks: self.clocks,
facts: self.facts,
civic_systems: BTreeMap::new(),
transcript: Vec::new(),
last_player_activity: self.world_time,
pending_ticks: 0,
away_ticks_processed: 0,
events: Vec::new(),
news: Vec::new(),
canon_candidates: self.canon_candidates,
gestalts: self.gestalts,
gestalt_members: self.gestalt_members,
pending_world_proposals: Vec::new(),
agency_profiles: self.agency_profiles,
agency_relations: self.agency_relations,
gestalt_lineages: self.gestalt_lineages,
resolution_policy: self.resolution_policy,
resolution_pins: BTreeMap::new(),
resolution_cover: None,
nemesis_attention_history: Vec::new(),
strategic_tick_count: 0,
}
}
pub fn digest(&self) -> Result<String> {
crate::legacy_transition::digest_serializable(self)
}
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExternalSubjectAuthority {
pub schema: String,
pub id: String,
pub campaign_id: Uuid,
pub subject_id: String,
pub subject_kind: AgencySubjectKind,
pub owner_id: String,
pub authority_key_sha256: String,
#[serde(default)]
pub last_source_revision: Option<u64>,
#[serde(default)]
pub last_payload_digest: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct WorldSeedAdmission {
pub schema: String,
pub campaign_id: Uuid,
pub producer_id: String,
pub producer_kind: WorldSeedProducerKind,
pub seed_digest: String,
pub idempotency_key: String,
#[serde(default)]
pub external_subjects: Vec<ExternalSubjectAuthority>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct WorldSeedAdmissionReceipt {
pub schema: String,
pub campaign_id: Uuid,
pub producer_id: String,
pub seed_digest: String,
pub idempotency_key: String,
pub admitted_subject_ids: Vec<String>,
pub admitted_at: DateTime<Utc>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct WorldSeedAdmissionRequest {
pub schema: String,
pub seed: WorldSeed,
pub admission: WorldSeedAdmission,
/// Proves possession of every external authority declared in this request.
/// The raw value is never persisted.
pub authority_key: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExternalSubjectSnapshot {
pub schema: String,
pub campaign_id: Uuid,
pub expected_world_revision: u64,
pub authority_id: String,
pub owner_id: String,
pub authority_key: String,
pub source_revision: u64,
pub idempotency_key: String,
pub payload_digest: String,
pub projection: ExternalSubjectProjection,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(tag = "subject_kind", content = "state", rename_all = "snake_case")]
pub enum ExternalSubjectProjection {
Institution(InstitutionState),
Gestalt(GestaltPersonaState),
}
impl ExternalSubjectProjection {
pub fn subject_id(&self) -> &str {
match self {
Self::Institution(value) => &value.id,
Self::Gestalt(value) => &value.id,
}
}
pub fn subject_kind(&self) -> AgencySubjectKind {
match self {
Self::Institution(_) => AgencySubjectKind::Institution,
Self::Gestalt(_) => AgencySubjectKind::Gestalt,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExternalSnapshotReceipt {
pub schema: String,
pub id: String,
pub campaign_id: Uuid,
pub authority_id: String,
pub subject_id: String,
pub owner_id: String,
pub source_revision: u64,
pub payload_digest: String,
pub previous_world_revision: u64,
pub world_revision: u64,
pub committed_at: DateTime<Utc>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ExternalProposalStatus {
Pending,
Accepted,
PartiallyAccepted,
Rejected,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExternalWorldProposal {
pub schema: String,
pub id: String,
pub campaign_id: Uuid,
pub world_revision: u64,
pub authority_id: String,
pub external_subject_id: String,
pub source_subject_id: String,
pub intent: String,
pub intended_effect: String,
pub action_digest: String,
pub public_channels: Vec<String>,
pub state_references: Vec<String>,
pub status: ExternalProposalStatus,
pub created_at: DateTime<Utc>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExternalProposalListRequest {
pub schema: String,
pub campaign_id: Uuid,
pub authority_id: String,
pub owner_id: String,
pub authority_key: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExternalProposalList {
pub schema: String,
pub campaign_id: Uuid,
pub authority_id: String,
pub proposals: Vec<ExternalWorldProposal>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ExternalProposalAcknowledgement {
pub schema: String,
pub campaign_id: Uuid,
pub authority_id: String,
pub owner_id: String,
pub authority_key: String,
pub proposal_id: String,
pub idempotency_key: String,
pub status: ExternalProposalStatus,
pub result_summary: String,
pub acknowledged_at: DateTime<Utc>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ExternalProposalReceipt {
pub schema: String,
pub campaign_id: Uuid,
pub authority_id: String,
pub proposal_id: String,
pub idempotency_key: String,
pub status: ExternalProposalStatus,
pub result_summary: String,
pub acknowledged_at: DateTime<Utc>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct WorldNewspaperRequest {
pub schema: String,
pub campaign_id: Uuid,
pub authority_id: String,
pub owner_id: String,
pub authority_key: String,
pub title: String,
#[schemars(length(min = 1, max = 600))]
pub editorial_voice: String,
pub newsroom: crate::newspaper::WorldNewspaperNewsroom,
#[schemars(range(min = 1, max = 6))]
pub max_articles: u16,
}
pub fn authority_key_digest(value: &str) -> String {
format!("sha256:{:x}", Sha256::digest(value.as_bytes()))
}
pub fn validate_authority_key(authority: &ExternalSubjectAuthority, supplied: &str) -> Result<()> {
if supplied.is_empty() || authority_key_digest(supplied) != authority.authority_key_sha256 {
return Err(anyhow!("external subject authority proof is invalid"));
}
Ok(())
}
pub fn snapshot_payload_digest(snapshot: &ExternalSubjectSnapshot) -> Result<String> {
crate::legacy_transition::digest_serializable(&(
snapshot.campaign_id,
&snapshot.authority_id,
&snapshot.owner_id,
snapshot.source_revision,
&snapshot.idempotency_key,
&snapshot.projection,
))
}
pub fn validate_seed_admission(
seed: &WorldSeed,
admission: &WorldSeedAdmission,
authority_key: &str,
) -> Result<Campaign> {
if seed.schema != "ghostlight.world_seed.v1"
|| admission.schema != "ghostlight.world_seed_admission.v1"
|| seed.id != admission.campaign_id
|| admission.seed_digest != seed.digest()?
|| admission.producer_id.trim().is_empty()
|| admission.idempotency_key.trim().is_empty()
{
return Err(anyhow!("world seed admission envelope is inconsistent"));
}
let mut campaign = seed.clone().into_campaign();
crate::resolution::ensure_agency_profiles(&mut campaign);
crate::compiler::validate_campaign_seed(&campaign)?;
let mut seen = std::collections::BTreeSet::new();
let mut seen_subjects = std::collections::BTreeSet::new();
for authority in &admission.external_subjects {
if authority.schema != "ghostlight.external_subject_authority.v1"
|| authority.campaign_id != campaign.id
|| authority.owner_id != admission.producer_id
|| !seen.insert(authority.id.as_str())
|| !seen_subjects.insert(authority.subject_id.as_str())
|| authority.last_source_revision.is_some()
|| authority.last_payload_digest.is_some()
{
return Err(anyhow!(
"external subject authority envelope is inconsistent"
));
}
validate_authority_key(authority, authority_key)?;
let profile = campaign
.agency_profiles
.get_mut(&authority.subject_id)
.filter(|profile| profile.subject_kind == authority.subject_kind)
.ok_or_else(|| anyhow!("external authority subject or kind is unknown"))?;
match authority.subject_kind {
AgencySubjectKind::Institution
if campaign.institutions.contains_key(&authority.subject_id) => {}
AgencySubjectKind::Gestalt if campaign.gestalts.contains_key(&authority.subject_id) => {
}
_ => return Err(anyhow!("external authority subject kind is unsupported")),
}
profile.simulation_eligible = false;
}
crate::compiler::validate_campaign_seed(&campaign)?;
let primary = &campaign.player_actor_id;
if !campaign.actors.contains_key(primary)
&& !campaign.institutions.contains_key(primary)
&& !campaign.gestalts.contains_key(primary)
{
return Err(anyhow!("primary controlled subject is missing"));
}
if admission.producer_kind == WorldSeedProducerKind::Consumer
&& !admission
.external_subjects
.iter()
.any(|authority| authority.subject_id == *primary)
{
return Err(anyhow!(
"consumer seed primary controlled subject lacks external authority"
));
}
Ok(campaign)
}
pub fn proposal_targets(action: &CellActionProposal) -> Vec<&str> {
action
.effects
.iter()
.flat_map(|effect| match effect {
StrategicCellEffect::GestaltActivity {
target_subject_ids, ..
}
| StrategicCellEffect::ActorActivity {
target_subject_ids, ..
}
| StrategicCellEffect::MemberActivity {
target_subject_ids, ..
} => target_subject_ids
.iter()
.map(String::as_str)
.collect::<Vec<_>>(),
_ => Vec::new(),
})
.collect()
}

View file

@ -1,76 +0,0 @@
use crate::domain::{OutcomeBand, RollReceipt};
pub fn capped_modifier(values: impl IntoIterator<Item = i8>) -> i8 {
values
.into_iter()
.map(i16::from)
.sum::<i16>()
.clamp(-10, 10) as i8
}
pub fn outcome(d20: u8, modifier: i8, dc: u8) -> OutcomeBand {
let total = i16::from(d20) + i16::from(modifier);
let base = if total >= i16::from(dc) + 10 {
OutcomeBand::StrongSuccess
} else if total >= i16::from(dc) {
OutcomeBand::Success
} else if total >= i16::from(dc) - 5 {
OutcomeBand::Mixed
} else {
OutcomeBand::Failure
};
shift(
base,
if d20 == 20 {
1
} else if d20 == 1 {
-1
} else {
0
},
)
}
fn shift(band: OutcomeBand, delta: i8) -> OutcomeBand {
use OutcomeBand::*;
match (band, delta) {
(Failure, 1) => Mixed,
(Mixed, 1) => Success,
(Success, 1) => StrongSuccess,
(StrongSuccess, -1) => Success,
(Success, -1) => Mixed,
(Mixed, -1) => Failure,
(value, _) => value,
}
}
pub fn receipt(digest: String, d20: u8, modifier: i8, dc: u8) -> RollReceipt {
RollReceipt {
schema: "ghostlight.roll_receipt.v1".into(),
assessment_digest: digest,
d20,
modifier_total: modifier,
total: i16::from(d20) + i16::from(modifier),
dc,
outcome: outcome(d20, modifier, dc),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn caps_context_not_attributes() {
assert_eq!(capped_modifier([8, 7, -2]), 10);
}
#[test]
fn margin_bands_hold() {
assert_eq!(outcome(10, 0, 15), OutcomeBand::Mixed);
assert_eq!(outcome(15, 0, 15), OutcomeBand::Success);
assert_eq!(outcome(20, 5, 15), OutcomeBand::StrongSuccess);
}
#[test]
fn natural_one_only_shifts_one_band() {
assert_eq!(outcome(1, 10, 5), OutcomeBand::Mixed);
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,572 @@
//! Eve/CultUI projection for the one live world owner.
use crate::{
mesh::{COMMAND_BOUNDARY, COMMAND_RESULT_SCHEMA, PROVIDER_ID, SURFACE_ID},
world::{AffordanceKind, ControllerMode, DecisionAction, WorldPhase, WorldSnapshot},
};
use anyhow::{Context, bail};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct EveCommandInvocation {
pub(crate) schema: String,
#[serde(rename = "providerId")]
pub(crate) provider_id: String,
#[serde(rename = "surfaceId")]
pub(crate) surface_id: String,
pub(crate) operation: EveOperation,
pub(crate) payload: Value,
#[serde(rename = "issuedAt")]
pub(crate) issued_at: String,
#[serde(rename = "clientId")]
pub(crate) client_id: String,
#[serde(rename = "commandBoundary")]
pub(crate) command_boundary: String,
#[serde(rename = "receiptSchema")]
pub(crate) receipt_schema: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub(crate) struct EveOperation {
pub(crate) operation_id: String,
pub(crate) schema_id: Option<String>,
pub(crate) idempotency_key: Option<String>,
#[serde(default)]
pub(crate) route_hint: EveRouteHint,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub(crate) struct EveRouteHint {
pub(crate) source_version: Option<u64>,
pub(crate) transport: Option<String>,
}
pub(crate) fn surface_version(snapshot: Option<&WorldSnapshot>) -> u64 {
snapshot
.map(|world| world.revision.saturating_add(1))
.unwrap_or(0)
}
pub(crate) fn world_state(snapshot: Option<&WorldSnapshot>) -> &'static str {
match snapshot.map(|world| world.phase) {
None => "empty",
Some(WorldPhase::Draft) => "draft",
Some(WorldPhase::Active) => "active",
}
}
pub(crate) fn anonymous_surface() -> Value {
anonymous_surface_at(0)
}
pub(crate) fn mesh_surface(snapshot: Option<&WorldSnapshot>) -> Value {
anonymous_surface_at(surface_version(snapshot))
}
fn anonymous_surface_at(version: u64) -> Value {
surface_document(
version,
"Ghostlight Dungeon",
vec![
json!({
"id":"ghostlight.access",
"kind":"heimdall.access_gate",
"props":{
"state":"anonymous",
"title":"Enter Ghostlight",
"detail":"Sign in with Discord to reach the world owner."
},
"children":[]
}),
command_button(
"ghostlight.auth.begin",
"Continue with Discord",
"heimdall.auth.begin",
json!({}),
&[],
),
],
vec![command_descriptor(
"heimdall.auth.begin",
"heimdall.auth_begin_command.v1",
&[],
"Heimdall",
)],
)
}
pub(crate) fn authenticated_surface(
account: &str,
snapshot: Option<&WorldSnapshot>,
) -> anyhow::Result<Value> {
let version = surface_version(snapshot);
let mut children = vec![json!({
"id":"ghostlight.identity",
"kind":"heimdall.identity",
"props":{
"state":"authenticated",
"title":"Authenticated",
"detail":"Heimdall identity is bound server-side.",
"displayName":short_principal(account)
},
"children":[]
})];
let mut commands = Vec::new();
match snapshot {
None => {
children.extend([
json!({
"id":"world.create.title",
"kind":"control.input.text",
"props":{"label":"World title","placeholder":"A name for this world"},
"stateBindings":[local_draft("title", "string")],
"children":[]
}),
json!({
"id":"world.create.subject",
"kind":"control.input.text",
"props":{"label":"Your name","placeholder":"The first person in the world"},
"stateBindings":[local_draft("subject_label", "string")],
"children":[]
}),
json!({
"id":"world.create.narrative_persona",
"kind":"control.input.text",
"props":{"label":"Narrative persona (optional)","placeholder":"A person who lives the story in prose"},
"stateBindings":[local_draft("narrative_persona_label", "string")],
"children":[]
}),
json!({
"id":"world.create.operational_agent",
"kind":"control.input.text",
"props":{"label":"Operational agent (optional)","placeholder":"An institution or operator-shaped mind"},
"stateBindings":[local_draft("operational_agent_label", "string")],
"children":[]
}),
command_button(
"world.create",
"Create world",
"world.create",
json!({}),
&[
"title",
"subject_label",
"narrative_persona_label",
"operational_agent_label",
],
),
]);
commands.push(command_descriptor(
"world.create",
"ghostlight.world_create.v1",
&[
"title",
"subject_label",
"narrative_persona_label",
"operational_agent_label",
],
"WorldMailbox",
));
}
Some(world) => {
children.push(json!({
"id":"world.summary",
"kind":"card",
"props":{"title":world.title,"subtitle":format!("{:?} · revision {}", world.phase, world.revision)},
"children":[{
"id":"world.summary.body",
"kind":"text",
"props":{"value":format!("{} subject(s), {} committed event(s)", world.subjects.len(), world.events.len())},
"children":[]
}]
}));
match world.phase {
WorldPhase::Draft => {
if world
.required_approvers
.contains(&crate::world::PrincipalId::new(account))
&& !world
.draft_approvals
.contains(&crate::world::PrincipalId::new(account))
{
children.push(command_button(
"world.approve",
"Approve draft",
"world.approve",
json!({}),
&[],
));
commands.push(command_descriptor(
"world.approve",
"ghostlight.world_approve.v0",
&[],
"WorldMailbox",
));
}
if world.owner == crate::world::PrincipalId::new(account)
&& world.draft_approvals == world.required_approvers
{
children.push(command_button(
"world.activate",
"Activate world",
"world.activate",
json!({}),
&[],
));
commands.push(command_descriptor(
"world.activate",
"ghostlight.world_activate.v0",
&[],
"WorldMailbox",
));
}
}
WorldPhase::Active => {
let story = world
.events
.iter()
.map(|event| match &event.invocation.action {
DecisionAction::Speak { text } => json!({
"id":format!("world.event.{}", event.revision),
"kind":"text",
"props":{"value":text},
"children":[]
}),
})
.collect::<Vec<_>>();
children.push(json!({
"id":"world.story",
"kind":"card",
"props":{"title":"Story"},
"children":story
}));
let principal = crate::world::PrincipalId::new(account);
let opportunity = world.opportunities.iter().find_map(|opportunity| {
world.subjects.iter().find_map(|subject| {
let affordance_id = subject.affordances.get(&AffordanceKind::Speak)?;
(subject.id == opportunity.scope.subject_id
&& subject.human_controller.as_ref() == Some(&principal)
&& opportunity.affordance_ids.contains(affordance_id))
.then_some((opportunity, affordance_id))
})
});
if let Some((opportunity, affordance_id)) = opportunity {
children.extend([
json!({
"id":"world.speak.text",
"kind":"control.input.textarea",
"props":{"label":"Say something","rows":3,"placeholder":"Your exact words"},
"stateBindings":[local_draft("text", "string")],
"children":[]
}),
command_button(
"world.speak",
"Speak",
"world.speak",
json!({"opportunity":opportunity,"affordance_id":affordance_id}),
&["text"],
),
]);
commands.push(command_descriptor(
"world.speak",
"ghostlight.world_speak.v0",
&["text", "opportunity", "affordance_id"],
"WorldMailbox",
));
}
if world.owner == crate::world::PrincipalId::new(account) {
let mut has_controller_command = false;
for (index, opportunity) in world
.opportunities
.iter()
.filter(|opportunity| {
opportunity.controller_mode != ControllerMode::Human
})
.enumerate()
{
let Some(subject) = world
.subjects
.iter()
.find(|subject| subject.id == opportunity.scope.subject_id)
else {
continue;
};
has_controller_command = true;
children.push(command_button(
&format!("world.controller.act.{index}"),
&format!("Let {} act", subject.label),
"world.controller.act",
json!({"opportunity":opportunity}),
&[],
));
}
if has_controller_command {
commands.push(command_descriptor(
"world.controller.act",
"ghostlight.world_controller_act.v0",
&["opportunity"],
"ControllerRunner → WorldMailbox",
));
}
}
}
}
}
}
children.push(command_button(
"app.auth.logout",
"Sign out",
"app.auth.logout",
json!({}),
&[],
));
commands.push(command_descriptor(
"app.auth.logout",
"ghostlight.app_logout.v2",
&[],
"AppSessionOwner",
));
Ok(surface_document(
version,
snapshot
.map(|world| world.title.as_str())
.unwrap_or("Ghostlight Dungeon"),
children,
commands,
))
}
pub(crate) fn validate_invocation(
invocation: &EveCommandInvocation,
expected_transport: &str,
) -> anyhow::Result<()> {
if invocation.schema != "gamecult.eve.command_invocation.v1"
|| invocation.provider_id != PROVIDER_ID
|| invocation.surface_id != SURFACE_ID
|| invocation.command_boundary != COMMAND_BOUNDARY
|| invocation.receipt_schema != COMMAND_RESULT_SCHEMA
{
bail!("invocation does not match the Ghostlight Eve boundary");
}
if invocation.operation.operation_id.trim().is_empty()
|| invocation
.operation
.idempotency_key
.as_deref()
.is_none_or(str::is_empty)
|| invocation
.operation
.schema_id
.as_deref()
.is_none_or(str::is_empty)
|| invocation.client_id.trim().is_empty()
|| invocation.issued_at.parse::<DateTime<Utc>>().is_err()
|| invocation.operation.route_hint.transport.as_deref() != Some(expected_transport)
{
bail!("invocation metadata is incomplete");
}
let expected = operation_schema(&invocation.operation.operation_id)
.context("Eve operation is not advertised by Ghostlight")?;
if invocation.operation.schema_id.as_deref() != Some(expected) {
bail!("operation payload schema does not match its command descriptor");
}
if invocation.payload.get("caller").is_some()
|| invocation.payload.get("caller_id").is_some()
|| invocation.payload.get("callerId").is_some()
{
bail!("payload may not supply caller authority");
}
Ok(())
}
pub(crate) fn operation_schema(operation: &str) -> Option<&'static str> {
Some(match operation {
"heimdall.auth.begin" => "heimdall.auth_begin_command.v1",
"heimdall.auth.complete" => "heimdall.auth_complete_command.v1",
"app.auth.logout" => "ghostlight.app_logout.v2",
"world.create" => "ghostlight.world_create.v1",
"world.approve" => "ghostlight.world_approve.v0",
"world.activate" => "ghostlight.world_activate.v0",
"world.speak" => "ghostlight.world_speak.v0",
"world.controller.act" => "ghostlight.world_controller_act.v0",
_ => return None,
})
}
pub(crate) fn command_result(
invocation: &EveCommandInvocation,
state: &str,
message: impl Into<String>,
source_version: Option<u64>,
plugin_payload: Option<Value>,
receipt: Option<Value>,
) -> Value {
json!({
"schema":COMMAND_RESULT_SCHEMA,
"providerId":PROVIDER_ID,
"surfaceId":SURFACE_ID,
"operationId":invocation.operation.operation_id,
"idempotencyKey":invocation.operation.idempotency_key,
"state":state,
"message":message.into(),
"sourceVersion":source_version,
"pluginPayload":plugin_payload,
"receipt":receipt,
"updatedAtUtc":Utc::now().to_rfc3339()
})
}
fn surface_document(
version: u64,
title: &str,
children: Vec<Value>,
commands: Vec<Value>,
) -> Value {
json!({
"type":"surface-state",
"schema":"gamecult.eve.surface.v1",
"providerId":PROVIDER_ID,
"providerKind":"narrative.simulation",
"title":title,
"version":version,
"updatedAtUtc":Utc::now().to_rfc3339(),
"surface":{
"id":SURFACE_ID,
"root":{"id":"ghostlight.root","kind":"surface","props":{},"children":children},
"styles":{"tokens":{
"colorBackground":"#0c1110",
"colorPanel":"#17201d",
"colorText":"#e8e1cf",
"colorMuted":"#9aa69f",
"colorAccent":"#d49b58"
}}
},
"commands":commands
})
}
fn command_button(id: &str, label: &str, command: &str, action: Value, bindings: &[&str]) -> Value {
let mut action = action.as_object().cloned().unwrap_or_default();
action.insert("command".into(), Value::String(command.into()));
json!({
"id":id,
"kind":"control.button",
"props":{"label":label,"command":command,"action":action,"captureBindings":bindings},
"children":[]
})
}
fn command_descriptor(command: &str, schema: &str, bindings: &[&str], authority: &str) -> Value {
json!({
"schema":"gamecult.eve.command.v1",
"command":command,
"payloadSchema":schema,
"captureBindings":bindings,
"transport":"https-json",
"authority":authority
})
}
fn local_draft(key: &str, value_type: &str) -> Value {
json!({"scope":"local-draft","key":key,"type":value_type})
}
fn short_principal(principal: &str) -> String {
principal.chars().take(20).collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn invocation(operation: &str, schema: &str, payload: Value) -> EveCommandInvocation {
EveCommandInvocation {
schema: "gamecult.eve.command_invocation.v1".into(),
provider_id: PROVIDER_ID.into(),
surface_id: SURFACE_ID.into(),
operation: EveOperation {
operation_id: operation.into(),
schema_id: Some(schema.into()),
idempotency_key: Some(uuid::Uuid::new_v4().to_string()),
route_hint: EveRouteHint {
source_version: Some(0),
transport: Some("https-json".into()),
},
},
payload,
issued_at: Utc::now().to_rfc3339(),
client_id: "fixture".into(),
command_boundary: COMMAND_BOUNDARY.into(),
receipt_schema: COMMAND_RESULT_SCHEMA.into(),
}
}
#[test]
fn anonymous_surface_advertises_only_authentication() {
let surface = anonymous_surface();
let commands = surface["commands"].as_array().unwrap();
assert_eq!(commands.len(), 1);
assert_eq!(commands[0]["command"], "heimdall.auth.begin");
assert_eq!(surface["version"], 0);
}
#[test]
fn empty_authenticated_surface_has_create_without_session_zero() {
let surface = authenticated_surface("sha256:owner", None).unwrap();
let encoded = serde_json::to_string(&surface).unwrap();
assert!(encoded.contains("world.create"));
assert!(encoded.contains("narrative_persona_label"));
assert!(encoded.contains("operational_agent_label"));
assert!(!encoded.contains("session_zero"));
assert!(!encoded.contains("campaign"));
assert_eq!(surface["version"], 0);
}
#[test]
fn payload_cannot_claim_authority() {
let forged = invocation(
"world.speak",
"ghostlight.world_speak.v0",
json!({"text":"hello","caller":"owner"}),
);
assert!(validate_invocation(&forged, "https-json").is_err());
let bound = invocation(
"world.speak",
"ghostlight.world_speak.v0",
json!({"text":"hello","opportunity":{},"affordance_id":"bound"}),
);
assert!(validate_invocation(&bound, "https-json").is_ok());
}
#[test]
fn invocation_metadata_rejects_legacy_authority_extensions() {
let exact = invocation(
"world.speak",
"ghostlight.world_speak.v0",
json!({"text":"hello","opportunity":{},"affordance_id":"bound"}),
);
let mut outer = serde_json::to_value(&exact).unwrap();
outer["callerId"] = json!("legacy-owner");
assert!(serde_json::from_value::<EveCommandInvocation>(outer).is_err());
let mut route = serde_json::to_value(&exact).unwrap();
route["operation"]["routeHint"]["caller"] = json!("legacy-owner");
assert!(serde_json::from_value::<EveCommandInvocation>(route).is_err());
}
#[test]
fn removed_operation_is_unknown() {
assert!(operation_schema("session_zero.begin").is_none());
assert!(operation_schema("world.assess").is_none());
assert!(operation_schema("governance.time.propose").is_none());
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,937 +0,0 @@
use crate::{
domain::{Campaign, GestaltPresencePlan, GestaltPromotion},
model::{ModelPort, ModelStageReceipt, ModelStageRequest, run_validated_stage},
};
use anyhow::{Result, anyhow};
use schemars::schema_for;
use std::{collections::BTreeSet, sync::Arc};
#[derive(Clone)]
pub struct GestaltPresencePlanner {
pub model: Arc<dyn ModelPort>,
pub model_name: String,
}
impl GestaltPresencePlanner {
pub async fn plan(
&self,
campaign: &Campaign,
event_summary: &str,
) -> Result<(GestaltPresencePlan, Vec<ModelStageReceipt>)> {
let player_location = &campaign.actors[&campaign.player_actor_id].location_id;
let nearby_gestalts = campaign
.gestalts
.values()
.filter(|gestalt| {
crate::resolution::validate_active_gestalt_presence_location(
campaign,
&gestalt.id,
player_location,
)
.is_ok()
})
.collect::<Vec<_>>();
let nearby_gestalt_ids = nearby_gestalts
.iter()
.map(|gestalt| gestalt.id.clone())
.collect::<BTreeSet<_>>();
let player = &campaign.actors[&campaign.player_actor_id];
let nearby_dormant_members = campaign
.gestalt_members
.values()
.filter(|member| {
nearby_gestalt_ids.contains(&member.gestalt_id)
&& crate::resolution::dormant_member_location(campaign, &member.id)
.is_ok_and(|location| location == *player_location)
})
.map(|member| {
serde_json::json!({
"member": member,
"player_relationship_to_member": player
.relationships
.get(&crate::domain::gestalt_member_subject_id(&member.id)),
})
})
.collect::<Vec<_>>();
let nearby_dormant_member_ids = campaign
.gestalt_members
.values()
.filter(|member| {
nearby_gestalt_ids.contains(&member.gestalt_id)
&& crate::resolution::dormant_member_location(campaign, &member.id)
.is_ok_and(|location| location == *player_location)
})
.map(|member| member.id.clone())
.collect::<BTreeSet<_>>();
let materialized_members = campaign
.gestalt_members
.values()
.filter_map(|member| {
let actor_id = member.materialized_actor_id.as_ref()?;
let actor = campaign.actors.get(actor_id)?;
Some(serde_json::json!({
"gestalt_id":member.gestalt_id,
"member_id":member.id,
"member_name":member.name,
"member_version":member.version,
"actor_id":actor_id,
"actor_name":actor.name,
"actor_location_id":actor.location_id,
"conditions":actor.conditions,
"goals":actor.goals,
"obligations":actor.obligations,
"recent_memories":actor.memories.iter().rev().take(8).collect::<Vec<_>>(),
"player_relationship_to_member":player.relationships.get(actor_id),
"member_relationship_to_player":actor.relationships.get(&player.id),
"relevance_lease_until_revision":member.relevance_lease_until_revision,
}))
})
.collect::<Vec<_>>();
let materialized_actor_ids = campaign
.gestalt_members
.values()
.filter_map(|member| member.materialized_actor_id.clone())
.collect::<BTreeSet<_>>();
let admitted_individuation_stimulus = automatic_individuation_stimulus(campaign);
let individuation_admitted = admitted_individuation_stimulus
.as_deref()
.is_some_and(|stimulus| stimulus == event_summary);
let candidates = serde_json::json!({
"player_location_id": player_location,
"addressed_existing_actor_ids": automatic_individuation_addressed_actor_ids(campaign),
"nearby_active_leaf_gestalts": nearby_gestalts,
"nearby_dormant_members": nearby_dormant_members,
"materialized_members": materialized_members,
});
let mut schema = serde_json::to_value(schema_for!(GestaltPresencePlan))?;
constrain_presence_schema(
&mut schema,
&nearby_gestalt_ids,
&nearby_dormant_member_ids,
&materialized_actor_ids,
player_location,
individuation_admitted,
)?;
let individuation_instruction = if individuation_admitted {
"The immediately committed event is direct player speech. If that speech makes one anonymous population member individually relevant and no supplied member fits, you may individuate exactly one durable member delta from the gestalt baseline. Give that person a stable personal self-identifier suitable to the setting, never a role, condition, manifest category, or descriptive placeholder. Use a new stable lowercase id, version 0, the exact gestalt id/version, no materialized actor id, and record only personal departures from the shared baseline."
} else {
"The immediately committed event does not admit a new canonical person. The individuations array must be empty. Cast only supplied existing members."
};
let base_prompt = format!(
"Cast reversible Persona population presence for the next scene after this event. The purpose is to make causal continuity visible without crowding the scene or inventing coincidence. Every materialized_members entry is an already-individualized canonical person, including their stable public identity and current actor state. Never individuate another instance, substitute, or namesake for a supplied materialized person; addressed_existing_actor_ids already satisfy the exact direct addresses resolved before this stage. Promote an existing dormant member when their exact durable history makes them individually relevant. When a nearby dormant member has a reciprocal player relationship and an unresolved callback signal such as an obligation, memory, or goal, promote the single strongest earned callback unless the event makes their presence implausible or dramatically harmful. An ordinary shared-location event is enough opportunity for an earned callback; do not require the player to ask for that person. Prefer an existing person over anonymous individuation whenever their exact delta supports the scene. Return no promotion when there is no earned callback or the current event conflicts with it. {individuation_instruction} Demote a materialized member when they are no longer scene-relevant. Select exact supplied member, actor, and gestalt IDs. Ghostlight binds versions and occupancy from the canonical snapshot after selection; those metadata fields are not your decision. Aggregate deltas must remain empty; population learning requires separate review. Emit the exact JSON schema.\nSCHEMA:\n{}\nCANDIDATES:\n{}\nEVENT:\n{}",
serde_json::to_string_pretty(&schema)?,
candidates,
event_summary
);
let snapshot_binding = format!("campaign:{}:revision:{}", campaign.id, campaign.revision);
let mut correction = String::new();
let mut receipts = Vec::new();
loop {
let mut output = run_validated_stage(
self.model.as_ref(),
&ModelStageRequest {
stage: "gestalt_presence_planner".into(),
model: self.model_name.clone(),
snapshot_binding: snapshot_binding.clone(),
lived_stream: format!("{base_prompt}{correction}"),
output_schema: Some(schema.clone()),
source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(),
temperature: Some(0.0),
max_output_tokens: Some(1_500),
},
)
.await?;
let candidate = output
.structured
.clone()
.ok_or_else(|| anyhow!("presence planner produced no plan"))
.and_then(|value| serde_json::from_value(value).map_err(Into::into))
.and_then(|mut plan| {
bind_presence_authority(campaign, &mut plan, player_location)?;
validate_plan(campaign, &plan, player_location, event_summary)?;
Ok(plan)
});
match candidate {
Ok(plan) => {
receipts.push(output.receipt);
return Ok((plan, receipts));
}
Err(error) if receipts.is_empty() => {
output.receipt.validation_result = "semantic_invalid".into();
output.receipt.local_validation_error =
Some(error.to_string().chars().take(1_000).collect());
let rejected = output
.structured
.as_ref()
.and_then(|value| serde_json::to_string(value).ok())
.unwrap_or_else(|| "unavailable".into());
receipts.push(output.receipt);
correction = format!(
"\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS PRESENCE PLAN: {error}\nPREVIOUS PLAN:\n{rejected}\nReturn one corrected complete plan against the same snapshot. Promote only exact nearby_dormant_members and demote only exact materialized_members. Ghostlight binds canonical versions and occupancy after your semantic selection."
);
}
Err(error) => {
return Err(anyhow!(
"presence planner failed semantic validation after one correction: {error}"
));
}
}
}
}
}
/// Bind revision, ownership, and occupancy fields from canonical state after
/// the model has selected semantic presence changes. Those fields are kernel
/// authority, not facts a Persona stage is expected to copy correctly.
fn bind_presence_authority(
campaign: &Campaign,
plan: &mut GestaltPresencePlan,
player_location: &str,
) -> Result<()> {
for promotion in &mut plan.promotions {
let member = campaign
.gestalt_members
.get(&promotion.member_id)
.ok_or_else(|| anyhow!("presence plan invented a member"))?;
let gestalt = campaign
.gestalts
.get(&member.gestalt_id)
.ok_or_else(|| anyhow!("presence member belongs to an unknown gestalt"))?;
promotion.gestalt_id = member.gestalt_id.clone();
promotion.expected_gestalt_version = gestalt.version;
promotion.expected_member_version = member.version;
promotion.location_id =
crate::resolution::dormant_member_location(campaign, &promotion.member_id)?;
}
for individuation in &mut plan.individuations {
let gestalt = campaign
.gestalts
.get(&individuation.gestalt_id)
.ok_or_else(|| anyhow!("presence plan invented a gestalt"))?;
individuation.expected_gestalt_version = gestalt.version;
individuation.location_id = player_location.to_owned();
individuation.member.schema = "ghostlight.gestalt_member_delta.v1".into();
individuation.member.gestalt_id = individuation.gestalt_id.clone();
individuation.member.version = 0;
individuation.member.last_location_id = Some(player_location.to_owned());
individuation.member.materialized_actor_id = None;
individuation.member.last_relevant_revision = 0;
individuation.member.relevance_lease_until_revision = 0;
}
Ok(())
}
/// A player addressing a known nearby folded person is itself sufficient
/// foreground relevance. Materializing that exact person is deterministic;
/// the optional presence model does not get a veto.
pub fn required_addressed_promotions(campaign: &Campaign) -> Result<GestaltPresencePlan> {
let Some(turn) = campaign.transcript.last().filter(|turn| {
turn.revision == campaign.revision && turn.speaker == campaign.player_actor_id
}) else {
return Ok(GestaltPresencePlan::default());
};
let mut promotions = Vec::new();
for subject_id in &turn.persona_response_actor_ids {
if campaign.actors.contains_key(subject_id) || campaign.gestalts.contains_key(subject_id) {
continue;
}
let member_id = crate::resolution::dormant_member_id_for_subject(campaign, subject_id)
.ok_or_else(|| anyhow!("addressed Persona subject is neither present nor folded"))?;
let member = &campaign.gestalt_members[member_id];
let gestalt = campaign
.gestalts
.get(&member.gestalt_id)
.ok_or_else(|| anyhow!("addressed member belongs to an unknown gestalt"))?;
promotions.push(GestaltPromotion {
gestalt_id: member.gestalt_id.clone(),
expected_gestalt_version: gestalt.version,
member_id: member.id.clone(),
expected_member_version: member.version,
location_id: crate::resolution::dormant_member_location(campaign, member_id)?,
});
}
Ok(GestaltPresencePlan {
individuations: Vec::new(),
promotions,
demotions: Vec::new(),
})
}
fn constrain_presence_schema(
schema: &mut serde_json::Value,
nearby_gestalt_ids: &BTreeSet<String>,
dormant_member_ids: &BTreeSet<String>,
materialized_actor_ids: &BTreeSet<String>,
player_location: &str,
individuation_admitted: bool,
) -> Result<()> {
constrain_candidate_array(
schema,
"promotions",
"GestaltPromotion",
"member_id",
dormant_member_ids,
)?;
constrain_candidate_array(
schema,
"demotions",
"GestaltDemotion",
"actor_id",
materialized_actor_ids,
)?;
constrain_candidate_array(
schema,
"individuations",
"GestaltIndividuation",
"gestalt_id",
nearby_gestalt_ids,
)?;
schema["properties"]["individuations"]["maxItems"] = serde_json::json!(
if individuation_admitted && !nearby_gestalt_ids.is_empty() {
1
} else {
0
}
);
for definition in ["GestaltPromotion", "GestaltIndividuation"] {
if !nearby_gestalt_ids.is_empty() {
schema["$defs"][definition]["properties"]["gestalt_id"] =
serde_json::json!({"type":"string","enum":nearby_gestalt_ids});
}
schema["$defs"][definition]["properties"]["location_id"] =
serde_json::json!({"type":"string","enum":[player_location]});
}
if !nearby_gestalt_ids.is_empty() {
schema["$defs"]["GestaltMemberDelta"]["properties"]["gestalt_id"] =
serde_json::json!({"type":"string","enum":nearby_gestalt_ids});
}
Ok(())
}
fn constrain_candidate_array(
schema: &mut serde_json::Value,
field: &str,
definition: &str,
id_field: &str,
allowed_ids: &BTreeSet<String>,
) -> Result<()> {
let array = schema
.pointer_mut(&format!("/properties/{field}"))
.and_then(serde_json::Value::as_object_mut)
.ok_or_else(|| anyhow!("presence schema omitted {field}"))?;
if allowed_ids.is_empty() {
array.insert("maxItems".into(), serde_json::json!(0));
} else {
array.insert("maxItems".into(), serde_json::json!(allowed_ids.len()));
schema["$defs"][definition]["properties"][id_field] =
serde_json::json!({"type":"string","enum":allowed_ids});
}
Ok(())
}
fn validate_plan(
campaign: &Campaign,
plan: &GestaltPresencePlan,
player_location: &str,
event_summary: &str,
) -> Result<()> {
let individuation_admitted = automatic_individuation_stimulus(campaign)
.as_deref()
.is_some_and(|stimulus| stimulus == event_summary);
if plan.individuations.len() > usize::from(individuation_admitted) {
return Err(anyhow!(
"automatic individuation requires the exact immediately committed player speech and admits at most one person"
));
}
let mut members = BTreeSet::new();
let active_local_gestalt_ids = campaign
.gestalts
.values()
.filter(|gestalt| {
crate::resolution::validate_active_gestalt_presence_location(
campaign,
&gestalt.id,
player_location,
)
.is_ok()
})
.map(|gestalt| gestalt.id.as_str())
.collect::<BTreeSet<_>>();
let established_public_identities = campaign
.actors
.values()
.filter(|actor| actor.location_id == player_location)
.map(|actor| normalized_public_identity(&actor.name))
.chain(
campaign
.gestalt_members
.values()
.filter(|member| active_local_gestalt_ids.contains(member.gestalt_id.as_str()))
.map(|member| normalized_public_identity(&member.name)),
)
.collect::<BTreeSet<_>>();
for individuation in &plan.individuations {
let member = &individuation.member;
let gestalt = campaign
.gestalts
.get(&individuation.gestalt_id)
.ok_or_else(|| anyhow!("presence plan invented a gestalt"))?;
crate::resolution::validate_active_gestalt_presence_location(
campaign,
&individuation.gestalt_id,
player_location,
)?;
if individuation.expected_gestalt_version != gestalt.version
|| individuation.location_id != player_location
|| member.gestalt_id != individuation.gestalt_id
|| member.version != 0
|| member.materialized_actor_id.is_some()
|| member.id.trim().is_empty()
|| member.name.trim().is_empty()
|| campaign.gestalt_members.contains_key(&member.id)
|| !members.insert(member.id.clone())
{
return Err(anyhow!(
"presence individuation does not match its snapshot"
));
}
if established_public_identities.contains(&normalized_public_identity(&member.name)) {
return Err(anyhow!(
"presence individuation duplicates an established local or population identity"
));
}
}
for promotion in &plan.promotions {
if !members.insert(promotion.member_id.clone()) {
return Err(anyhow!("presence plan promotes one member twice"));
}
let member = campaign
.gestalt_members
.get(&promotion.member_id)
.ok_or_else(|| anyhow!("presence plan invented a member"))?;
let gestalt = campaign
.gestalts
.get(&promotion.gestalt_id)
.ok_or_else(|| anyhow!("presence plan invented a gestalt"))?;
let member_location = crate::resolution::dormant_member_location(campaign, &member.id)?;
if member.gestalt_id != promotion.gestalt_id
|| member.version != promotion.expected_member_version
|| gestalt.version != promotion.expected_gestalt_version
|| member.materialized_actor_id.is_some()
|| promotion.location_id != player_location
|| member_location != promotion.location_id
{
return Err(anyhow!("presence promotion does not match its snapshot"));
}
}
let materialized: BTreeSet<_> = campaign
.gestalt_members
.values()
.filter_map(|member| member.materialized_actor_id.clone())
.collect();
let mut actors = BTreeSet::new();
for demotion in &plan.demotions {
if !actors.insert(demotion.actor_id.clone()) || !materialized.contains(&demotion.actor_id) {
return Err(anyhow!(
"presence plan demotes an unknown or duplicate member"
));
}
let member = campaign
.gestalt_members
.values()
.find(|member| {
member.materialized_actor_id.as_deref() == Some(demotion.actor_id.as_str())
})
.expect("materialized member was validated");
let actor = &campaign.actors[&demotion.actor_id];
if actor.location_id == player_location
|| member.relevance_lease_until_revision > campaign.revision
{
return Err(anyhow!(
"presence plan demotes a visible or recently relevant member"
));
}
}
Ok(())
}
fn normalized_public_identity(value: &str) -> String {
value.trim().to_lowercase()
}
pub(crate) fn automatic_individuation_addressed_actor_ids(campaign: &Campaign) -> BTreeSet<String> {
campaign
.transcript
.last()
.filter(|turn| {
turn.revision == campaign.revision && turn.speaker == campaign.player_actor_id
})
.map(|turn| turn.persona_response_actor_ids.clone())
.unwrap_or_default()
}
pub(crate) fn automatic_individuation_stimulus(campaign: &Campaign) -> Option<String> {
let turn = campaign.transcript.last()?;
(turn.revision == campaign.revision && turn.speaker == campaign.player_actor_id)
.then(|| format!("{} says: {}", turn.speaker, turn.text.trim()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
domain::{ActorState, GestaltMemberDelta, GestaltPersonaState, Location, NarrativeTurn},
model::ModelStageRequest,
};
use async_trait::async_trait;
use std::{
collections::{BTreeMap, BTreeSet},
sync::{
Mutex,
atomic::{AtomicUsize, Ordering},
},
};
struct CapturePresenceModel {
prompt: Arc<Mutex<String>>,
}
struct CorrectingPresenceModel {
calls: AtomicUsize,
}
#[async_trait]
impl ModelPort for CapturePresenceModel {
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
*self.prompt.lock().unwrap() = request.lived_stream.clone();
Ok(serde_json::json!({
"individuations":[],
"promotions":[],
"demotions":[]
})
.to_string())
}
fn provider(&self) -> &'static str {
"presence-capture"
}
}
#[async_trait]
impl ModelPort for CorrectingPresenceModel {
async fn run(&self, _request: &ModelStageRequest) -> Result<String> {
self.calls.fetch_add(1, Ordering::SeqCst);
Ok(serde_json::json!({
"individuations":[],
"promotions":[{
"gestalt_id":"nearby-leaf",
"expected_gestalt_version":98,
"member_id":"mira",
"expected_member_version":99,
"location_id":"center"
}],
"demotions":[]
})
.to_string())
}
fn provider(&self) -> &'static str {
"presence-correction"
}
}
#[test]
fn presence_schema_binds_each_transition_to_exact_candidate_ids() {
let mut schema = serde_json::to_value(schema_for!(GestaltPresencePlan)).unwrap();
constrain_presence_schema(
&mut schema,
&BTreeSet::from(["nearby-leaf".into()]),
&BTreeSet::from(["mira".into()]),
&BTreeSet::from(["member:already-here".into()]),
"center",
true,
)
.unwrap();
assert_eq!(
schema["$defs"]["GestaltPromotion"]["properties"]["member_id"]["enum"],
serde_json::json!(["mira"])
);
assert_eq!(
schema["$defs"]["GestaltDemotion"]["properties"]["actor_id"]["enum"],
serde_json::json!(["member:already-here"])
);
assert_eq!(
schema["$defs"]["GestaltIndividuation"]["properties"]["gestalt_id"]["enum"],
serde_json::json!(["nearby-leaf"])
);
assert_eq!(
schema["$defs"]["GestaltPromotion"]["properties"]["location_id"]["enum"],
serde_json::json!(["center"])
);
}
#[test]
fn presence_schema_makes_empty_candidate_lanes_structurally_empty() {
let mut schema = serde_json::to_value(schema_for!(GestaltPresencePlan)).unwrap();
constrain_presence_schema(
&mut schema,
&BTreeSet::new(),
&BTreeSet::new(),
&BTreeSet::new(),
"center",
false,
)
.unwrap();
for field in ["promotions", "demotions", "individuations"] {
assert_eq!(schema["properties"][field]["maxItems"], 0);
}
jsonschema::validator_for(&schema).unwrap();
}
#[test]
fn only_exact_immediately_committed_player_speech_admits_individuation() {
let mut campaign = crate::resolution::tests::campaign(0, 8);
campaign.revision = 7;
campaign.transcript.push(NarrativeTurn {
revision: 7,
at: chrono::Utc::now(),
speaker: campaign.player_actor_id.clone(),
text: "I ask the unnamed porter for their name.".into(),
persona_response_actor_ids: BTreeSet::new(),
});
let exact = format!(
"{} says: I ask the unnamed porter for their name.",
campaign.player_actor_id
);
assert_eq!(
automatic_individuation_stimulus(&campaign).as_deref(),
Some(exact.as_str())
);
campaign.transcript.push(NarrativeTurn {
revision: 8,
at: chrono::Utc::now(),
speaker: "world".into(),
text: "They agree to help.".into(),
persona_response_actor_ids: BTreeSet::new(),
});
campaign.revision = 8;
assert!(automatic_individuation_stimulus(&campaign).is_none());
}
#[test]
fn individuation_cannot_duplicate_an_established_population_identity() {
let mut campaign = crate::resolution::tests::campaign(0, 8);
campaign.revision = 7;
campaign.gestalts.insert(
"refugees".into(),
GestaltPersonaState {
schema: "ghostlight.gestalt_persona_state.v1".into(),
id: "refugees".into(),
name: "Refugees".into(),
version: 0,
home_location_id: "center".into(),
shared_capabilities: BTreeSet::new(),
shared_knowledge: BTreeSet::new(),
resources: BTreeSet::new(),
goals: vec![],
pressures: vec![],
},
);
campaign.gestalt_members.insert(
"oxygen_patient".into(),
GestaltMemberDelta {
schema: "ghostlight.gestalt_member_delta.v1".into(),
id: "oxygen_patient".into(),
gestalt_id: "refugees".into(),
version: 1,
name: "Taren".into(),
capability_additions: BTreeSet::new(),
capability_removals: BTreeSet::new(),
knowledge_additions: BTreeSet::new(),
knowledge_removals: BTreeSet::new(),
equipment: BTreeSet::new(),
conditions: BTreeSet::new(),
obligations: BTreeSet::new(),
relationships: BTreeMap::new(),
goals: vec![],
memories: vec![],
last_location_id: Some("center".into()),
materialized_actor_id: Some("member:oxygen_patient".into()),
last_relevant_revision: 7,
relevance_lease_until_revision: 9,
},
);
campaign.actors.insert(
"member:oxygen_patient".into(),
ActorState {
id: "member:oxygen_patient".into(),
name: "Taren".into(),
location_id: "center".into(),
capabilities: BTreeSet::new(),
knowledge: BTreeSet::new(),
equipment: BTreeSet::new(),
conditions: BTreeSet::new(),
obligations: BTreeSet::new(),
relationships: BTreeMap::new(),
goals: vec![],
memories: vec![],
},
);
campaign.transcript.push(NarrativeTurn {
revision: 7,
at: chrono::Utc::now(),
speaker: campaign.player_actor_id.clone(),
text: "Taren, tell me whether the regulator is holding.".into(),
persona_response_actor_ids: BTreeSet::new(),
});
crate::resolution::ensure_agency_profiles(&mut campaign);
let plan = GestaltPresencePlan {
individuations: vec![crate::domain::GestaltIndividuation {
gestalt_id: "refugees".into(),
expected_gestalt_version: 0,
member: GestaltMemberDelta {
schema: "ghostlight.gestalt_member_delta.v1".into(),
id: "second_taren".into(),
gestalt_id: "refugees".into(),
version: 0,
name: " tArEn ".into(),
capability_additions: BTreeSet::new(),
capability_removals: BTreeSet::new(),
knowledge_additions: BTreeSet::new(),
knowledge_removals: BTreeSet::new(),
equipment: BTreeSet::new(),
conditions: BTreeSet::new(),
obligations: BTreeSet::new(),
relationships: BTreeMap::new(),
goals: vec![],
memories: vec![],
last_location_id: Some("center".into()),
materialized_actor_id: None,
last_relevant_revision: 0,
relevance_lease_until_revision: 0,
},
location_id: "center".into(),
}],
promotions: vec![],
demotions: vec![],
};
let event = format!(
"{} says: Taren, tell me whether the regulator is holding.",
campaign.player_actor_id
);
assert!(
validate_plan(&campaign, &plan, "center", &event)
.unwrap_err()
.to_string()
.contains("established local or population identity")
);
}
#[tokio::test]
async fn presence_planner_binds_authority_fields_from_the_snapshot() {
let mut campaign = crate::resolution::tests::campaign(0, 8);
campaign.gestalts.insert(
"nearby-leaf".into(),
GestaltPersonaState {
schema: "ghostlight.gestalt_persona_state.v1".into(),
id: "nearby-leaf".into(),
name: "Nearby leaf".into(),
version: 0,
home_location_id: "center".into(),
shared_capabilities: BTreeSet::new(),
shared_knowledge: BTreeSet::new(),
resources: BTreeSet::new(),
goals: vec![],
pressures: vec![],
},
);
campaign.gestalt_members.insert(
"mira".into(),
GestaltMemberDelta {
schema: "ghostlight.gestalt_member_delta.v1".into(),
id: "mira".into(),
gestalt_id: "nearby-leaf".into(),
version: 0,
name: "Mira".into(),
capability_additions: BTreeSet::new(),
capability_removals: BTreeSet::new(),
knowledge_additions: BTreeSet::new(),
knowledge_removals: BTreeSet::new(),
equipment: BTreeSet::new(),
conditions: BTreeSet::new(),
obligations: BTreeSet::new(),
relationships: BTreeMap::new(),
goals: vec![],
memories: vec![],
last_location_id: Some("center".into()),
materialized_actor_id: None,
last_relevant_revision: 0,
relevance_lease_until_revision: 0,
},
);
crate::resolution::ensure_agency_profiles(&mut campaign);
let model = Arc::new(CorrectingPresenceModel {
calls: AtomicUsize::new(0),
});
let (plan, receipts) = GestaltPresencePlanner {
model: model.clone(),
model_name: "fixture".into(),
}
.plan(&campaign, "The player enters the square.")
.await
.unwrap();
assert_eq!(model.calls.load(Ordering::SeqCst), 1);
assert_eq!(receipts.len(), 1);
assert_eq!(
plan.promotions,
vec![GestaltPromotion {
gestalt_id: "nearby-leaf".into(),
expected_gestalt_version: 0,
member_id: "mira".into(),
expected_member_version: 0,
location_id: "center".into(),
}]
);
}
#[tokio::test]
async fn presence_projection_contains_only_nearby_active_leaves_and_relevant_members() {
let mut campaign = crate::resolution::tests::campaign(0, 8);
campaign.locations.insert(
"far".into(),
Location {
id: "far".into(),
name: "Far".into(),
container_id: None,
routes: BTreeMap::new(),
persistent_features: vec![],
},
);
let gestalt = |id: &str, name: &str, location: &str| GestaltPersonaState {
schema: "ghostlight.gestalt_persona_state.v1".into(),
id: id.into(),
name: name.into(),
version: 0,
home_location_id: location.into(),
shared_capabilities: BTreeSet::new(),
shared_knowledge: BTreeSet::new(),
resources: BTreeSet::new(),
goals: vec![],
pressures: vec![],
};
campaign.gestalts.insert(
"nearby-leaf".into(),
gestalt("nearby-leaf", "Nearby leaf", "center"),
);
campaign
.gestalts
.insert("far-leaf".into(), gestalt("far-leaf", "Far leaf", "far"));
campaign.gestalts.insert(
"inactive-parent".into(),
gestalt("inactive-parent", "Inactive parent", "center"),
);
let member = |id: &str, name: &str, gestalt_id: &str, location: &str| GestaltMemberDelta {
schema: "ghostlight.gestalt_member_delta.v1".into(),
id: id.into(),
gestalt_id: gestalt_id.into(),
version: 0,
name: name.into(),
capability_additions: BTreeSet::new(),
capability_removals: BTreeSet::new(),
knowledge_additions: BTreeSet::new(),
knowledge_removals: BTreeSet::new(),
equipment: BTreeSet::new(),
conditions: BTreeSet::new(),
obligations: BTreeSet::new(),
relationships: BTreeMap::new(),
goals: vec![],
memories: vec![],
last_location_id: Some(location.into()),
materialized_actor_id: None,
last_relevant_revision: 0,
relevance_lease_until_revision: 0,
};
campaign.gestalt_members.insert(
"mira".into(),
member("mira", "Mira Nearby", "nearby-leaf", "center"),
);
let player_id = campaign.player_actor_id.clone();
campaign
.actors
.get_mut(&player_id)
.unwrap()
.relationships
.insert("member:mira".into(), "helped her cross the flood".into());
campaign
.gestalt_members
.get_mut("mira")
.unwrap()
.relationships
.insert(player_id, "trusts them for helping".into());
campaign
.gestalt_members
.get_mut("mira")
.unwrap()
.obligations
.insert("thank the player if they meet again".into());
campaign.gestalt_members.insert(
"far-person".into(),
member("far-person", "Far Person", "far-leaf", "far"),
);
let mut taren = member("taren", "Taren", "nearby-leaf", "center");
taren.version = 3;
taren.materialized_actor_id = Some("member:taren".into());
taren.relevance_lease_until_revision = 12;
campaign.gestalt_members.insert("taren".into(), taren);
campaign.actors.insert(
"member:taren".into(),
ActorState {
id: "member:taren".into(),
name: "Taren".into(),
location_id: "center".into(),
capabilities: BTreeSet::new(),
knowledge: BTreeSet::new(),
equipment: BTreeSet::new(),
conditions: BTreeSet::from(["oxygen regulator holding for now".into()]),
obligations: BTreeSet::from(["remain with the convoy".into()]),
relationships: BTreeMap::new(),
goals: vec![],
memories: vec!["Ash repaired the regulator".into()],
},
);
crate::resolution::ensure_agency_profiles(&mut campaign);
let parent = campaign.agency_profiles.get_mut("inactive-parent").unwrap();
parent.active_leaf = false;
parent.simulation_eligible = false;
let prompt = Arc::new(Mutex::new(String::new()));
GestaltPresencePlanner {
model: Arc::new(CapturePresenceModel {
prompt: prompt.clone(),
}),
model_name: "fixture".into(),
}
.plan(&campaign, "The player works in the square.")
.await
.unwrap();
let prompt = prompt.lock().unwrap();
assert!(prompt.contains("Nearby leaf"));
assert!(prompt.contains("Mira Nearby"));
assert!(prompt.contains("helped her cross the flood"));
assert!(prompt.contains("thank the player if they meet again"));
assert!(prompt.contains("Taren"));
assert!(prompt.contains("oxygen regulator holding for now"));
assert!(prompt.contains("Ash repaired the regulator"));
assert!(prompt.contains("materialized person"));
assert!(prompt.contains("do not require the player to ask for that person"));
assert!(!prompt.contains("Far leaf"));
assert!(!prompt.contains("Far Person"));
assert!(!prompt.contains("Inactive parent"));
}
}

View file

@ -67,7 +67,7 @@ struct HeimdallCommandBoundaryCatalogEntry {
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct HeimdallCommandBoundaryRecord {
schema: String,
boundary_id: String,
@ -79,7 +79,7 @@ struct HeimdallCommandBoundaryRecord {
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct HeimdallBoundaryCommand {
operation: String,
request_schema: String,
@ -87,7 +87,7 @@ struct HeimdallBoundaryCommand {
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct HeimdallPrivateRoute {
endpoint: String,
exposure: String,
@ -100,7 +100,7 @@ cultmesh_rs::cultmesh_documents!(HeimdallDiscoveryDocuments {
});
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct PrivateEnvelope {
schema: String,
app_slug: String,
@ -149,7 +149,7 @@ struct DiscordRolePolicy<'a> {
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct AuthBeginReceipt {
pub status: String,
pub handle: String,
@ -158,14 +158,14 @@ pub struct AuthBeginReceipt {
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct AuthNavigation {
pub url: String,
pub allowed_origins: Vec<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct AuthCompletionReceipt {
pub status: String,
pub handle: Option<String>,
@ -180,12 +180,13 @@ pub struct AuthCompletionReceipt {
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AccountSummary {
pub id: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct HeimdallSession {
pub account_id: String,
pub session_id: String,
@ -195,13 +196,13 @@ pub struct HeimdallSession {
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct RefreshSummary {
pub expires_at: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct AuthLogoutReceipt {
pub status: String,
pub session_id: String,
@ -228,6 +229,83 @@ pub struct AppClaim {
pub slug: String,
}
/// Opaque session material admitted only after a signed Heimdall completion
/// and its response envelope agree exactly.
pub(crate) struct VerifiedSessionAdmission(VerifiedSessionMaterial);
/// Opaque refresh material admitted only after a signed Heimdall refresh and
/// its response envelope agree exactly.
pub(crate) struct VerifiedSessionRefresh(VerifiedSessionMaterial);
struct VerifiedSessionMaterial {
account_id: String,
heimdall_session_id: String,
access_revision: u64,
capabilities: Vec<String>,
access_expires_at: DateTime<Utc>,
refresh_expires_at: DateTime<Utc>,
refresh_claim: String,
}
macro_rules! verified_session_accessors {
($name:ident) => {
impl $name {
pub(crate) fn account_id(&self) -> &str {
&self.0.account_id
}
pub(crate) fn heimdall_session_id(&self) -> &str {
&self.0.heimdall_session_id
}
pub(crate) fn access_revision(&self) -> u64 {
self.0.access_revision
}
pub(crate) fn capabilities(&self) -> &[String] {
&self.0.capabilities
}
pub(crate) fn access_expires_at(&self) -> DateTime<Utc> {
self.0.access_expires_at.to_owned()
}
pub(crate) fn refresh_expires_at(&self) -> DateTime<Utc> {
self.0.refresh_expires_at.to_owned()
}
pub(crate) fn refresh_claim(&self) -> &str {
&self.0.refresh_claim
}
}
};
}
verified_session_accessors!(VerifiedSessionAdmission);
verified_session_accessors!(VerifiedSessionRefresh);
#[cfg(test)]
impl VerifiedSessionAdmission {
pub(crate) fn fixture(
account_id: impl Into<String>,
heimdall_session_id: impl Into<String>,
access_revision: u64,
access_expires_at: DateTime<Utc>,
refresh_expires_at: DateTime<Utc>,
refresh_claim: impl Into<String>,
) -> Self {
Self(VerifiedSessionMaterial {
account_id: account_id.into(),
heimdall_session_id: heimdall_session_id.into(),
access_revision,
capabilities: vec!["app_access".into()],
access_expires_at,
refresh_expires_at,
refresh_claim: refresh_claim.into(),
})
}
}
impl HeimdallClient {
pub fn from_env() -> anyhow::Result<Self> {
let odin_endpoint: SocketAddr = required_env("GHOSTLIGHT_ODIN_RUDP")?
@ -364,8 +442,8 @@ impl HeimdallClient {
pub async fn verify_completion(
&self,
completion: &AuthCompletionReceipt,
) -> anyhow::Result<AccessClaims> {
completion: AuthCompletionReceipt,
) -> anyhow::Result<VerifiedSessionAdmission> {
if completion.status != "authenticated" {
bail!("Heimdall completion is not authenticated");
}
@ -374,14 +452,16 @@ impl HeimdallClient {
.as_deref()
.context("Heimdall omitted the access token")?;
let claims = self.verify_access(token).await?;
verify_claim_binding(completion, &claims, true)?;
Ok(claims)
verify_claim_binding(&completion, &claims, true)?;
Ok(VerifiedSessionAdmission(verified_session_material(
completion, claims,
)?))
}
pub async fn verify_refresh(
&self,
completion: &AuthCompletionReceipt,
) -> anyhow::Result<AccessClaims> {
completion: AuthCompletionReceipt,
) -> anyhow::Result<VerifiedSessionRefresh> {
if completion.status != "authenticated" {
bail!("Heimdall refresh is not authenticated");
}
@ -390,8 +470,10 @@ impl HeimdallClient {
.as_deref()
.context("Heimdall refresh omitted the access token")?;
let claims = self.verify_access(token).await?;
verify_claim_binding(completion, &claims, false)?;
Ok(claims)
verify_claim_binding(&completion, &claims, false)?;
Ok(VerifiedSessionRefresh(verified_session_material(
completion, claims,
)?))
}
async fn verify_access(&self, token: &str) -> anyhow::Result<AccessClaims> {
@ -483,13 +565,29 @@ impl HeimdallClient {
bail!("Heimdall returned the wrong private response contract");
}
let sealed: PrivateEnvelope = rmp_serde::from_slice(&STANDARD.decode(payload)?)?;
if sealed.operation != operation || sealed.content_schema != expected_schema {
bail!("Heimdall private response disagrees with the requested operation");
}
validate_private_response_binding(&sealed, &operation, expected_schema, idempotency_key)?;
open_envelope(&sealed, &self.shared_secret)
}
}
fn validate_private_response_binding(
envelope: &PrivateEnvelope,
operation: &str,
content_schema: &str,
idempotency_key: &str,
) -> anyhow::Result<()> {
if envelope.app_slug != APP_SLUG {
bail!("Heimdall private response belongs to another app");
}
if envelope.operation != operation || envelope.content_schema != content_schema {
bail!("Heimdall private response disagrees with the requested operation");
}
if envelope.idempotency_key != idempotency_key {
bail!("Heimdall private response belongs to another request");
}
Ok(())
}
fn verify_claim_binding(
completion: &AuthCompletionReceipt,
claims: &AccessClaims,
@ -519,6 +617,58 @@ fn verify_claim_binding(
Ok(())
}
fn verified_session_material(
completion: AuthCompletionReceipt,
claims: AccessClaims,
) -> anyhow::Result<VerifiedSessionMaterial> {
if !completion
.shared_capabilities
.iter()
.any(|value| value == "app_access")
{
bail!("Heimdall response did not expose signed app_access");
}
let session = completion
.session
.as_ref()
.context("Heimdall omitted the verified session")?;
let access_expiry = i64::try_from(claims.exp).context("Heimdall access expiry is too large")?;
let access_expires_at =
DateTime::from_timestamp(access_expiry, 0).context("Heimdall access expiry is invalid")?;
let session_expires_at: DateTime<Utc> = session
.expires_at
.parse()
.context("Heimdall session expiry is invalid")?;
if session_expires_at != access_expires_at {
bail!("Heimdall session expiry disagrees with its signed claim");
}
let refresh_expires_at: DateTime<Utc> = completion
.refresh
.as_ref()
.context("Heimdall omitted refresh expiry")?
.expires_at
.parse()
.context("Heimdall refresh expiry is invalid")?;
if refresh_expires_at <= access_expires_at {
bail!("Heimdall refresh expiry does not outlive access");
}
let refresh_claim = completion
.refresh_token
.context("Heimdall omitted its refresh claim")?;
if refresh_claim.is_empty() || refresh_claim.trim() != refresh_claim {
bail!("Heimdall refresh claim is empty or noncanonical");
}
Ok(VerifiedSessionMaterial {
account_id: claims.account_id,
heimdall_session_id: claims.sid,
access_revision: claims.access_revision,
capabilities: claims.capabilities,
access_expires_at,
refresh_expires_at,
refresh_claim,
})
}
fn invoke_operation(
endpoint: SocketAddr,
target_runtime_id: &str,
@ -844,6 +994,42 @@ mod tests {
}
}
#[test]
fn private_responses_are_bound_to_the_exact_app_and_request() {
let secret = "fixture-shared-secret";
let operation = "heimdall.auth.begin";
let content_schema = "heimdall.auth_begin_receipt.v1";
let exact = seal_envelope(operation, content_schema, "request-a", secret, &"receipt")
.expect("fixture response should seal");
validate_private_response_binding(&exact, operation, content_schema, "request-a")
.expect("exact response binding should be accepted");
let replayed_other_request =
seal_envelope(operation, content_schema, "request-b", secret, &"receipt")
.expect("other request should seal validly");
assert!(
validate_private_response_binding(
&replayed_other_request,
operation,
content_schema,
"request-a",
)
.unwrap_err()
.to_string()
.contains("another request")
);
let mut other_app = exact;
other_app.app_slug = "another-app".into();
other_app.signature = sign(&other_app, secret).expect("other app response should sign");
assert!(
validate_private_response_binding(&other_app, operation, content_schema, "request-a",)
.unwrap_err()
.to_string()
.contains("another app")
);
}
#[test]
fn accepts_only_the_discovered_loopback_private_boundary() {
let resolved = validate_heimdall_boundary(boundary("rudp://127.0.0.1:4101"))

View file

@ -1,4 +1,5 @@
use anyhow::{Context, Result, anyhow, bail};
use cultcache_rs::{CultCacheEnvelope, SingleFileMessagePackBackingStore};
use cultnet_rs::{
CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding,
CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, CultNetWireContract,
@ -6,15 +7,240 @@ use cultnet_rs::{
encode_cultnet_message_to_vec, open_service_identity_at,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[cfg(target_os = "linux")]
use std::os::unix::fs::MetadataExt;
use std::{
net::{SocketAddr, UdpSocket},
path::Path,
path::{Path, PathBuf},
time::{Duration, Instant},
};
pub const GHOSTLIGHT_IDUNN_HEALTH_CONTRACT: &str = "ghostlight.cultnet-rudp-service-health";
const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0";
const IDUNN_HEALTH_RUDP_CONNECTION_ID: u32 = 0x1d0d_0001;
const GHOSTLIGHT_ACTIVATION_SCHEMA: &str = "gamecult.ghostlight.activation.v1";
const GHOSTLIGHT_ACTIVATION_PATH: &str = "/etc/gamecult/ghostlight-dungeon/runtime/ACTIVATION";
const GHOSTLIGHT_UNIT_PATH: &str = "/etc/systemd/system/ghostlight-dungeon.service";
const GHOSTLIGHT_RUNTIME_ENVIRONMENT_PATH: &str = "/srv/ghostlight/deploy/runtime.env";
const TRAFFIC_ADMISSION_PATH: &str =
"/etc/gamecult/ghostlight-dungeon/runtime/traffic-admission.cc";
const TRAFFIC_ADMISSION_TYPE: &str = "idunn.runtime_traffic_admission";
const TRAFFIC_ADMISSION_SCHEMA: &str = "idunn.runtime_traffic_admission.v2";
const TRAFFIC_ADMISSION_KEY: &str = "yggdrasil-ghostlight";
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct IdunnReleaseBinding {
pub(crate) release_id: String,
pub(crate) release_witness_sha256: String,
pub(crate) source_commit: String,
pub(crate) deployment_id: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct IdunnActivationBinding {
activation_witness_sha256: String,
}
// Idunn owns and writes this CultCache schema. Ghostlight carries only the
// exact read-side projection required to consume that root traffic grant.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct TrafficAdmissionConsumerProjection {
schema_version: String,
daemon_id: String,
release_id: String,
release_witness_sha256: String,
source_commit: String,
deployment_id: String,
activation_witness_sha256: String,
signed_health_sha256: String,
publisher_incarnation_id: String,
publisher_sequence: u64,
signer_identity_id: String,
runtime_process_id: u32,
runtime_process_starttime_ticks: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct RuntimeProcessInstanceBinding {
process_id: u32,
starttime_ticks: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct ActivationWitness {
activation_id: String,
daemon_id: String,
release_id: String,
release_witness_sha256: String,
source_commit: String,
deployment_id: String,
unit_path: String,
unit_sha256: String,
runtime_environment_path: String,
runtime_environment_sha256: String,
}
#[derive(Clone)]
pub(crate) struct GhostlightTrafficAdmissionGate {
path: PathBuf,
expected: TrafficAdmissionConsumerProjection,
ghostlight_gid: u32,
}
pub(crate) struct PublishedHealthStatementIdentity {
daemon_id: String,
signed_health_sha256: String,
publisher_incarnation_id: String,
publisher_sequence: u64,
signer_identity_id: String,
}
impl IdunnReleaseBinding {
fn validate(&self) -> Result<()> {
require_id(&self.release_id, "release id")?;
require_id(&self.deployment_id, "deployment id")?;
if !self
.release_witness_sha256
.strip_prefix("sha256-")
.is_some_and(|digest| is_lower_hex(digest, 64))
|| !is_lower_hex(&self.source_commit, 40)
{
bail!("release health binding is malformed");
}
Ok(())
}
}
impl IdunnActivationBinding {
fn validate(&self) -> Result<()> {
require_sha256(&self.activation_witness_sha256, "activation witness digest")
}
}
impl GhostlightTrafficAdmissionGate {
pub(crate) fn from_environment(
release: &IdunnReleaseBinding,
activation: &IdunnActivationBinding,
published: &PublishedHealthStatementIdentity,
) -> Result<Self> {
#[cfg(not(target_os = "linux"))]
bail!("signed Ghostlight health and traffic admission require Linux");
let raw_path = std::env::var("GHOSTLIGHT_TRAFFIC_ADMISSION")
.context("GHOSTLIGHT_TRAFFIC_ADMISSION is required for signed health")?;
if raw_path != TRAFFIC_ADMISSION_PATH {
bail!("Ghostlight traffic admission path is not the fixed root policy path");
}
Ok(Self {
path: PathBuf::from(raw_path),
expected: traffic_admission_expectation(release, activation, published)?,
ghostlight_gid: local_group_id("ghostlight")?,
})
}
pub(crate) async fn wait_until_granted(&self, timeout: Duration) -> Result<()> {
let started = tokio::time::Instant::now();
let mut last_invalid_observation = None;
loop {
match self.is_current() {
Ok(true) => return Ok(()),
Ok(false) => last_invalid_observation = None,
Err(error) => last_invalid_observation = Some(format!("{error:#}")),
}
if started.elapsed() >= timeout {
let detail = last_invalid_observation
.as_deref()
.unwrap_or("the fixed admission record remained absent");
bail!(
"timed out waiting for exact sealed root traffic admission {}: {}",
self.path.display(),
detail,
);
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
pub(crate) fn require_current(&self) -> Result<()> {
if !self.is_current()? {
bail!(
"root traffic admission disappeared from {}",
self.path.display()
);
}
Ok(())
}
fn is_current(&self) -> Result<bool> {
match std::fs::symlink_metadata(&self.path) {
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(error) => {
return Err(error).with_context(|| {
format!(
"inspecting Ghostlight traffic admission {}",
self.path.display()
)
});
}
}
require_sealed_traffic_admission_files(&self.path, self.ghostlight_gid)?;
SingleFileMessagePackBackingStore::new(&self.path).with_read_only_shared_snapshot(
|entries| {
require_sealed_traffic_admission_files(&self.path, self.ghostlight_gid)?;
let admitted = decode_traffic_admission_entries(&entries)?;
require_exact_traffic_admission(&admitted, &self.expected)
},
)?;
Ok(true)
}
}
pub(crate) fn active_activation_binding(
release: &IdunnReleaseBinding,
) -> Result<IdunnActivationBinding> {
#[cfg(not(target_os = "linux"))]
bail!("signed Ghostlight health activation requires Linux");
release.validate()?;
let activation_path = Path::new(GHOSTLIGHT_ACTIVATION_PATH);
let unit_path = Path::new(GHOSTLIGHT_UNIT_PATH);
let runtime_environment_path = Path::new(GHOSTLIGHT_RUNTIME_ENVIRONMENT_PATH);
let activation_bytes = read_root_controlled_file(activation_path, "Ghostlight activation")?;
let unit_bytes = read_root_controlled_file(unit_path, "Ghostlight systemd unit")?;
let runtime_environment_bytes =
read_root_controlled_file(runtime_environment_path, "Ghostlight runtime environment")?;
let witness = parse_activation_witness(&activation_bytes)?;
let activation_id = std::env::var("GHOSTLIGHT_ACTIVATION_ID")
.context("GHOSTLIGHT_ACTIVATION_ID is required for signed health")?;
require_safe_token(&activation_id, "activation id")?;
let expected = ActivationWitness {
activation_id,
daemon_id: TRAFFIC_ADMISSION_KEY.into(),
release_id: release.release_id.clone(),
release_witness_sha256: release.release_witness_sha256.clone(),
source_commit: release.source_commit.clone(),
deployment_id: release.deployment_id.clone(),
unit_path: GHOSTLIGHT_UNIT_PATH.into(),
unit_sha256: format!("sha256-{}", hex(&Sha256::digest(&unit_bytes))),
runtime_environment_path: GHOSTLIGHT_RUNTIME_ENVIRONMENT_PATH.into(),
runtime_environment_sha256: format!(
"sha256-{}",
hex(&Sha256::digest(&runtime_environment_bytes))
),
};
validate_activation_witness(&witness)?;
if witness != expected {
bail!("activation witness does not bind the exact Ghostlight launch inputs");
}
let binding = IdunnActivationBinding {
activation_witness_sha256: format!("sha256-{}", hex(&Sha256::digest(&activation_bytes))),
};
binding.validate()?;
Ok(binding)
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct IdunnSignedDaemonHealthRecord {
@ -36,6 +262,7 @@ struct IdunnSignedDaemonHealthRecord {
#[serde(with = "serde_bytes")]
signature: Vec<u8>,
private_state_exposed: bool,
activation_witness_sha256: Option<String>,
}
impl IdunnSignedDaemonHealthRecord {
@ -60,37 +287,63 @@ impl IdunnSignedDaemonHealthRecord {
|| self.detail.chars().any(char::is_control)
|| self.publisher_sequence == 0
|| self.observed_at_unix_millis == 0
|| self.release_id.is_some()
|| self.release_witness_sha256.is_some()
|| self.source_commit.is_some()
|| self.deployment_id.is_some()
|| self.signature_algorithm != "ed25519"
|| self.signature.len() != 64
|| self.private_state_exposed
{
bail!("signed daemon health shape is invalid");
}
IdunnReleaseBinding {
release_id: self
.release_id
.clone()
.ok_or_else(|| anyhow!("signed health release id is absent"))?,
release_witness_sha256: self
.release_witness_sha256
.clone()
.ok_or_else(|| anyhow!("signed health release witness is absent"))?,
source_commit: self
.source_commit
.clone()
.ok_or_else(|| anyhow!("signed health source commit is absent"))?,
deployment_id: self
.deployment_id
.clone()
.ok_or_else(|| anyhow!("signed health deployment id is absent"))?,
}
.validate()?;
IdunnActivationBinding {
activation_witness_sha256: self
.activation_witness_sha256
.clone()
.ok_or_else(|| anyhow!("signed health activation witness is absent"))?,
}
.validate()?;
Ok(())
}
}
pub struct IdunnHealthPublisher {
pub(crate) struct IdunnHealthPublisher {
endpoint: SocketAddr,
daemon_id: String,
source_runtime_id: String,
health_contract: String,
signer: ServiceIdentitySigner<GameCultProviderHealthIdentity>,
release: IdunnReleaseBinding,
activation: IdunnActivationBinding,
publisher_incarnation_id: String,
publisher_sequence: u64,
}
impl IdunnHealthPublisher {
pub fn open(
pub(crate) fn open(
endpoint: SocketAddr,
daemon_id: impl Into<String>,
source_runtime_id: impl Into<String>,
health_contract: impl Into<String>,
identity_store: impl AsRef<Path>,
release: IdunnReleaseBinding,
activation: IdunnActivationBinding,
) -> Result<Self> {
let daemon_id = daemon_id.into();
let source_runtime_id = source_runtime_id.into();
@ -98,6 +351,8 @@ impl IdunnHealthPublisher {
require_id(&daemon_id, "Idunn daemon id")?;
require_id(&source_runtime_id, "health source runtime id")?;
require_id(&health_contract, "Idunn health contract")?;
release.validate()?;
activation.validate()?;
Ok(Self {
endpoint,
daemon_id,
@ -106,12 +361,18 @@ impl IdunnHealthPublisher {
signer: open_service_identity_at::<GameCultProviderHealthIdentity>(
identity_store.as_ref(),
)?,
release,
activation,
publisher_incarnation_id: uuid::Uuid::new_v4().to_string(),
publisher_sequence: 0,
})
}
pub fn publish(&mut self, state: &str, detail: &str) -> Result<()> {
pub(crate) fn publish(
&mut self,
state: &str,
detail: &str,
) -> Result<PublishedHealthStatementIdentity> {
if !matches!(state, "active" | "warming" | "degraded" | "failed") {
bail!("unsupported Idunn daemon health state");
}
@ -133,13 +394,14 @@ impl IdunnHealthPublisher {
publisher_incarnation_id: self.publisher_incarnation_id.clone(),
publisher_sequence: self.publisher_sequence,
observed_at_unix_millis: chrono::Utc::now().timestamp_millis().try_into()?,
release_id: None,
release_witness_sha256: None,
source_commit: None,
deployment_id: None,
release_id: Some(self.release.release_id.clone()),
release_witness_sha256: Some(self.release.release_witness_sha256.clone()),
source_commit: Some(self.release.source_commit.clone()),
deployment_id: Some(self.release.deployment_id.clone()),
signature_algorithm: "ed25519".into(),
signature: Vec::new(),
private_state_exposed: false,
activation_witness_sha256: Some(self.activation.activation_witness_sha256.clone()),
};
let unsigned = canonical_unsigned_record(&record)?;
let proof = self
@ -150,10 +412,18 @@ impl IdunnHealthPublisher {
}
record.signature = proof.signature;
record.validate()?;
publish_signed_health(self.endpoint, &self.source_runtime_id, &record)
let signed_health_sha256 =
publish_signed_health(self.endpoint, &self.source_runtime_id, &record)?;
Ok(PublishedHealthStatementIdentity {
daemon_id: record.daemon_id,
signed_health_sha256,
publisher_incarnation_id: record.publisher_incarnation_id,
publisher_sequence: record.publisher_sequence,
signer_identity_id: record.signer_identity_id,
})
}
pub fn public_key(&self) -> &[u8] {
pub(crate) fn public_key(&self) -> &[u8] {
&self.signer.entry().public_key
}
}
@ -162,13 +432,14 @@ fn publish_signed_health(
endpoint: SocketAddr,
source_runtime_id: &str,
signed: &IdunnSignedDaemonHealthRecord,
) -> Result<()> {
) -> Result<String> {
signed.validate()?;
let payload = rmp_serde::to_vec(signed).context("encoding canonical signed Idunn health")?;
let decoded: IdunnSignedDaemonHealthRecord = rmp_serde::from_slice(&payload)?;
if decoded != *signed || rmp_serde::to_vec(&decoded)? != payload {
bail!("signed Idunn health encoding is noncanonical");
}
let signed_health_sha256 = format!("sha256-{}", hex(&Sha256::digest(&payload)));
let message = CultNetMessage::DocumentPutRaw {
message_id: format!(
"ghostlight-signed-health:{}:{}:{}",
@ -220,9 +491,387 @@ fn publish_signed_health(
"schema",
encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0)?,
)?;
Ok(signed_health_sha256)
}
fn parse_activation_witness(bytes: &[u8]) -> Result<ActivationWitness> {
let text = std::str::from_utf8(bytes).context("Ghostlight activation witness is not UTF-8")?;
let body = text
.strip_suffix('\n')
.ok_or_else(|| anyhow!("Ghostlight activation witness has no canonical final newline"))?;
if body.contains('\r') {
bail!("Ghostlight activation witness has noncanonical line endings");
}
let lines = body.split('\n').collect::<Vec<_>>();
let [
schema,
activation_id,
daemon_id,
release_id,
release_witness_sha256,
source_commit,
deployment_id,
unit_path,
unit_sha256,
runtime_environment_path,
runtime_environment_sha256,
] = lines.as_slice()
else {
bail!("Ghostlight activation witness has an unexpected field set");
};
if exact_witness_value(schema, "schema_version")? != GHOSTLIGHT_ACTIVATION_SCHEMA {
bail!("Ghostlight activation witness schema is not admitted");
}
let witness = ActivationWitness {
activation_id: exact_witness_value(activation_id, "activation_id")?.into(),
daemon_id: exact_witness_value(daemon_id, "daemon_id")?.into(),
release_id: exact_witness_value(release_id, "release_id")?.into(),
release_witness_sha256: exact_witness_value(
release_witness_sha256,
"release_witness_sha256",
)?
.into(),
source_commit: exact_witness_value(source_commit, "source_commit")?.into(),
deployment_id: exact_witness_value(deployment_id, "deployment_id")?.into(),
unit_path: exact_witness_value(unit_path, "unit_path")?.into(),
unit_sha256: exact_witness_value(unit_sha256, "unit_sha256")?.into(),
runtime_environment_path: exact_witness_value(
runtime_environment_path,
"runtime_environment_path",
)?
.into(),
runtime_environment_sha256: exact_witness_value(
runtime_environment_sha256,
"runtime_environment_sha256",
)?
.into(),
};
validate_activation_witness(&witness)?;
Ok(witness)
}
fn exact_witness_value<'a>(line: &'a str, field: &str) -> Result<&'a str> {
let prefix = format!("{field}=");
let value = line
.strip_prefix(&prefix)
.with_context(|| format!("Ghostlight activation witness field {field} is out of order"))?;
if value.is_empty() || value.trim() != value || value.chars().any(char::is_control) {
bail!("Ghostlight activation witness field {field} is malformed");
}
Ok(value)
}
fn validate_activation_witness(witness: &ActivationWitness) -> Result<()> {
require_safe_token(&witness.activation_id, "activation id")?;
require_safe_token(&witness.deployment_id, "deployment id")?;
require_id(&witness.release_id, "release id")?;
if witness.daemon_id != TRAFFIC_ADMISSION_KEY
|| witness.unit_path != GHOSTLIGHT_UNIT_PATH
|| witness.runtime_environment_path != GHOSTLIGHT_RUNTIME_ENVIRONMENT_PATH
|| !is_lower_hex(&witness.source_commit, 40)
{
bail!("Ghostlight activation witness identity is malformed");
}
require_sha256(&witness.release_witness_sha256, "release witness digest")?;
require_sha256(&witness.unit_sha256, "systemd unit digest")?;
require_sha256(
&witness.runtime_environment_sha256,
"runtime environment digest",
)?;
Ok(())
}
fn traffic_admission_expectation(
release: &IdunnReleaseBinding,
activation: &IdunnActivationBinding,
published: &PublishedHealthStatementIdentity,
) -> Result<TrafficAdmissionConsumerProjection> {
release.validate()?;
activation.validate()?;
if published.daemon_id != TRAFFIC_ADMISSION_KEY || published.publisher_sequence != 1 {
bail!("signed health identity for traffic admission is malformed");
}
require_sha256(
&published.signed_health_sha256,
"signed health statement digest",
)?;
require_id(
&published.signer_identity_id,
"traffic admission signer identity",
)?;
uuid::Uuid::parse_str(&published.publisher_incarnation_id)
.context("traffic admission publisher incarnation is malformed")?;
let process = current_runtime_process_instance()?;
let expected = TrafficAdmissionConsumerProjection {
schema_version: TRAFFIC_ADMISSION_SCHEMA.into(),
daemon_id: published.daemon_id.clone(),
release_id: release.release_id.clone(),
release_witness_sha256: release.release_witness_sha256.clone(),
source_commit: release.source_commit.clone(),
deployment_id: release.deployment_id.clone(),
activation_witness_sha256: activation.activation_witness_sha256.clone(),
signed_health_sha256: published.signed_health_sha256.clone(),
publisher_incarnation_id: published.publisher_incarnation_id.clone(),
publisher_sequence: published.publisher_sequence,
signer_identity_id: published.signer_identity_id.clone(),
runtime_process_id: process.process_id,
runtime_process_starttime_ticks: process.starttime_ticks,
};
validate_traffic_admission_projection(&expected)?;
Ok(expected)
}
fn decode_traffic_admission_entries(
entries: &[CultCacheEnvelope],
) -> Result<TrafficAdmissionConsumerProjection> {
let [record] = entries else {
bail!("Ghostlight traffic admission store must contain exactly one record");
};
if record.key != TRAFFIC_ADMISSION_KEY
|| record.r#type != TRAFFIC_ADMISSION_TYPE
|| record.schema_id.as_deref() != Some(TRAFFIC_ADMISSION_SCHEMA)
{
bail!("Ghostlight traffic admission store has the wrong typed envelope");
}
let admitted: TrafficAdmissionConsumerProjection = rmp_serde::from_slice(&record.payload)
.context("decoding typed Ghostlight traffic admission record")?;
if rmp_serde::to_vec(&admitted)? != record.payload {
bail!("Ghostlight traffic admission payload is not canonical positional MessagePack");
}
validate_traffic_admission_projection(&admitted)?;
Ok(admitted)
}
fn validate_traffic_admission_projection(
admission: &TrafficAdmissionConsumerProjection,
) -> Result<()> {
if admission.schema_version != TRAFFIC_ADMISSION_SCHEMA
|| admission.daemon_id != TRAFFIC_ADMISSION_KEY
|| admission.publisher_sequence == 0
|| admission.runtime_process_id == 0
|| admission.runtime_process_starttime_ticks == 0
|| !is_lower_hex(&admission.source_commit, 40)
{
bail!("Ghostlight traffic admission typed identity is invalid");
}
require_id(&admission.release_id, "traffic admission release id")?;
require_safe_token(&admission.deployment_id, "traffic admission deployment id")?;
require_id(
&admission.signer_identity_id,
"traffic admission signer identity",
)?;
uuid::Uuid::parse_str(&admission.publisher_incarnation_id)
.context("traffic admission publisher incarnation is malformed")?;
require_sha256(
&admission.release_witness_sha256,
"traffic admission release witness digest",
)?;
require_sha256(
&admission.activation_witness_sha256,
"traffic admission activation witness digest",
)?;
require_sha256(
&admission.signed_health_sha256,
"traffic admission signed health digest",
)?;
Ok(())
}
fn current_runtime_process_instance() -> Result<RuntimeProcessInstanceBinding> {
let process_id = std::process::id();
if process_id == 0 {
bail!("current Ghostlight process id is invalid");
}
let stat = std::fs::read_to_string("/proc/self/stat")
.context("reading current Ghostlight /proc starttime")?;
Ok(RuntimeProcessInstanceBinding {
process_id,
starttime_ticks: parse_proc_stat_starttime(&stat, process_id)?,
})
}
fn parse_proc_stat_starttime(stat: &str, expected_process_id: u32) -> Result<u64> {
let stat = stat.strip_suffix('\n').unwrap_or(stat);
if stat.contains('\r') || stat.contains('\n') {
bail!("current Ghostlight /proc stat has noncanonical line endings");
}
let prefix = format!("{expected_process_id} (");
if !stat.starts_with(&prefix) {
bail!("current Ghostlight /proc stat has the wrong process id");
}
let command_end = stat
.rfind(") ")
.context("current Ghostlight /proc stat has no command terminator")?;
let fields = stat[command_end + 2..]
.split_ascii_whitespace()
.collect::<Vec<_>>();
if fields.len() <= 19 || fields[0].len() != 1 {
bail!("current Ghostlight /proc stat is missing starttime");
}
let value = fields[19];
let starttime_ticks = value
.parse::<u64>()
.context("current Ghostlight /proc starttime is malformed")?;
if starttime_ticks == 0 || starttime_ticks.to_string() != value {
bail!("current Ghostlight /proc starttime is noncanonical");
}
Ok(starttime_ticks)
}
fn require_exact_traffic_admission(
admitted: &TrafficAdmissionConsumerProjection,
expected: &TrafficAdmissionConsumerProjection,
) -> Result<()> {
if admitted != expected {
bail!("root traffic admission does not match the exact startup statement");
}
Ok(())
}
fn require_sealed_traffic_admission_files(path: &Path, ghostlight_gid: u32) -> Result<()> {
#[cfg(not(target_os = "linux"))]
bail!("Ghostlight traffic admission sealing requires Linux");
#[cfg(target_os = "linux")]
{
if path != Path::new(TRAFFIC_ADMISSION_PATH) {
bail!("Ghostlight traffic admission is not at its fixed path");
}
let parent = path
.parent()
.context("Ghostlight traffic admission has no parent")?;
let expected_parent = Path::new("/etc/gamecult/ghostlight-dungeon/runtime");
if parent != expected_parent {
bail!("Ghostlight traffic admission parent is not canonical");
}
require_exact_root_group_mode(
parent,
"traffic admission directory",
ghostlight_gid,
0o750,
true,
)?;
require_exact_root_group_mode(
path,
"traffic admission record",
ghostlight_gid,
0o640,
false,
)?;
let lock_path = sibling_lock_path(path);
require_exact_root_group_mode(
&lock_path,
"traffic admission shared lock",
ghostlight_gid,
0o640,
false,
)?;
for ancestor in parent.ancestors().skip(1) {
let metadata = std::fs::symlink_metadata(ancestor).with_context(|| {
format!(
"inspecting traffic admission ancestor {}",
ancestor.display()
)
})?;
if metadata.file_type().is_symlink()
|| metadata.uid() != 0
|| metadata.mode() & 0o022 != 0
{
bail!("traffic admission ancestor is indirect or mutable outside root");
}
}
Ok(())
}
}
#[cfg(target_os = "linux")]
fn require_exact_root_group_mode(
path: &Path,
label: &str,
group_id: u32,
mode: u32,
directory: bool,
) -> Result<()> {
let metadata = std::fs::symlink_metadata(path)
.with_context(|| format!("inspecting {label} {}", path.display()))?;
if metadata.file_type().is_symlink()
|| metadata.uid() != 0
|| metadata.gid() != group_id
|| metadata.mode() & 0o7777 != mode
|| (directory && !metadata.file_type().is_dir())
|| (!directory && !metadata.file_type().is_file())
{
bail!("{label} does not have the exact root:ghostlight sealed shape");
}
Ok(())
}
fn local_group_id(name: &str) -> Result<u32> {
#[cfg(not(target_os = "linux"))]
bail!("local group identity verification requires Linux");
#[cfg(target_os = "linux")]
{
let bytes = read_root_controlled_file(Path::new("/etc/group"), "local group database")?;
let text = std::str::from_utf8(&bytes).context("local group database is not UTF-8")?;
let mut found = None;
for line in text.lines() {
let fields = line.split(':').collect::<Vec<_>>();
if fields.first().copied() != Some(name) {
continue;
}
let value = fields
.get(2)
.filter(|value| !value.is_empty())
.context("local Ghostlight group has no numeric id")?;
let group_id = value
.parse::<u32>()
.context("local Ghostlight group id is malformed")?;
if group_id.to_string() != *value || found.replace(group_id).is_some() {
bail!("local Ghostlight group identity is noncanonical or duplicate");
}
}
found.context("local Ghostlight group is absent")
}
}
fn sibling_lock_path(path: &Path) -> PathBuf {
let mut lock_name = path
.file_name()
.map(|value| value.to_os_string())
.unwrap_or_else(|| "cultcache.cc".into());
lock_name.push(".lock");
path.with_file_name(lock_name)
}
fn read_root_controlled_file(path: &Path, label: &str) -> Result<Vec<u8>> {
#[cfg(not(target_os = "linux"))]
bail!("{label} root-control verification requires Linux");
#[cfg(target_os = "linux")]
{
if !path.is_absolute() {
bail!("{label} path is not absolute");
}
for candidate in path.ancestors() {
let metadata = std::fs::symlink_metadata(candidate)
.with_context(|| format!("inspecting {label} path {}", candidate.display()))?;
if metadata.file_type().is_symlink()
|| metadata.uid() != 0
|| metadata.mode() & 0o022 != 0
{
bail!("{label} path is indirect or mutable outside root");
}
}
let metadata = std::fs::symlink_metadata(path)
.with_context(|| format!("inspecting {label} {}", path.display()))?;
if !metadata.file_type().is_file() {
bail!("{label} is not a regular file");
}
std::fs::read(path).with_context(|| format!("reading {label} {}", path.display()))
}
}
fn canonical_unsigned_record(record: &IdunnSignedDaemonHealthRecord) -> Result<Vec<u8>> {
let mut unsigned = record.clone();
unsigned.signature.clear();
@ -241,6 +890,35 @@ fn require_id(value: &str, label: &str) -> Result<()> {
Ok(())
}
fn require_safe_token(value: &str, label: &str) -> Result<()> {
if value.is_empty()
|| value.len() > 256
|| !value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
{
bail!("{label} is malformed");
}
Ok(())
}
fn require_sha256(value: &str, label: &str) -> Result<()> {
if !value
.strip_prefix("sha256-")
.is_some_and(|digest| is_lower_hex(digest, 64))
{
bail!("{label} is malformed");
}
Ok(())
}
fn is_lower_hex(value: &str, length: usize) -> bool {
value.len() == length
&& value
.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
}
#[cfg(test)]
mod tests {
use super::*;
@ -250,7 +928,7 @@ mod tests {
};
#[test]
fn ghostlight_health_is_canonical_private_free_and_release_unbound() {
fn ghostlight_health_is_canonical_private_free_and_release_bound() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("provider.cc");
let signer = enroll_service_identity_at::<GameCultProviderHealthIdentity>(&path).unwrap();
@ -260,6 +938,15 @@ mod tests {
"ghostlight-dungeon-yggdrasil",
GHOSTLIGHT_IDUNN_HEALTH_CONTRACT,
&path,
IdunnReleaseBinding {
release_id: "release-1".into(),
release_witness_sha256: format!("sha256-{}", "a".repeat(64)),
source_commit: "b".repeat(40),
deployment_id: "deployment-1".into(),
},
IdunnActivationBinding {
activation_witness_sha256: format!("sha256-{}", "c".repeat(64)),
},
)
.unwrap();
publisher.publisher_sequence = 7;
@ -274,13 +961,14 @@ mod tests {
publisher_incarnation_id: publisher.publisher_incarnation_id.clone(),
publisher_sequence: publisher.publisher_sequence,
observed_at_unix_millis: 1_787_315_696_789,
release_id: None,
release_witness_sha256: None,
source_commit: None,
deployment_id: None,
release_id: Some(publisher.release.release_id.clone()),
release_witness_sha256: Some(publisher.release.release_witness_sha256.clone()),
source_commit: Some(publisher.release.source_commit.clone()),
deployment_id: Some(publisher.release.deployment_id.clone()),
signature_algorithm: "ed25519".into(),
signature: Vec::new(),
private_state_exposed: false,
activation_witness_sha256: Some(publisher.activation.activation_witness_sha256.clone()),
};
let unsigned = canonical_unsigned_record(&record).unwrap();
let proof = publisher
@ -293,8 +981,120 @@ mod tests {
IdunnSignedDaemonHealthPurpose,
>(&signer.trust_anchor().unwrap(), &unsigned, &proof)
.unwrap();
assert!(record.release_id.is_none());
assert_eq!(record.release_id.as_deref(), Some("release-1"));
assert!(!record.private_state_exposed);
assert_eq!(rmp_serde::to_vec(&record).unwrap()[..3], [0xdc, 0, 17]);
let activation_digest = format!("sha256-{}", "c".repeat(64));
assert_eq!(
record.activation_witness_sha256.as_deref(),
Some(activation_digest.as_str())
);
assert_eq!(rmp_serde::to_vec(&record).unwrap()[..3], [0xdc, 0, 18]);
}
#[test]
fn activation_witness_is_strict_ordered_and_launch_bound() {
let text = format!(
"schema_version={GHOSTLIGHT_ACTIVATION_SCHEMA}\n\
activation_id=activation-7\n\
daemon_id={TRAFFIC_ADMISSION_KEY}\n\
release_id={release}\n\
release_witness_sha256=sha256-{release_witness}\n\
source_commit={source}\n\
deployment_id=deployment-9\n\
unit_path={GHOSTLIGHT_UNIT_PATH}\n\
unit_sha256=sha256-{unit}\n\
runtime_environment_path={GHOSTLIGHT_RUNTIME_ENVIRONMENT_PATH}\n\
runtime_environment_sha256=sha256-{runtime}\n",
release = "a".repeat(40),
release_witness = "b".repeat(64),
source = "a".repeat(40),
unit = "c".repeat(64),
runtime = "d".repeat(64),
);
let parsed = parse_activation_witness(text.as_bytes()).unwrap();
assert_eq!(parsed.activation_id, "activation-7");
assert_eq!(parsed.daemon_id, TRAFFIC_ADMISSION_KEY);
let reordered = text.replacen(
"activation_id=activation-7\ndaemon_id=yggdrasil-ghostlight",
"daemon_id=yggdrasil-ghostlight\nactivation_id=activation-7",
1,
);
assert!(parse_activation_witness(reordered.as_bytes()).is_err());
assert!(parse_activation_witness(text.trim_end().as_bytes()).is_err());
}
#[test]
fn typed_traffic_admission_is_canonical_and_exact_startup_bound() {
let release = IdunnReleaseBinding {
release_id: "a".repeat(40),
release_witness_sha256: format!("sha256-{}", "b".repeat(64)),
source_commit: "a".repeat(40),
deployment_id: "deployment-9".into(),
};
let activation = IdunnActivationBinding {
activation_witness_sha256: format!("sha256-{}", "c".repeat(64)),
};
let published = PublishedHealthStatementIdentity {
daemon_id: TRAFFIC_ADMISSION_KEY.into(),
signed_health_sha256: format!("sha256-{}", "d".repeat(64)),
publisher_incarnation_id: uuid::Uuid::new_v4().to_string(),
publisher_sequence: 1,
signer_identity_id: "signer-1".into(),
};
let expected = traffic_admission_expectation(&release, &activation, &published).unwrap();
let payload = rmp_serde::to_vec(&expected).unwrap();
assert_eq!(payload.first().copied(), Some(0x9d));
assert_eq!(expected.runtime_process_id, std::process::id());
assert!(expected.runtime_process_starttime_ticks > 0);
let envelope = CultCacheEnvelope {
key: TRAFFIC_ADMISSION_KEY.into(),
r#type: TRAFFIC_ADMISSION_TYPE.into(),
schema_id: Some(TRAFFIC_ADMISSION_SCHEMA.into()),
stored_at: "2026-09-02T00:00:00Z".into(),
payload,
};
assert_eq!(
decode_traffic_admission_entries(std::slice::from_ref(&envelope)).unwrap(),
expected
);
let mut substituted = expected.clone();
substituted.publisher_sequence += 1;
validate_traffic_admission_projection(&substituted).unwrap();
assert!(require_exact_traffic_admission(&substituted, &expected).is_err());
let mut substituted_process = expected.clone();
substituted_process.runtime_process_id += 1;
validate_traffic_admission_projection(&substituted_process).unwrap();
assert!(require_exact_traffic_admission(&substituted_process, &expected).is_err());
let mut substituted_starttime = expected.clone();
substituted_starttime.runtime_process_starttime_ticks += 1;
validate_traffic_admission_projection(&substituted_starttime).unwrap();
assert!(require_exact_traffic_admission(&substituted_starttime, &expected).is_err());
let mut stale_schema = expected.clone();
stale_schema.schema_version = "idunn.runtime_traffic_admission.v1".into();
assert!(validate_traffic_admission_projection(&stale_schema).is_err());
let named_payload = rmp_serde::to_vec_named(&expected).unwrap();
let named = CultCacheEnvelope {
payload: named_payload,
..envelope.clone()
};
assert!(decode_traffic_admission_entries(&[named]).is_err());
assert!(decode_traffic_admission_entries(&[envelope.clone(), envelope.clone()]).is_err());
}
#[test]
fn proc_stat_starttime_parser_binds_pid_and_kernel_tick_identity() {
let stat =
"4242 (ghostlight ) worker) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 98765 20\n";
assert_eq!(parse_proc_stat_starttime(stat, 4242).unwrap(), 98_765);
assert!(parse_proc_stat_starttime(stat, 4243).is_err());
assert!(
parse_proc_stat_starttime(
"4242 (ghostlight) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 0",
4242,
)
.is_err()
);
}
}

View file

@ -1,35 +0,0 @@
use crate::domain::WorldActionProposal;
pub fn winner(proposals: &[WorldActionProposal]) -> Option<WorldActionProposal> {
proposals.iter().cloned().max_by(|left, right| {
left.priority
.cmp(&right.priority)
.then_with(|| right.actor_id.cmp(&left.actor_id))
.then_with(|| right.intent.cmp(&left.intent))
})
}
#[cfg(test)]
mod tests {
use super::*;
fn proposal(actor: &str, priority: i16) -> WorldActionProposal {
WorldActionProposal {
actor_id: actor.into(),
intent: "act".into(),
intended_effect: "change something".into(),
priority,
state_references: vec![],
}
}
#[test]
fn priority_wins_with_stable_actor_tie_break() {
let proposals = vec![
proposal("bert", 5),
proposal("anna", 5),
proposal("cara", 4),
];
assert_eq!(winner(&proposals).unwrap().actor_id, "anna");
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,39 +0,0 @@
#![recursion_limit = "256"]
pub mod agency_corpus;
pub mod agent;
pub mod assessor;
pub mod clock;
pub mod compiler;
pub mod consumer;
pub mod d20;
pub mod domain;
pub mod elaboration;
pub mod follow_through;
pub mod gestalt;
pub mod idunn_health;
pub mod initiative;
pub mod kernel;
pub mod legacy_transition;
pub mod mesh;
pub mod model;
pub mod model_connector;
pub mod model_runtime;
pub mod newspaper;
pub mod outcome;
pub mod persistence;
pub mod persona;
pub mod registry;
pub mod resolution;
pub mod scheduler;
pub mod session_zero;
pub mod surface;
pub mod transition;
pub mod turn;
pub mod vault;
#[cfg(windows)]
#[cfg(windows)]
pub mod windows_secret;
mod world;
pub use kernel::{KernelError, WorldKernel};

File diff suppressed because it is too large Load diff

View file

@ -1,14 +1,9 @@
use crate::{
domain::{
Campaign, CellAppraisal, GestaltMaterializationReceipt, RejectedProposalReceipt,
ResolutionControlReceipt, ResolutionPlanReceipt, StrategicActivityOutcome,
StrategicTickReceipt, VaultEvidenceReceipt, WorldCommitReceipt,
},
model::{ModelRuntimeStatus, ModelStageReceipt},
session_zero::{CampaignMembership, SessionZeroState},
surface::{operator_surface, player_surface, player_surface_for_actor},
vault::VaultSourceManifest,
};
//! Derived CultMesh and Eve projection.
//!
//! The mesh publishes the world owner's current surface. It never pulls or
//! repairs world state and it has no command authority.
use crate::{eve, world::WorldSnapshot};
use anyhow::Result;
use chrono::Utc;
use cultcache_rs::DatabaseEntry;
@ -20,80 +15,27 @@ use serde_json::{Value, json};
use std::{
net::SocketAddr,
path::Path,
sync::{Arc, Condvar, Mutex},
sync::{
Arc, Condvar, Mutex,
atomic::{AtomicBool, Ordering},
},
thread,
};
pub const PROVIDER_ID: &str = "gamecult.ghostlight.dungeon";
pub const SURFACE_ID: &str = "ghostlight.play";
pub const COMMAND_BOUNDARY: &str = "ghostlight.eve.commands";
pub const COMMAND_RESULT_SCHEMA: &str = "gamecult.eve.command_result.v1";
pub const HEALTH_KEY: &str = "ghostlight:dungeon:health";
pub const ADVERTISEMENT_KEY: &str = "eve:provider:gamecult.ghostlight.dungeon";
pub(crate) const PROVIDER_ID: &str = "gamecult.ghostlight.dungeon";
pub(crate) const SURFACE_ID: &str = "ghostlight.play";
pub(crate) const COMMAND_BOUNDARY: &str = "ghostlight.eve.commands";
pub(crate) const COMMAND_RESULT_SCHEMA: &str = "gamecult.eve.command_result.v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MeshRuntimeIdentity {
pub runtime_id: String,
pub service_id: String,
pub located_service: String,
}
impl Default for MeshRuntimeIdentity {
fn default() -> Self {
Self {
runtime_id: "ghostlight-dungeon-starfire".into(),
service_id: "ghostlight-dungeon-starfire".into(),
located_service: "starfire".into(),
}
}
}
#[derive(Clone)]
pub struct CampaignMeshSnapshot {
pub campaign: Campaign,
pub membership: Option<CampaignMembership>,
pub evidence: Vec<VaultEvidenceReceipt>,
pub commits: Vec<WorldCommitReceipt>,
pub stages: Vec<ModelStageReceipt>,
pub strategic_ticks: Vec<StrategicTickReceipt>,
pub gestalt_receipts: Vec<GestaltMaterializationReceipt>,
pub rejected: Vec<RejectedProposalReceipt>,
pub resolution_plans: Vec<ResolutionPlanReceipt>,
pub cell_appraisals: Vec<CellAppraisal>,
pub activity_outcomes: Vec<StrategicActivityOutcome>,
pub resolution_controls: Vec<ResolutionControlReceipt>,
}
#[derive(Clone)]
pub struct SessionZeroMeshSnapshot {
pub session_zero_id: uuid::Uuid,
pub member_id: String,
pub surface: Value,
}
const HEALTH_KEY: &str = "ghostlight:dungeon:health";
const ADVERTISEMENT_KEY: &str = "eve:provider:gamecult.ghostlight.dungeon";
const SURFACE_KEY: &str = "eve:surface:ghostlight.play";
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.eve.surface", schema = "gamecult.eve.surface.v1")]
pub struct EveSurfaceRecord {
struct EveSurfaceRecord {
#[cultcache(key = 0)]
pub value: Value,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "gamecult.eve.surface_state",
schema = "gamecult.eve.surface_state.v1"
)]
pub struct EveSurfaceStateRecord {
#[cultcache(key = 0)]
pub provider_id: String,
#[cultcache(key = 1)]
pub title: String,
#[cultcache(key = 2)]
pub version: i64,
#[cultcache(key = 3)]
pub updated_at: String,
#[cultcache(key = 4)]
pub surface: Value,
value: Value,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
@ -101,41 +43,46 @@ pub struct EveSurfaceStateRecord {
type = "gamecult.eve.provider_advertisement",
schema = "gamecult.eve.provider_advertisement.v1"
)]
pub struct EveProviderAdvertisementRecord {
struct EveProviderAdvertisementRecord {
#[cultcache(key = 0)]
pub value: Value,
value: Value,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "ghostlight.service_health",
schema = "ghostlight.service_health.v1"
schema = "ghostlight.service_health.v2"
)]
pub struct ServiceHealthRecord {
struct ServiceHealthRecord {
#[cultcache(key = 0)]
pub value: Value,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "ghostlight.schema_catalog",
schema = "ghostlight.schema_catalog.v1"
)]
pub struct SchemaCatalogRecord {
#[cultcache(key = 0)]
pub value: Value,
value: Value,
}
cultmesh_rs::cultmesh_documents!(GhostlightDocuments {
EveSurfaceRecord => "gamecult.eve.surface.v1",
EveSurfaceStateRecord => "gamecult.eve.surface_state.v1",
EveProviderAdvertisementRecord => "gamecult.eve.provider_advertisement.v1",
ServiceHealthRecord => "ghostlight.service_health.v1",
SchemaCatalogRecord => "ghostlight.schema_catalog.v1",
ServiceHealthRecord => "ghostlight.service_health.v2",
});
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct MeshRuntimeIdentity {
pub(crate) runtime_id: String,
pub(crate) service_id: String,
pub(crate) located_service: String,
}
impl Default for MeshRuntimeIdentity {
fn default() -> Self {
Self {
runtime_id: "ghostlight-dungeon".into(),
service_id: "ghostlight-dungeon".into(),
located_service: "local".into(),
}
}
}
#[derive(Clone)]
pub struct MeshPublisher {
pub(crate) struct MeshPublisher {
node: Arc<Mutex<CultMeshNode>>,
remote: Option<RemoteReplication>,
identity: MeshRuntimeIdentity,
@ -146,14 +93,11 @@ struct RemoteReplication {
target: SocketAddr,
runtime_id: String,
pending: Arc<(Mutex<Option<Vec<cultnet_rs::CultNetMessage>>>, Condvar)>,
alive: Arc<AtomicBool>,
}
impl MeshPublisher {
pub fn open(store_path: impl AsRef<Path>, rudp_target: Option<SocketAddr>) -> Result<Self> {
Self::open_with_identity(store_path, rudp_target, MeshRuntimeIdentity::default())
}
pub fn open_with_identity(
pub(crate) fn open(
store_path: impl AsRef<Path>,
rudp_target: Option<SocketAddr>,
identity: MeshRuntimeIdentity,
@ -166,11 +110,14 @@ impl MeshPublisher {
GhostlightDocuments,
CultMeshNodeOptions {
runtime_id: identity.runtime_id.clone(),
pull_on_start: true,
// Ghostlight derives its own interface from the local owner.
// Stale remote surfaces must never become startup authority.
pull_on_start: false,
},
)?;
let remote =
rudp_target.map(|target| RemoteReplication::start(target, identity.runtime_id.clone()));
let remote = rudp_target
.map(|target| RemoteReplication::start(target, identity.runtime_id.clone()))
.transpose()?;
Ok(Self {
node: Arc::new(Mutex::new(node)),
remote,
@ -178,125 +125,30 @@ impl MeshPublisher {
})
}
pub fn identity(&self) -> &MeshRuntimeIdentity {
&self.identity
pub(crate) fn provider_advertisement(&self, updated_at: &str) -> Value {
provider_advertisement(&self.identity, updated_at)
}
pub fn provider_advertisement(&self, updated_at: &str) -> Value {
json!({
"schema":"gamecult.eve.provider_advertisement.v1",
"providerId":PROVIDER_ID,
"serviceId":self.identity.service_id.as_str(),
"verseId":"gamecult.private",
"rootVerse":"gamecult",
"canonicalService":"ghostlight-dungeon",
"locatedService":self.identity.located_service.as_str(),
"cultMeshAddress":"cultmesh://gamecult.private/ghostlight/providers/dungeon",
"title":"Ghostlight Dungeon",
"kind":"narrative.simulation",
"updatedAtUtc":updated_at,
"freshness":{"state":"live","lastSeenAtUtc":updated_at,"maxAgeMs":360000},
"schemas":[
"gamecult.eve.surface.v1",
"gamecult.eve.command_invocation.v1",
COMMAND_RESULT_SCHEMA,
"gamecult.eve.command_receipt.v1",
"heimdall.access_gate_state.v1"
],
"witnesses":[{"kind":"source-commit","ref":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")}],
"worldConsumerBoundary":{
"serviceId":"ghostlight.world.consumer",
"transport":"cultnet.transport.rudp.v0",
"endpoint":"127.0.0.1:4102",
"exposure":"loopback-only",
"operations":[
"ghostlight.world.seed.admit",
"ghostlight.world.external.snapshot.apply",
"ghostlight.world.external.proposals.list",
"ghostlight.world.external.proposal.acknowledge",
"ghostlight.world.newspaper.compose"
],
"ownership":"Consumers own declared external subjects; Ghostlight owns all simulated world subjects and emits proposals across that boundary."
},
"surfaces":[{
"surfaceId":SURFACE_ID,
"schema":"gamecult.eve.surface.v1",
"url":"/api/eve/surfaces/ghostlight.play",
"transport":"https-json",
"status":"available",
"surfaceKind":"subject-scoped-narrative",
"interactionModel":"typed-command-receipts",
"worldInteraction":{
"projectionKind":"actor-filtered-authoritative",
"stateSchemas":["ghostlight.session_zero.v1","ghostlight.campaign.v1"],
"commandBoundary":COMMAND_BOUNDARY,
"nativeCommandBoundary":{
"serviceId":"ghostlight.native.player",
"transport":"cultnet.transport.rudp.v0",
"endpoint":"127.0.0.1:4102",
"exposure":"loopback-only",
"authentication":"Heimdall-backed Ghostlight app session",
"operations":["ghostlight.auth.begin","ghostlight.auth.complete","ghostlight.surface.get","ghostlight.eve.invoke"]
},
"receiptSchema":COMMAND_RESULT_SCHEMA,
"loweringTargets":["browser","eve-native","tui"],
"ownership":"Ghostlight kernels own state; Eve lowers projections and commands."
},
"requiresPlugins":[{
"pluginId":"gamecult.heimdall.access",
"versionRange":"^1.0.0",
"availability":"required",
"requiredCapabilities":["auth.gate","auth.begin","auth.complete","auth.logout"]
}]
}],
"commands":[
{"command":COMMAND_BOUNDARY,"transport":"https-json","summary":"Canonical Ghostlight Eve command boundary."},
{"command":"ghostlight.native.player","transport":"cultnet.transport.rudp.v0","summary":"Loopback native access to the same actor-filtered surface and Eve command authority."},
{"command":"ghostlight.world.consumer","transport":"cultnet.transport.rudp.v0","summary":"Typed world-seed admission, external snapshots, and proposal exchange for game consumers."}
]
})
}
pub fn publish_snapshot(
&self,
campaigns: &[CampaignMeshSnapshot],
session_zeros: &[SessionZeroMeshSnapshot],
model_status: &ModelRuntimeStatus,
live_turn_pressure: usize,
) -> Result<Value> {
pub(crate) fn publish(&self, snapshot: Option<&WorldSnapshot>) -> Result<Value> {
let surface = eve::mesh_surface(snapshot);
let world_state = eve::world_state(snapshot);
let version = eve::surface_version(snapshot);
let updated_at = Utc::now().to_rfc3339();
let health = json!({
"schema":"ghostlight.service_health.v1",
"schema":"ghostlight.service_health.v2",
"status":"ok",
"campaigns":campaigns.len(),
"sessionZeros":session_zeros.len(),
"modelProvider":model_status,
"scheduler":{"live_turn_pressure":live_turn_pressure},
"worldState":world_state,
"surfaceVersion":version,
"updatedAtUtc":updated_at,
"runtime":self.identity.runtime_id.as_str(),
"runtime":self.identity.runtime_id,
"commit":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")
});
let catalog = json!({
"schema":"ghostlight.schema_catalog.v1",
"providerId":PROVIDER_ID,
"schemas":schema_catalog(),
"updatedAtUtc":updated_at
});
let advertisement = self.provider_advertisement(&updated_at);
let advertisement = provider_advertisement(&self.identity, &updated_at);
let mut node = self
.node
.lock()
.map_err(|_| anyhow::anyhow!("mesh lock poisoned"))?;
let mut remote_messages = Vec::new();
self.put_and_stage(
&mut node,
HEALTH_KEY,
&ServiceHealthRecord {
value: health.clone(),
},
&mut remote_messages,
)?;
self.put_and_stage(
&mut node,
ADVERTISEMENT_KEY,
@ -307,166 +159,13 @@ impl MeshPublisher {
)?;
self.put_and_stage(
&mut node,
"ghostlight:schema-catalog",
&SchemaCatalogRecord { value: catalog },
SURFACE_KEY,
&EveSurfaceRecord { value: surface },
&mut remote_messages,
)?;
for snapshot in campaigns {
let campaign = &snapshot.campaign;
let interface_version = campaign
.revision
.saturating_mul(1_000_000_000_000)
.saturating_add(
campaign
.resolution_policy
.resolution_epoch
.saturating_mul(1_000_000),
)
.saturating_add(campaign.resolution_policy.provider_configuration_epoch)
as i64;
if let Some(membership) = &snapshot.membership {
for member in membership.members.values().filter(|member| member.active) {
let surface = player_surface_for_actor(campaign, &member.actor_id);
let key = format!(
"eve:surface:ghostlight.campaign.{}.{}",
campaign.id, member.member_id
);
self.put_and_stage(
&mut node,
&key,
&EveSurfaceRecord { value: surface },
&mut remote_messages,
)?;
self.put_and_stage(
&mut node,
format!(
"eve:surface-state:ghostlight.campaign.{}.{}",
campaign.id, member.member_id
),
&EveSurfaceStateRecord {
provider_id: PROVIDER_ID.into(),
title: campaign.name.clone(),
version: interface_version,
updated_at: updated_at.clone(),
surface: player_surface_for_actor(campaign, &member.actor_id),
},
&mut remote_messages,
)?;
}
} else {
let surface = player_surface(campaign);
let key = format!("eve:surface:ghostlight.campaign.{}", campaign.id);
self.put_and_stage(
&mut node,
&key,
&EveSurfaceRecord { value: surface },
&mut remote_messages,
)?;
self.put_and_stage(
&mut node,
format!("eve:surface-state:ghostlight.campaign.{}", campaign.id),
&EveSurfaceStateRecord {
provider_id: PROVIDER_ID.into(),
title: campaign.name.clone(),
version: interface_version,
updated_at: updated_at.clone(),
surface: player_surface(campaign),
},
&mut remote_messages,
)?;
}
let operator = operator_surface(
campaign,
&snapshot.evidence,
&snapshot.commits,
&snapshot.stages,
&snapshot.strategic_ticks,
&snapshot.gestalt_receipts,
&snapshot.rejected,
&snapshot.resolution_plans,
&snapshot.cell_appraisals,
&snapshot.activity_outcomes,
&snapshot.resolution_controls,
live_turn_pressure,
);
self.put_and_stage(
&mut node,
format!("eve:operator:ghostlight.campaign.{}", campaign.id),
&EveSurfaceRecord {
value: operator.clone(),
},
&mut remote_messages,
)?;
self.put_and_stage(
&mut node,
format!("eve:operator-state:ghostlight.campaign.{}", campaign.id),
&EveSurfaceStateRecord {
provider_id: PROVIDER_ID.into(),
title: format!("{} operator", campaign.name),
version: interface_version,
updated_at: updated_at.clone(),
surface: operator,
},
&mut remote_messages,
)?;
}
for snapshot in session_zeros {
let key = format!(
"eve:surface:ghostlight.session-zero.{}.{}",
snapshot.session_zero_id, snapshot.member_id
);
self.put_and_stage(
&mut node,
&key,
&EveSurfaceRecord {
value: snapshot.surface.clone(),
},
&mut remote_messages,
)?;
self.put_and_stage(
&mut node,
format!(
"eve:surface-state:ghostlight.session-zero.{}.{}",
snapshot.session_zero_id, snapshot.member_id
),
&EveSurfaceStateRecord {
provider_id: PROVIDER_ID.into(),
title: snapshot.surface["title"]
.as_str()
.unwrap_or("Session Zero")
.into(),
version: snapshot.surface["version"].as_i64().unwrap_or_default(),
updated_at: updated_at.clone(),
surface: snapshot.surface.clone(),
},
&mut remote_messages,
)?;
}
node.flush()?;
drop(node);
if let Some(remote) = &self.remote {
remote.enqueue(remote_messages);
}
Ok(health)
}
pub fn health(&self) -> Result<Value> {
self.node
.lock()
.map_err(|_| anyhow::anyhow!("mesh lock poisoned"))?
.get_required::<ServiceHealthRecord>(HEALTH_KEY)
.map(|record| record.value)
}
pub fn publish_live_turn_pressure(&self, live_turn_pressure: usize) -> Result<Value> {
let mut node = self
.node
.lock()
.map_err(|_| anyhow::anyhow!("mesh lock poisoned"))?;
let mut health = node.get_required::<ServiceHealthRecord>(HEALTH_KEY)?.value;
health["scheduler"]["live_turn_pressure"] = json!(live_turn_pressure);
health["updatedAtUtc"] = json!(Utc::now().to_rfc3339());
let mut remote_messages = Vec::new();
// Health is the completion marker for this derived projection. A
// failed advertisement or surface write must leave the prior version
// visibly stale rather than publishing green first.
self.put_and_stage(
&mut node,
HEALTH_KEY,
@ -475,7 +174,6 @@ impl MeshPublisher {
},
&mut remote_messages,
)?;
node.flush()?;
drop(node);
if let Some(remote) = &self.remote {
remote.enqueue(remote_messages);
@ -483,13 +181,18 @@ impl MeshPublisher {
Ok(health)
}
pub fn operator_surface(&self, campaign_id: uuid::Uuid) -> Result<Value> {
pub(crate) fn health(&self) -> Result<Value> {
if self
.remote
.as_ref()
.is_some_and(|remote| !remote.is_alive())
{
anyhow::bail!("Odin projection worker stopped");
}
self.node
.lock()
.map_err(|_| anyhow::anyhow!("mesh lock poisoned"))?
.get_required::<EveSurfaceRecord>(&format!(
"eve:operator:ghostlight.campaign.{campaign_id}"
))
.try_lock()
.map_err(|_| anyhow::anyhow!("mesh projection is busy or its lock is poisoned"))?
.get_required::<ServiceHealthRecord>(HEALTH_KEY)
.map(|record| record.value)
}
@ -516,20 +219,88 @@ impl MeshPublisher {
}
}
pub(crate) fn provider_advertisement(identity: &MeshRuntimeIdentity, updated_at: &str) -> Value {
json!({
"schema":"gamecult.eve.provider_advertisement.v1",
"providerId":PROVIDER_ID,
"serviceId":identity.service_id,
"verseId":"gamecult.private",
"rootVerse":"gamecult",
"canonicalService":"ghostlight-dungeon",
"locatedService":identity.located_service,
"cultMeshAddress":"cultmesh://gamecult.private/ghostlight/providers/dungeon",
"title":"Ghostlight Dungeon",
"kind":"narrative.simulation",
"updatedAtUtc":updated_at,
"freshness":{"state":"live","lastSeenAtUtc":updated_at,"maxAgeMs":360000},
"schemas":[
"gamecult.eve.surface.v1",
"gamecult.eve.command_invocation.v1",
COMMAND_RESULT_SCHEMA,
"heimdall.access_gate_state.v1",
"ghostlight.world_state.foundation.v0"
],
"witnesses":[{
"kind":"source-commit",
"ref":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")
}],
"surfaces":[{
"surfaceId":SURFACE_ID,
"schema":"gamecult.eve.surface.v1",
"url":"/api/eve/surfaces/ghostlight.play",
"transport":"https-json",
"status":"available",
"surfaceKind":"subject-scoped-narrative",
"interactionModel":"typed-command-receipts",
"worldInteraction":{
"projectionKind":"owner-derived",
"stateSchemas":["ghostlight.world_state.foundation.v0"],
"commandBoundary":COMMAND_BOUNDARY,
"receiptSchema":COMMAND_RESULT_SCHEMA,
"loweringTargets":["browser","eve-native","tui"],
"ownership":"One Ghostlight WorldMailbox owns state; Eve lowers derived projections and commands."
},
"requiresPlugins":[{
"pluginId":"gamecult.heimdall.access",
"versionRange":"^1.0.0",
"availability":"required",
"requiredCapabilities":["auth.gate","auth.begin","auth.complete","auth.logout"]
}]
}],
"commands":[{
"command":COMMAND_BOUNDARY,
"transport":"https-json",
"summary":"Canonical Ghostlight Eve command boundary."
}]
})
}
impl RemoteReplication {
fn start(target: SocketAddr, runtime_id: String) -> Self {
fn start(target: SocketAddr, runtime_id: String) -> Result<Self> {
let pending = Arc::new((
Mutex::new(None::<Vec<cultnet_rs::CultNetMessage>>),
Condvar::new(),
));
let worker_pending = pending.clone();
let worker_runtime_id = runtime_id.clone();
let alive = Arc::new(AtomicBool::new(true));
let worker_alive = alive.clone();
thread::Builder::new()
.name("ghostlight-odin-rudp".into())
.spawn(move || loop {
.spawn(move || {
struct Liveness(Arc<AtomicBool>);
impl Drop for Liveness {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
let _liveness = Liveness(worker_alive);
loop {
let messages = {
let (lock, ready) = &*worker_pending;
let mut pending = lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let mut pending = lock
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
while pending.is_none() {
pending = ready
.wait(pending)
@ -541,21 +312,38 @@ impl RemoteReplication {
continue;
}
let options = remote_options(target, &worker_runtime_id);
if let Err(error) = publish_cultnet_messages_to_rudp_catalog(&messages, options) {
if let Err(error) =
publish_cultnet_messages_to_rudp_catalog(&messages, options)
{
tracing::warn!(
document_count = messages.len(),
%target,
%error,
"Odin RUDP batch publication failed; retained canonical local CultMesh projection"
"Odin publication failed; retaining the newest derived projection for retry"
);
let (lock, ready) = &*worker_pending;
let mut pending = lock
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if pending.is_none() {
*pending = Some(messages);
}
let _ = ready
.wait_timeout(pending, std::time::Duration::from_secs(2))
.unwrap_or_else(|poisoned| poisoned.into_inner());
}
})
.expect("Ghostlight RUDP replication worker must start");
Self {
}
})?;
Ok(Self {
target,
runtime_id,
pending,
}
alive,
})
}
fn is_alive(&self) -> bool {
self.alive.load(Ordering::Acquire)
}
fn options(&self) -> CultMeshRudpDocumentPublishOptions {
@ -578,161 +366,83 @@ fn remote_options(target: SocketAddr, runtime_id: &str) -> CultMeshRudpDocumentP
options
}
fn schema_catalog() -> Value {
json!({
"ghostlight.campaign.v1": schemars::schema_for!(Campaign),
"ghostlight.session_zero.v1": schemars::schema_for!(SessionZeroState),
"ghostlight.vault_source_manifest.v1": schemars::schema_for!(VaultSourceManifest),
"ghostlight.world_seed.v1": schemars::schema_for!(crate::consumer::WorldSeed),
"ghostlight.world_seed_admission_request.v1": schemars::schema_for!(crate::consumer::WorldSeedAdmissionRequest),
"ghostlight.world_seed_admission_receipt.v1": schemars::schema_for!(crate::consumer::WorldSeedAdmissionReceipt),
"ghostlight.external_subject_authority.v1": schemars::schema_for!(crate::consumer::ExternalSubjectAuthority),
"ghostlight.external_subject_snapshot.v1": schemars::schema_for!(crate::consumer::ExternalSubjectSnapshot),
"ghostlight.external_snapshot_receipt.v1": schemars::schema_for!(crate::consumer::ExternalSnapshotReceipt),
"ghostlight.external_world_proposal.v1": schemars::schema_for!(crate::consumer::ExternalWorldProposal),
"ghostlight.external_proposal_list_request.v1": schemars::schema_for!(crate::consumer::ExternalProposalListRequest),
"ghostlight.external_proposal_list.v1": schemars::schema_for!(crate::consumer::ExternalProposalList),
"ghostlight.external_proposal_acknowledgement.v1": schemars::schema_for!(crate::consumer::ExternalProposalAcknowledgement),
"ghostlight.external_proposal_receipt.v1": schemars::schema_for!(crate::consumer::ExternalProposalReceipt),
"ghostlight.world_newspaper_request.v3": schemars::schema_for!(crate::consumer::WorldNewspaperRequest),
"ghostlight.world_newspaper_issue.v3": schemars::schema_for!(crate::newspaper::WorldNewspaperIssue)
})
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn health_is_read_from_the_same_typed_mesh_record_that_is_published() {
let temp = tempdir().unwrap();
let publisher = MeshPublisher::open(temp.path().join("mesh.cc"), None).unwrap();
let model_status = fixture_model_status();
let written = publisher
.publish_snapshot(&[], &[], &model_status, 2)
.unwrap();
assert_eq!(publisher.health().unwrap(), written);
assert_eq!(written["scheduler"]["live_turn_pressure"], 2);
assert_eq!(written["modelProvider"]["provider"], "fixture");
assert!(written.get("deepseek").is_none());
let catalog = publisher
.node
.lock()
.unwrap()
.get_required::<SchemaCatalogRecord>("ghostlight:schema-catalog")
.unwrap();
let schemas = catalog.value["schemas"].as_object().unwrap();
assert_eq!(schemas.len(), 16);
assert!(schemas["ghostlight.campaign.v1"]["$schema"].is_string());
assert!(schemas["ghostlight.session_zero.v1"]["$schema"].is_string());
assert!(schemas["ghostlight.vault_source_manifest.v1"]["$schema"].is_string());
assert!(schemas["ghostlight.world_newspaper_request.v3"]["$schema"].is_string());
assert!(schemas["ghostlight.world_newspaper_issue.v3"]["$schema"].is_string());
assert!(!schemas.contains_key("ghostlight.persona_stage_receipt.v1"));
assert!(!schemas.contains_key("ghostlight.world_mutation.v1"));
drop(catalog);
drop(publisher);
let reopened = MeshPublisher::open(temp.path().join("mesh.cc"), None).unwrap();
assert_eq!(reopened.health().unwrap(), written);
}
#[test]
fn live_turn_pressure_updates_the_canonical_health_document_immediately() {
let temp = tempdir().unwrap();
let publisher = MeshPublisher::open(temp.path().join("mesh.cc"), None).unwrap();
publisher
.publish_snapshot(&[], &[], &fixture_model_status(), 0)
.unwrap();
let pressured = publisher.publish_live_turn_pressure(3).unwrap();
assert_eq!(pressured["scheduler"]["live_turn_pressure"], 3);
assert_eq!(publisher.health().unwrap(), pressured);
let idle = publisher.publish_live_turn_pressure(0).unwrap();
assert_eq!(idle["scheduler"]["live_turn_pressure"], 0);
assert_eq!(publisher.health().unwrap(), idle);
}
#[test]
fn unavailable_odin_cannot_take_away_the_local_projection() {
let temp = tempdir().unwrap();
let unavailable = "127.0.0.1:1".parse().unwrap();
let publisher =
MeshPublisher::open(temp.path().join("mesh.cc"), Some(unavailable)).unwrap();
let started = std::time::Instant::now();
let model_status = fixture_model_status();
let written = publisher
.publish_snapshot(&[], &[], &model_status, 0)
.expect("local projection remains writable while rendezvous is unavailable");
assert!(
started.elapsed() < std::time::Duration::from_millis(500),
"optional remote replication blocked local publication"
);
assert_eq!(publisher.health().unwrap(), written);
assert!(
publisher
.node
.lock()
.unwrap()
.get_required::<SchemaCatalogRecord>("ghostlight:schema-catalog")
.is_ok()
);
}
fn fixture_model_status() -> ModelRuntimeStatus {
ModelRuntimeStatus {
provider: "fixture".into(),
fast_model: "fixture-fast".into(),
balanced_model: "fixture-balanced".into(),
capable_model: "fixture-capable".into(),
readiness: "ready".into(),
}
}
#[test]
fn public_provider_advertises_one_subject_scoped_surface_and_heimdall_plugin() {
let temp = tempdir().unwrap();
let publisher = MeshPublisher::open_with_identity(
temp.path().join("mesh.cc"),
fn publishes_only_owner_derived_surface_and_health() {
let directory = tempfile::tempdir().unwrap();
let publisher = MeshPublisher::open(
directory.path().join("mesh-v2.cc"),
None,
MeshRuntimeIdentity {
runtime_id: "ghostlight-test".into(),
service_id: "ghostlight-test".into(),
located_service: "fixture".into(),
},
MeshRuntimeIdentity::default(),
)
.unwrap();
let advertisement = publisher.provider_advertisement("2026-08-22T00:00:00Z");
let surfaces = advertisement["surfaces"].as_array().unwrap();
assert_eq!(surfaces.len(), 1);
assert_eq!(surfaces[0]["surfaceId"], SURFACE_ID);
let health = publisher.publish(None).unwrap();
assert_eq!(health["worldState"], "empty");
assert_eq!(health["surfaceVersion"], 0);
assert_eq!(publisher.health().unwrap(), health);
let node = publisher.node.lock().unwrap();
assert_eq!(
surfaces[0]["worldInteraction"]["commandBoundary"],
COMMAND_BOUNDARY
);
assert_eq!(
surfaces[0]["worldInteraction"]["receiptSchema"],
COMMAND_RESULT_SCHEMA
);
assert_eq!(
surfaces[0]["worldInteraction"]["nativeCommandBoundary"]["endpoint"],
"127.0.0.1:4102"
);
assert_eq!(
surfaces[0]["worldInteraction"]["nativeCommandBoundary"]["exposure"],
"loopback-only"
);
assert_eq!(
surfaces[0]["requiresPlugins"][0]["pluginId"],
"gamecult.heimdall.access"
node.get_required::<EveSurfaceRecord>(SURFACE_KEY)
.unwrap()
.value,
eve::mesh_surface(None)
);
assert!(
advertisement.to_string().find("account_hash").is_none(),
"public advertisement must remain subject-agnostic"
node.get_required::<EveProviderAdvertisementRecord>(ADVERTISEMENT_KEY)
.is_ok()
);
assert!(node.get_required::<ServiceHealthRecord>(HEALTH_KEY).is_ok());
}
#[test]
fn unavailable_odin_cannot_block_local_publication() {
let directory = tempfile::tempdir().unwrap();
let publisher = MeshPublisher::open(
directory.path().join("mesh-v2.cc"),
Some("127.0.0.1:1".parse().unwrap()),
MeshRuntimeIdentity::default(),
)
.unwrap();
let started = std::time::Instant::now();
publisher.publish(None).unwrap();
assert!(started.elapsed() < std::time::Duration::from_millis(500));
assert_eq!(publisher.health().unwrap()["worldState"], "empty");
}
#[test]
fn stopped_odin_worker_makes_runtime_health_non_green() {
let directory = tempfile::tempdir().unwrap();
let publisher = MeshPublisher::open(
directory.path().join("mesh-v2.cc"),
Some("127.0.0.1:1".parse().unwrap()),
MeshRuntimeIdentity::default(),
)
.unwrap();
publisher.publish(None).unwrap();
publisher
.remote
.as_ref()
.unwrap()
.alive
.store(false, Ordering::Release);
assert!(publisher.health().is_err());
}
#[test]
fn advertisement_has_one_surface_and_one_command_boundary() {
let directory = tempfile::tempdir().unwrap();
let publisher = MeshPublisher::open(
directory.path().join("mesh-v2.cc"),
None,
MeshRuntimeIdentity::default(),
)
.unwrap();
let advertisement = publisher.provider_advertisement("2026-09-01T00:00:00Z");
assert_eq!(advertisement["surfaces"].as_array().unwrap().len(), 1);
assert_eq!(advertisement["commands"].as_array().unwrap().len(), 1);
assert_eq!(advertisement["surfaces"][0]["surfaceId"], SURFACE_ID);
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,124 +0,0 @@
use crate::{
model::{DeepSeekPort, ModelPort, ModelRuntimeStatus, OpenRouterPort},
model_connector::CodexConnectorModelPort,
};
use anyhow::{Context, Result, bail};
use std::{
net::SocketAddr,
path::{Path, PathBuf},
sync::Arc,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ModelRuntimeSelection {
pub provider: String,
pub fast_model: String,
pub balanced_model: String,
pub capable_model: String,
pub credential_path: PathBuf,
pub connector_endpoint: SocketAddr,
pub runtime_id: String,
pub connector_max_concurrent_requests: usize,
}
impl ModelRuntimeSelection {
pub fn from_environment(runtime_root: impl AsRef<Path>) -> Result<Self> {
let provider = std::env::var("GHOSTLIGHT_MODEL_PROVIDER")
.unwrap_or_else(|_| "deepseek".into())
.to_ascii_lowercase();
let (
default_fast_model,
default_balanced_model,
default_capable_model,
default_secret_name,
) = match provider.as_str() {
"deepseek" => (
"deepseek-v4-flash",
"deepseek-v4-pro",
"deepseek-v4-pro",
"deepseek.dpapi",
),
"openrouter" => (
"stealth/ox-alpha",
"stealth/ox-alpha",
"stealth/ox-alpha",
"openrouter.key",
),
"codex-connector" => (
"gpt-5.6-luna",
"gpt-5.6-terra",
"gpt-5.6-luna",
"codex-connector.key",
),
unsupported => bail!("unsupported model provider {unsupported}"),
};
Ok(Self {
provider,
fast_model: std::env::var("GHOSTLIGHT_MODEL_FAST")
.unwrap_or_else(|_| default_fast_model.into()),
balanced_model: std::env::var("GHOSTLIGHT_MODEL_BALANCED")
.unwrap_or_else(|_| default_balanced_model.into()),
capable_model: std::env::var("GHOSTLIGHT_MODEL_CAPABLE")
.unwrap_or_else(|_| default_capable_model.into()),
credential_path: std::env::var_os("GHOSTLIGHT_MODEL_CREDENTIAL")
.map(PathBuf::from)
.unwrap_or_else(|| {
runtime_root
.as_ref()
.join("secrets")
.join(default_secret_name)
}),
connector_endpoint: std::env::var("GHOSTLIGHT_MODEL_CONNECTOR")
.unwrap_or_else(|_| "127.0.0.1:4103".to_string())
.parse()
.context("GHOSTLIGHT_MODEL_CONNECTOR must be a socket address")?,
runtime_id: std::env::var("GHOSTLIGHT_RUNTIME_ID")
.unwrap_or_else(|_| "ghostlight-dungeon-yggdrasil".to_string()),
connector_max_concurrent_requests: std::env::var(
"GHOSTLIGHT_CODEX_CONNECTOR_MAX_CONCURRENT_REQUESTS",
)
.unwrap_or_else(|_| "8".to_string())
.parse::<usize>()
.context("GHOSTLIGHT_CODEX_CONNECTOR_MAX_CONCURRENT_REQUESTS must be an integer")?,
})
}
pub fn status(&self, readiness: impl Into<String>) -> ModelRuntimeStatus {
ModelRuntimeStatus {
provider: self.provider.clone(),
fast_model: self.fast_model.clone(),
balanced_model: self.balanced_model.clone(),
capable_model: self.capable_model.clone(),
readiness: readiness.into(),
}
}
pub fn open(&self) -> Result<Option<Arc<dyn ModelPort>>> {
if !self.credential_path.is_file() {
return Ok(None);
}
let provider: Arc<dyn ModelPort> = match self.provider.as_str() {
"deepseek" => Arc::new(DeepSeekPort::from_runtime_secret_with_models(
&self.credential_path,
self.fast_model.clone(),
self.capable_model.clone(),
)?),
"openrouter" => Arc::new(OpenRouterPort::from_runtime_secret(
&self.credential_path,
self.fast_model.clone(),
self.capable_model.clone(),
)?),
"codex-connector" => Arc::new(CodexConnectorModelPort::from_runtime_secret(
self.connector_endpoint,
&self.credential_path,
self.runtime_id.clone(),
self.fast_model.clone(),
self.balanced_model.clone(),
self.capable_model.clone(),
self.connector_max_concurrent_requests,
)?),
unsupported => bail!("unsupported model provider {unsupported}"),
};
Ok(Some(provider))
}
}

View file

@ -1,608 +0,0 @@
use super::{
AppState, EveCommandInvocation, complete_native_authentication, eve_command_for_transport,
surface,
};
use anyhow::{Context, Result, bail};
use axum::{
extract::State,
http::{HeaderMap, HeaderValue, header},
response::Response,
};
use base64::{Engine, engine::general_purpose::STANDARD};
use cultnet_rs::{
CULTNET_OPERATION_CONNECTION_ID, CultNetMessage, CultNetRudpServerEvent, CultNetRudpServerHub,
CultNetRudpServerHubOptions, CultNetRudpServerSessionContext, CultNetWireContract,
decode_cultnet_message_from_slice,
};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::{
net::{SocketAddr, UdpSocket},
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
mpsc,
},
time::Duration,
};
pub const NATIVE_ENDPOINT: &str = "127.0.0.1:4102";
pub const NATIVE_SERVICE_ID: &str = "ghostlight.native.player";
pub const NATIVE_RUNTIME_ID: &str = "ghostlight-dungeon-yggdrasil";
pub const NATIVE_AUTH_BEGIN: &str = "ghostlight.auth.begin";
pub const NATIVE_AUTH_COMPLETE: &str = "ghostlight.auth.complete";
pub const NATIVE_SURFACE_GET: &str = "ghostlight.surface.get";
pub const NATIVE_EVE_INVOKE: &str = "ghostlight.eve.invoke";
const MAX_IN_FLIGHT: usize = 64;
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NativeAuthBeginCommand {
pub schema: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NativeAuthCompleteCommand {
pub schema: String,
pub handle: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NativeSurfaceGetCommand {
pub schema: String,
pub session_token: String,
pub invite: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NativeEveInvokeCommand {
pub schema: String,
pub session_token: String,
pub invocation: serde_json::Value,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeAuthCompletionReceipt {
pub schema: String,
pub status: String,
pub message: String,
pub session_token: Option<String>,
pub refresh_expires_at: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct NativeFailure {
schema: String,
code: String,
message: String,
}
struct CompletedResponse {
session: CultNetRudpServerSessionContext,
response: CultNetMessage,
}
pub fn start(state: AppState) -> Result<()> {
let address: SocketAddr = NATIVE_ENDPOINT.parse()?;
let socket = UdpSocket::bind(address)
.with_context(|| format!("bind Ghostlight native CultNet boundary at {address}"))?;
socket.set_nonblocking(true)?;
let mut options = CultNetRudpServerHubOptions::new(
state.mesh.identity().runtime_id.clone(),
socket,
CULTNET_OPERATION_CONNECTION_ID,
);
options.max_fragment_bytes = Some(2_048);
options.max_pending_reliable_packets = Some(4_096);
let hub = CultNetRudpServerHub::new(options)?;
let runtime = tokio::runtime::Handle::current();
std::thread::Builder::new()
.name("ghostlight-native-cultmesh".into())
.spawn(move || {
if let Err(error) = run_server(hub, state, runtime) {
tracing::error!(%error, "Ghostlight native CultMesh boundary stopped");
std::process::exit(1);
}
})?;
Ok(())
}
fn run_server(
mut hub: CultNetRudpServerHub,
state: AppState,
runtime: tokio::runtime::Handle,
) -> Result<()> {
let (completed_tx, completed_rx) = mpsc::channel::<CompletedResponse>();
let in_flight = Arc::new(AtomicUsize::new(0));
loop {
while let Ok(completed) = completed_rx.try_recv() {
in_flight.fetch_sub(1, Ordering::SeqCst);
let (message_id, payload_bytes) = response_diagnostics(&completed.response);
match hub.session(completed.session.remote_addr) {
Some(active)
if active.session_generation == completed.session.session_generation =>
{
hub.send_schema_message(&completed.session, &completed.response)?;
tracing::info!(
%message_id,
payload_bytes,
session_generation = completed.session.session_generation,
remote_addr = %completed.session.remote_addr,
"Ghostlight native boundary queued completed operation response"
);
}
Some(active) => tracing::warn!(
%message_id,
completed_session_generation = completed.session.session_generation,
active_session_generation = active.session_generation,
remote_addr = %completed.session.remote_addr,
"Ghostlight native boundary fenced a completed response from a replaced session"
),
None => tracing::warn!(
%message_id,
session_generation = completed.session.session_generation,
remote_addr = %completed.session.remote_addr,
"Ghostlight native boundary could not deliver a completed response because its session vanished"
),
}
}
if let Some(event) = hub.receive_event_once()? {
let CultNetRudpServerEvent::Frame { session, frame } = event else {
hub.poll_resends()?;
continue;
};
if frame.channel_id != "schema" {
continue;
}
let request = match decode_cultnet_message_from_slice(
&frame.payload,
CultNetWireContract::CultNetSchemaV0,
) {
Ok(request @ CultNetMessage::OperationRequest { .. }) => request,
Ok(_) => continue,
Err(error) => {
tracing::warn!(%error, "Ghostlight native boundary rejected malformed CultNet payload");
continue;
}
};
if in_flight.load(Ordering::SeqCst) >= MAX_IN_FLIGHT {
let response = failure_response(
&request,
"busy",
"Ghostlight is already processing the maximum native command pressure.",
)?;
hub.send_schema_message(&session, &response)?;
continue;
}
in_flight.fetch_add(1, Ordering::SeqCst);
let tx = completed_tx.clone();
let request_state = state.clone();
runtime.spawn(async move {
let response = handle_operation(request_state, request).await;
let _ = tx.send(CompletedResponse { session, response });
});
}
hub.poll_resends()?;
std::thread::sleep(Duration::from_millis(5));
}
}
fn response_diagnostics(response: &CultNetMessage) -> (String, usize) {
match response {
CultNetMessage::OperationResponse {
message_id,
payload,
..
} => (message_id.clone(), payload.len()),
_ => ("non-operation-response".into(), 0),
}
}
pub(super) async fn handle_operation(state: AppState, request: CultNetMessage) -> CultNetMessage {
match handle_operation_inner(state, &request).await {
Ok(response) => response,
Err(error) => {
tracing::warn!(%error, "Ghostlight denied a native CultMesh operation");
failure_response(
&request,
"command-denied",
"Ghostlight denied the typed native operation without changing world state.",
)
.unwrap_or_else(|_| bare_failure_response(&request))
}
}
}
async fn handle_operation_inner(
state: AppState,
request: &CultNetMessage,
) -> Result<CultNetMessage> {
let CultNetMessage::OperationRequest {
service_id,
operation,
payload_schema,
payload_encoding,
target_runtime_id,
..
} = request
else {
bail!("native boundary accepts only operation requests");
};
if payload_encoding != "messagepack-base64"
|| (service_id != NATIVE_SERVICE_ID
&& service_id != ghostlight_dungeon::consumer::WORLD_CONSUMER_SERVICE_ID)
{
bail!("native request does not match the advertised service contract");
}
if target_runtime_id
.as_deref()
.is_some_and(|target| target != state.mesh.identity().runtime_id)
{
bail!("native request targets another runtime");
}
if service_id == ghostlight_dungeon::consumer::WORLD_CONSUMER_SERVICE_ID {
return match operation.as_str() {
ghostlight_dungeon::consumer::ADMIT_WORLD_OPERATION => {
require_schema(payload_schema, "ghostlight.world_seed_admission_request.v1")?;
let command: ghostlight_dungeon::consumer::WorldSeedAdmissionRequest =
decode_request(request)?;
require_schema(
&command.schema,
"ghostlight.world_seed_admission_request.v1",
)?;
let (_, receipt) = state.registry.admit_world_seed(command).await?;
success_response(
request,
"ghostlight.world_seed_admission_receipt.v1",
&receipt,
)
}
ghostlight_dungeon::consumer::APPLY_EXTERNAL_SNAPSHOT_OPERATION => {
require_schema(payload_schema, "ghostlight.external_subject_snapshot.v1")?;
let command: ghostlight_dungeon::consumer::ExternalSubjectSnapshot =
decode_request(request)?;
require_schema(&command.schema, "ghostlight.external_subject_snapshot.v1")?;
let receipt = state
.registry
.apply_external_subject_snapshot(command)
.await?;
success_response(request, "ghostlight.external_snapshot_receipt.v1", &receipt)
}
ghostlight_dungeon::consumer::LIST_EXTERNAL_PROPOSALS_OPERATION => {
require_schema(
payload_schema,
"ghostlight.external_proposal_list_request.v1",
)?;
let command: ghostlight_dungeon::consumer::ExternalProposalListRequest =
decode_request(request)?;
require_schema(
&command.schema,
"ghostlight.external_proposal_list_request.v1",
)?;
let proposals = state.registry.list_external_proposals(command).await?;
success_response(request, "ghostlight.external_proposal_list.v1", &proposals)
}
ghostlight_dungeon::consumer::ACKNOWLEDGE_EXTERNAL_PROPOSAL_OPERATION => {
require_schema(
payload_schema,
"ghostlight.external_proposal_acknowledgement.v1",
)?;
let command: ghostlight_dungeon::consumer::ExternalProposalAcknowledgement =
decode_request(request)?;
require_schema(
&command.schema,
"ghostlight.external_proposal_acknowledgement.v1",
)?;
let receipt = state
.registry
.acknowledge_external_proposal(command)
.await?;
success_response(request, "ghostlight.external_proposal_receipt.v1", &receipt)
}
ghostlight_dungeon::consumer::COMPOSE_NEWSPAPER_OPERATION => {
require_schema(payload_schema, "ghostlight.world_newspaper_request.v3")?;
let command: ghostlight_dungeon::consumer::WorldNewspaperRequest =
decode_request(request)?;
require_schema(&command.schema, "ghostlight.world_newspaper_request.v3")?;
let model = state
.model
.as_deref()
.ok_or_else(|| anyhow::anyhow!("newspaper editor is unavailable"))?;
let issue = state
.registry
.compose_world_newspaper(command, model)
.await?;
success_response(request, "ghostlight.world_newspaper_issue.v3", &issue)
}
_ => bail!("world consumer operation is not advertised by Ghostlight"),
};
}
match operation.as_str() {
NATIVE_AUTH_BEGIN => {
require_schema(payload_schema, "ghostlight.native_auth_begin.v1")?;
let command: NativeAuthBeginCommand = decode_request(request)?;
require_schema(&command.schema, "ghostlight.native_auth_begin.v1")?;
let receipt = state.heimdall.begin(message_id(request)?).await?;
success_response(request, "heimdall.auth_begin_receipt.v1", &receipt)
}
NATIVE_AUTH_COMPLETE => {
require_schema(payload_schema, "ghostlight.native_auth_complete.v1")?;
let command: NativeAuthCompleteCommand = decode_request(request)?;
require_schema(&command.schema, "ghostlight.native_auth_complete.v1")?;
if command.handle.trim().is_empty() {
bail!("native auth completion omitted its opaque handle");
}
let receipt =
complete_native_authentication(&state, &command.handle, message_id(request)?)
.await?;
success_response(
request,
"ghostlight.native_auth_completion_receipt.v1",
&receipt,
)
}
NATIVE_SURFACE_GET => {
require_schema(payload_schema, "ghostlight.native_surface_get.v1")?;
let command: NativeSurfaceGetCommand = decode_request(request)?;
require_schema(&command.schema, "ghostlight.native_surface_get.v1")?;
let headers = session_headers(&command.session_token)?;
let response = surface(headers, State(state), command.invite.as_deref()).await;
let value = response_json(response).await?;
success_response(request, "gamecult.eve.surface.v1", &value)
}
NATIVE_EVE_INVOKE => {
require_schema(payload_schema, "ghostlight.native_eve_invocation.v1")?;
let command: NativeEveInvokeCommand = decode_request(request)?;
require_schema(&command.schema, "ghostlight.native_eve_invocation.v1")?;
let headers = session_headers(&command.session_token)?;
let invocation: EveCommandInvocation = serde_json::from_value(command.invocation)?;
let response =
eve_command_for_transport(headers, state, invocation, "cultnet-rudp").await;
let value = response_json(response).await?;
success_response(request, "gamecult.eve.command_result.v1", &value)
}
_ => bail!("native operation is not advertised by Ghostlight"),
}
}
fn require_schema(actual: &str, expected: &str) -> Result<()> {
if actual != expected {
bail!("native payload schema does not match the operation");
}
Ok(())
}
fn session_headers(session_token: &str) -> Result<HeaderMap> {
if session_token.trim().is_empty() || session_token.len() > 256 {
bail!("native session token is malformed");
}
let mut headers = HeaderMap::new();
headers.insert(
header::COOKIE,
HeaderValue::from_str(&format!("ghostlight_session={session_token}"))?,
);
Ok(headers)
}
async fn response_json(response: Response) -> Result<serde_json::Value> {
if !response.status().is_success() {
bail!("Ghostlight product boundary rejected the authenticated request");
}
let bytes = axum::body::to_bytes(response.into_body(), 4 * 1024 * 1024).await?;
Ok(serde_json::from_slice(&bytes)?)
}
fn decode_request<T: DeserializeOwned>(request: &CultNetMessage) -> Result<T> {
let CultNetMessage::OperationRequest { payload, .. } = request else {
bail!("expected operation request");
};
Ok(rmp_serde::from_slice(&STANDARD.decode(payload)?)?)
}
fn success_response(
request: &CultNetMessage,
payload_schema: &str,
payload: &impl Serialize,
) -> Result<CultNetMessage> {
operation_response(request, "accepted", payload_schema, payload, Vec::new())
}
fn failure_response(request: &CultNetMessage, code: &str, message: &str) -> Result<CultNetMessage> {
operation_response(
request,
"denied",
"ghostlight.native_failure.v1",
&NativeFailure {
schema: "ghostlight.native_failure.v1".into(),
code: code.into(),
message: message.into(),
},
vec![message.into()],
)
}
fn bare_failure_response(request: &CultNetMessage) -> CultNetMessage {
let (message_id, service_id, operation) = match request {
CultNetMessage::OperationRequest {
message_id,
service_id,
operation,
..
} => (message_id.clone(), service_id.clone(), operation.clone()),
_ => (
uuid::Uuid::new_v4().to_string(),
NATIVE_SERVICE_ID.into(),
"unknown".into(),
),
};
CultNetMessage::OperationResponse {
message_id,
service_id,
operation,
status: "denied".into(),
payload_schema: "ghostlight.native_failure.v1".into(),
payload_encoding: "messagepack-base64".into(),
payload: String::new(),
diagnostics: vec!["Ghostlight denied the malformed native request.".into()],
source_runtime_id: Some(NATIVE_RUNTIME_ID.into()),
}
}
fn operation_response(
request: &CultNetMessage,
status: &str,
payload_schema: &str,
payload: &impl Serialize,
diagnostics: Vec<String>,
) -> Result<CultNetMessage> {
let CultNetMessage::OperationRequest {
message_id,
service_id,
operation,
..
} = request
else {
bail!("expected operation request");
};
Ok(CultNetMessage::OperationResponse {
message_id: message_id.clone(),
service_id: service_id.clone(),
operation: operation.clone(),
status: status.into(),
payload_schema: payload_schema.into(),
payload_encoding: "messagepack-base64".into(),
payload: STANDARD.encode(rmp_serde::to_vec_named(payload)?),
diagnostics,
source_runtime_id: Some(NATIVE_RUNTIME_ID.into()),
})
}
fn message_id(request: &CultNetMessage) -> Result<&str> {
let CultNetMessage::OperationRequest { message_id, .. } = request else {
bail!("expected operation request");
};
Ok(message_id)
}
#[cfg(test)]
mod tests {
use super::*;
use cultnet_rs::{
CULTNET_OPERATION_CONNECTION_ID, CultNetRudpSocketTransportConnection,
CultNetRudpSocketTransportOptions,
};
use std::time::Duration;
#[test]
fn native_session_payload_rejects_authority_fields() {
let payload = serde_json::json!({
"schema":"ghostlight.native_eve_invocation.v1",
"sessionToken":"opaque",
"invocation":{
"schema":"gamecult.eve.command_invocation.v1",
"providerId":"gamecult.ghostlight.dungeon",
"surfaceId":"ghostlight.play",
"operation":{"operationId":"world.speak","schemaId":"ghostlight.world_speak.v1","idempotencyKey":"one","routeHint":{"sourceVersion":1,"transport":"cultnet-rudp"}},
"payload":{"actor_id":"npc"},
"issuedAt":"2026-08-23T00:00:00Z",
"clientId":"native-test",
"commandBoundary":"ghostlight.eve.commands",
"receiptSchema":"gamecult.eve.command_result.v1"
}
});
let command = serde_json::from_value::<NativeEveInvokeCommand>(payload).unwrap();
assert!(super::super::contains_authority_field(
&command.invocation["payload"]
));
}
#[test]
fn native_newspaper_operation_rejects_the_retired_v1_schema() {
assert!(
require_schema(
"ghostlight.world_newspaper_request.v1",
"ghostlight.world_newspaper_request.v3"
)
.is_err()
);
assert!(
require_schema(
"ghostlight.world_newspaper_request.v3",
"ghostlight.world_newspaper_request.v3"
)
.is_ok()
);
}
#[test]
fn native_transport_delivers_large_response_after_long_keepalive_only_operation() {
let server_socket = UdpSocket::bind("127.0.0.1:0").unwrap();
server_socket
.set_read_timeout(Some(Duration::from_millis(5)))
.unwrap();
let server_addr = server_socket.local_addr().unwrap();
let mut hub_options = CultNetRudpServerHubOptions::new(
NATIVE_RUNTIME_ID,
server_socket,
CULTNET_OPERATION_CONNECTION_ID,
);
hub_options.max_fragment_bytes = Some(2_048);
hub_options.max_pending_reliable_packets = Some(4_096);
let mut hub = CultNetRudpServerHub::new(hub_options).unwrap();
let client_socket = UdpSocket::bind("127.0.0.1:0").unwrap();
client_socket
.set_read_timeout(Some(Duration::from_millis(5)))
.unwrap();
let mut client_options = CultNetRudpSocketTransportOptions::client(
"ghostlight-native-test",
client_socket,
server_addr,
CULTNET_OPERATION_CONNECTION_ID,
);
client_options.max_fragment_bytes = Some(2_048);
client_options.max_pending_reliable_packets = Some(4_096);
let mut client = CultNetRudpSocketTransportConnection::new(client_options).unwrap();
client.connect(b"long-operation-session".to_vec()).unwrap();
let session = (0..20)
.find_map(|_| match hub.receive_event_once().unwrap() {
Some(CultNetRudpServerEvent::Connected { session }) => Some(session),
_ => None,
})
.expect("server did not accept native test connection");
client.receive_once().unwrap();
assert!(client.connected());
for heartbeat in 0..64_u32 {
client.ping(heartbeat.to_be_bytes().to_vec()).unwrap();
assert!(hub.receive_event_once().unwrap().is_none());
assert!(client.receive_once().unwrap().is_none());
}
assert_eq!(hub.session(session.remote_addr), Some(&session));
let response = CultNetMessage::OperationResponse {
message_id: "long-operation".into(),
service_id: NATIVE_SERVICE_ID.into(),
operation: NATIVE_EVE_INVOKE.into(),
status: "accepted".into(),
payload_schema: "gamecult.eve.command_result.v1".into(),
payload_encoding: "messagepack-base64".into(),
payload: "x".repeat(256_000),
diagnostics: vec![],
source_runtime_id: Some(NATIVE_RUNTIME_ID.into()),
};
hub.send_schema_message(&session, &response).unwrap();
let received = (0..4_000).find_map(|_| {
let message = client.receive_schema_message_once().unwrap();
let _ = hub.receive_event_once().unwrap();
hub.poll_resends().unwrap();
message
});
assert_eq!(received, Some(response));
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,848 +0,0 @@
use crate::{
domain::{
Campaign, GestaltMaterializationReceipt, RejectedProposalReceipt, StrategicTickReceipt,
VaultEvidenceReceipt, WorldCommitReceipt,
},
model::ModelStageReceipt,
};
use serde_json::{Value, json};
pub const CAMPAIGN_REVISION_SCALE: u64 = 1_000_000_000_000;
pub fn campaign_interface_version(campaign: &Campaign) -> u64 {
campaign
.revision
.saturating_mul(CAMPAIGN_REVISION_SCALE)
.saturating_add(
campaign
.resolution_policy
.resolution_epoch
.saturating_mul(1_000_000),
)
.saturating_add(campaign.resolution_policy.provider_configuration_epoch)
}
pub fn rebase_campaign_surface_revision(source_version: u64, campaign_revision: u64) -> u64 {
campaign_revision
.saturating_mul(CAMPAIGN_REVISION_SCALE)
.saturating_add(source_version % CAMPAIGN_REVISION_SCALE)
}
pub fn player_surface(campaign: &Campaign) -> Value {
player_surface_for_actor(campaign, &campaign.player_actor_id)
}
pub fn player_surface_for_actor(campaign: &Campaign, viewer_actor_id: &str) -> Value {
let interface_version = campaign_interface_version(campaign);
let story = story_nodes(campaign);
let player = &campaign.actors[viewer_actor_id];
let location = &campaign.locations[&player.location_id];
let mut present_characters = campaign
.actors
.values()
.filter(|actor| actor.id != viewer_actor_id && actor.location_id == player.location_id)
.map(|actor| actor.name.clone())
.collect::<Vec<_>>();
present_characters.sort();
let mut local_populations = campaign
.gestalts
.values()
.filter(|gestalt| {
campaign
.agency_profiles
.get(&gestalt.id)
.is_some_and(|profile| profile.location_ids.contains(&player.location_id))
})
.map(|gestalt| gestalt.name.clone())
.collect::<Vec<_>>();
local_populations.sort();
let scene_presence = format!(
"Present characters: {}\nLocal populations: {}",
if present_characters.is_empty() {
"none".into()
} else {
present_characters.join(", ")
},
if local_populations.is_empty() {
"none".into()
} else {
local_populations.join(", ")
},
);
let relationships = if player.relationships.is_empty() {
"none".into()
} else {
player
.relationships
.iter()
.map(|(subject_id, relationship)| {
let display_name = campaign
.actors
.get(subject_id)
.map(|actor| actor.name.as_str())
.or_else(|| {
campaign
.institutions
.get(subject_id)
.map(|institution| institution.name.as_str())
})
.or_else(|| {
campaign
.gestalts
.get(subject_id)
.map(|gestalt| gestalt.name.as_str())
})
.or_else(|| {
subject_id
.strip_prefix("member:")
.and_then(|member_id| campaign.gestalt_members.get(member_id))
.map(|member| member.name.as_str())
})
.unwrap_or(subject_id);
format!("{display_name}: {relationship}")
})
.collect::<Vec<_>>()
.join(", ")
};
let player_profile = campaign.agency_profiles.get(viewer_actor_id);
let information_channels = player_profile
.map(|profile| join(&profile.information_channels))
.unwrap_or_else(|| "none".into());
let ledger = format!(
"Capabilities: {}\nEquipment: {}\nConditions: {}\nObligations: {}\nRelationships: {}\nKnown facts: {}\nInformation access: {}",
join(&player.capabilities),
join(&player.equipment),
join(&player.conditions),
join(&player.obligations),
relationships,
join(&player.knowledge),
information_channels,
);
let accessible_channels = player_profile.map(|profile| &profile.information_channels);
let accessible_news = campaign
.news
.iter()
.filter(|item| accessible_channels.is_some_and(|channels| channels.contains(&item.channel)))
.collect::<Vec<_>>();
let reported_event_ids = accessible_news
.iter()
.flat_map(|item| item.event_ids.iter().cloned())
.collect::<std::collections::BTreeSet<_>>();
let mut news = campaign
.events
.iter()
.rev()
.filter(|event| !reported_event_ids.contains(&event.id))
.filter(|event| {
event.kind != "reaction_wave"
&& event.kind != "group_travel"
&& (autonomous_strategic_event(event)
|| !event
.actor_ids
.iter()
.any(|actor_id| actor_id == viewer_actor_id))
})
.filter(|event| {
player_profile.is_some_and(|profile| {
crate::scheduler::subject_perceives_event(
viewer_actor_id,
&profile.location_ids,
&profile.information_channels,
event,
)
})
})
.take(12)
.map(|event| json!({"id":format!("observed:{}",event.id),"kind":"text","props":{"value":format!("[observed] {}",event.summary)},"children":[]}))
.collect::<Vec<_>>();
news.extend(accessible_news.into_iter().map(|item|json!({"id":item.id,"kind":"text","props":{"value":format!("[{}] {}",item.channel,item.headline)},"children":[]})));
let effective_budget = campaign
.resolution_cover
.as_ref()
.map(|cover| cover.effective_budget)
.unwrap_or(campaign.resolution_policy.active_cell_budget);
let strategic_wait_minutes = u32::from(campaign.tick_hours).saturating_mul(60);
let mut children = vec![
json!({"id":"dungeon.status","kind":"card","props":{"title":format!("{} · revision {} · {}",campaign.name,campaign.revision,campaign.world_time)},"children":[]}),
json!({"id":"dungeon.location","kind":"card","props":{"title":format!("{} · {}",location.name,player.name)},"children":[]}),
json!({"id":"dungeon.scene-presence","kind":"card","props":{"title":"Scene presence"},"children":[{"id":"dungeon.scene-presence.text","kind":"text","props":{"value":scene_presence},"children":[]}]}),
json!({"id":"dungeon.ledger","kind":"card","props":{"title":"Character ledger"},"children":[{"id":"dungeon.ledger.text","kind":"text","props":{"value":ledger},"children":[]}]}),
json!({"id":"dungeon.resolution","kind":"card","props":{"title":format!("World resolution · {} configured / {} effective",campaign.resolution_policy.active_cell_budget,effective_budget)},"children":[{"id":"dungeon.resolution.text","kind":"text","props":{"value":format!("Resolution epoch {} · {} pins · {} temporary overage",campaign.resolution_policy.resolution_epoch,campaign.resolution_pins.len(),campaign.resolution_cover.as_ref().map(|cover| cover.mandatory_overage).unwrap_or(0))},"children":[]}]}),
json!({"id":"dungeon.news","kind":"card","props":{"title":"Accessible news and rumors"},"children":news}),
json!({"id":"dungeon.transcript","kind":"card","props":{"title":"Story"},"children":story}),
json!({"id":"dungeon.speech","kind":"control.input.textarea","props":{"label":"Say something","rows":3,"placeholder":"Your character's exact words"},"stateBindings":[local_draft("text","string")],"children":[]}),
command_control(
"dungeon.speak",
"Speak",
"world.speak",
json!({"expected_revision":campaign.revision}),
&["text"],
),
json!({"id":"dungeon.attempt.description","kind":"control.input.textarea","props":{"label":"What do you try?","rows":4,"placeholder":"Describe the attempt, not a completed fact."},"stateBindings":[local_draft("description","string")],"children":[]}),
json!({"id":"dungeon.attempt.effect","kind":"control.input.text","props":{"label":"What effect do you want?","placeholder":"The concrete outcome you are trying to cause"},"stateBindings":[local_draft("intended_effect","string")],"children":[]}),
command_control(
"dungeon.assess",
"Assess stakes",
"world.assess",
json!({"expected_revision":campaign.revision}),
&["description", "intended_effect"],
),
json!({"id":"dungeon.wait.minutes","kind":"control.input.number","props":{"label":format!("Wait minutes ({} max)",strategic_wait_minutes),"value":30_u32.min(strategic_wait_minutes),"min":1,"max":strategic_wait_minutes},"stateBindings":[local_draft("minutes","number")],"children":[]}),
command_control(
"dungeon.wait",
"Wait",
"world.wait",
json!({"expected_revision":campaign.revision}),
&["minutes"],
),
json!({"id":"dungeon.time.minutes","kind":"control.input.number","props":{"label":"Proposed group time advance (minutes)","value":30,"min":1,"max":1440},"stateBindings":[local_draft("time_advance_minutes","number")],"children":[]}),
command_control(
"dungeon.time.propose",
"Propose group time advance",
"governance.time.propose",
json!({"expected_revision":campaign.revision}),
&["time_advance_minutes"],
),
json!({"id":"dungeon.cells.budget","kind":"control.input.number","props":{"label":"Active Persona-cell budget","value":campaign.resolution_policy.active_cell_budget,"min":1,"max":crate::resolution::MAX_ACTIVE_CELL_BUDGET},"stateBindings":[local_draft("active_cell_budget","number")],"children":[]}),
command_control(
"dungeon.cells.propose",
"Propose cell budget",
"governance.cells.propose",
json!({"expected_revision":campaign.revision,"expected_resolution_epoch":campaign.resolution_policy.resolution_epoch}),
&["active_cell_budget"],
),
command_control(
"dungeon.contract-review",
"Review campaign contract",
"campaign.contract_review.begin",
json!({}),
&[],
),
command_control(
"dungeon.campaign-entry",
"Campaigns and new Session Zero",
"campaign.entry",
json!({}),
&[],
),
command_control(
"dungeon.logout",
"Sign out",
"app.auth.logout",
json!({}),
&[],
),
];
if location.routes.is_empty() {
children.push(json!({"id":"dungeon.travel.none","kind":"text","props":{"value":"No compiled route leaves this location yet."},"children":[]}));
} else {
let default_destination_id = location
.routes
.values()
.next()
.map(|route| route.destination_id.as_str())
.expect("non-empty routes have a first destination");
children.push(json!({
"id":"dungeon.travel.destination",
"kind":"control.select",
"props":{"label":"Group destination","value":default_destination_id},
"stateBindings":[local_draft("destination_location_id","choice")],
"children":location.routes.values().filter_map(|route|campaign.locations.get(&route.destination_id).map(|destination|json!({
"id":format!("dungeon.travel.option.{}",route.destination_id),
"kind":"control.option",
"props":{"value":route.destination_id,"label":format!("{} · {} minutes · {}",destination.name,route.travel_minutes,route.distance)},
"children":[]
}))).collect::<Vec<_>>()
}));
children.push(command_control(
"dungeon.travel.propose",
"Propose group travel",
"governance.travel.propose",
json!({"expected_revision":campaign.revision}),
&["destination_location_id"],
));
}
children.push(json!({"id":"dungeon.destination.name","kind":"control.input.text","props":{"label":"Compile a new destination","placeholder":"Describe where you want to go"},"stateBindings":[local_draft("destination","string")],"children":[]}));
children.push(command_control(
"dungeon.destination.compile",
"Compile destination preview",
"world.destination.compile",
json!({}),
&["destination"],
));
children.push(command_control(
"dungeon.campaign.export",
"Export campaign (.cc)",
"campaign.export",
json!({}),
&[],
));
json!({
"type":"surface-state", "schema":"gamecult.eve.surface.v1", "providerId":"gamecult.ghostlight.dungeon",
"providerKind":"narrative.simulation", "title":campaign.name, "version":interface_version,
"updatedAtUtc":chrono::Utc::now().to_rfc3339(),
"world_revision":campaign.revision,
"viewer_actor_id":viewer_actor_id,
"player_location_id":player.location_id,
"reachable_destinations":location.routes.values().filter_map(|route|campaign.locations.get(&route.destination_id).map(|destination|json!({"id":route.destination_id,"name":destination.name,"travel_minutes":route.travel_minutes,"distance":route.distance}))).collect::<Vec<_>>(),
"resolution":{
"policy":campaign.resolution_policy,
"effective_budget":effective_budget,
"mandatory_overage":campaign.resolution_cover.as_ref().map(|cover| cover.mandatory_overage).unwrap_or(0),
"pin_count":campaign.resolution_pins.len(),
"fission_targets":campaign.agency_profiles.values().filter(|profile| profile.active_leaf && profile.subject_kind == crate::domain::AgencySubjectKind::Gestalt).filter_map(|profile| campaign.gestalts.get(&profile.subject_id)).filter(|gestalt|gestalt.home_location_id==player.location_id).map(|gestalt| json!({"id":gestalt.id,"name":gestalt.name})).collect::<Vec<_>>()
},
"surface":{"id":"ghostlight.play","root":{"id":"dungeon.root","kind":"surface","props":{},"children":children},"styles":{"tokens":{"colorBackground":"#0c1110","colorPanel":"#17201d","colorText":"#e8e1cf","colorMuted":"#9aa69f","colorAccent":"#d49b58"}}},
"commands":[
eve_command("world.speak","ghostlight.world_speak.v1", &["text"], "WorldKernel"),
eve_command("world.assess","ghostlight.player_action_assess.v1", &["description","intended_effect"], "WorldKernel"),
eve_command("world.attempt","ghostlight.player_action_attempt.v1", &[], "WorldKernel"),
eve_command("world.wait","ghostlight.world_wait.v1", &["minutes"], "WorldKernel"),
eve_command("governance.cells.propose","ghostlight.cell_budget_proposal.v1", &["active_cell_budget"], "WorldKernel"),
eve_command("governance.cells.approve","ghostlight.cell_budget_approval.v1", &[], "WorldKernel"),
eve_command("governance.time.propose","ghostlight.time_advance_proposal.v1", &["time_advance_minutes"], "WorldKernel"),
eve_command("governance.time.approve","ghostlight.time_advance_approval.v1", &[], "WorldKernel"),
eve_command("governance.travel.propose","ghostlight.group_travel_proposal.v1", &["destination_location_id"], "WorldKernel"),
eve_command("governance.travel.approve","ghostlight.group_travel_approval.v1", &[], "WorldKernel"),
eve_command("world.destination.compile","ghostlight.destination_compile.v1", &["destination"], "WorldCompiler"),
eve_command("world.destination.approve","ghostlight.destination_approval.v1", &[], "WorldKernel"),
eve_command("campaign.entry","ghostlight.campaign_entry.v1", &[], "ghostlight.account_preferences.v1"),
eve_command("campaign.export","ghostlight.campaign_export_request.v1", &[], "CampaignRegistry"),
eve_command("campaign.contract_review.begin","ghostlight.contract_review_begin.v1", &[], "SessionZeroKernel"),
eve_command("app.auth.logout","ghostlight.app_logout.v1", &[], "ghostlight.app_session.v1")
]
})
}
fn autonomous_strategic_event(event: &crate::domain::Event) -> bool {
matches!(
event.kind.as_str(),
"institution_action"
| "gestalt_action"
| "gestalt_migration"
| "gestalt_activity"
| "actor_movement"
| "actor_activity"
| "gestalt_member_activity"
| "gestalt_member_migration"
| "strategic_activity_outcome"
)
}
fn local_draft(name: &str, value_kind: &str) -> Value {
json!({"targetProp":"value","pointerId":format!("draft:{name}"),"sourceId":"renderer","schemaId":"gamecult.eve.local_draft.v1","routeKind":"local","bindingName":name,"documentId":"ghostlight.play.drafts","fieldPath":name,"valueKind":value_kind,"accessMode":"local-draft","authority":"renderer-ephemeral"})
}
fn command_control(
id: &str,
label: &str,
command: &str,
action: Value,
bindings: &[&str],
) -> Value {
let mut action = action.as_object().cloned().unwrap_or_default();
action.insert("command".into(), Value::String(command.into()));
json!({"id":id,"kind":"control.button","props":{"label":label,"command":command,"action":action,"captureBindings":bindings},"children":[]})
}
fn eve_command(command: &str, payload_schema: &str, bindings: &[&str], authority: &str) -> Value {
json!({"schema":"gamecult.eve.command.v1","command":command,"payloadSchema":payload_schema,"captureBindings":bindings,"transport":"https-json","authority":authority})
}
fn story_nodes(campaign: &Campaign) -> Vec<Value> {
let mut entries = Vec::new();
for (index, turn) in campaign.transcript.iter().enumerate() {
entries.push((
turn.revision,
index,
json!({"id":format!("turn-{}-{}-{}",turn.revision,index,turn.speaker),"kind":"text","props":{"value":format!("{}: {}",turn.speaker,turn.text)},"children":[]}),
));
}
entries.sort_by_key(|(revision, index, _)| (*revision, *index));
entries.into_iter().map(|(_, _, node)| node).collect()
}
pub fn operator_surface(
campaign: &Campaign,
evidence: &[VaultEvidenceReceipt],
commits: &[WorldCommitReceipt],
stages: &[ModelStageReceipt],
strategic_ticks: &[StrategicTickReceipt],
gestalt_receipts: &[GestaltMaterializationReceipt],
rejected: &[RejectedProposalReceipt],
resolution_plans: &[crate::domain::ResolutionPlanReceipt],
cell_appraisals: &[crate::domain::CellAppraisal],
activity_outcomes: &[crate::domain::StrategicActivityOutcome],
resolution_controls: &[crate::domain::ResolutionControlReceipt],
live_turn_pressure: usize,
) -> Value {
let interface_version = campaign_interface_version(campaign);
let cover_text = campaign
.resolution_cover
.as_ref()
.map(|cover| {
cover
.cells
.iter()
.map(|cell| {
format!(
"{} {:?} [{}] loss {:.3} debt focus {} — {}",
cell.id,
cell.mode,
cell.subject_ids
.iter()
.cloned()
.collect::<Vec<_>>()
.join(", "),
cell.merge_loss.total,
cell.detail_focus_subject_id.as_deref().unwrap_or("none"),
cell.rationale
)
})
.collect::<Vec<_>>()
.join("\n")
})
.unwrap_or_else(|| "No cover has committed yet.".into());
let graph_text = campaign
.agency_relations
.values()
.filter(|relation| relation.active)
.map(|relation| {
format!(
"{} --{:?}/{}--> {}",
relation.from_subject_id, relation.kind, relation.strength, relation.to_subject_id
)
})
.collect::<Vec<_>>()
.join("\n");
let provider_attempt_count = stages
.iter()
.map(|stage| stage.provider_attempts.len())
.sum::<usize>();
let retry_count = provider_attempt_count.saturating_sub(stages.len());
let token_usage = stages
.iter()
.flat_map(|stage| &stage.provider_attempts)
.filter_map(|attempt| attempt.token_usage.as_ref())
.fold(
crate::model::ModelTokenUsage::default(),
|mut total, usage| {
total.prompt_tokens = total.prompt_tokens.saturating_add(usage.prompt_tokens);
total.completion_tokens = total
.completion_tokens
.saturating_add(usage.completion_tokens);
total.total_tokens = total.total_tokens.saturating_add(usage.total_tokens);
total.prompt_cache_hit_tokens = total
.prompt_cache_hit_tokens
.saturating_add(usage.prompt_cache_hit_tokens);
total.prompt_cache_miss_tokens = total
.prompt_cache_miss_tokens
.saturating_add(usage.prompt_cache_miss_tokens);
total.reasoning_tokens = total
.reasoning_tokens
.saturating_add(usage.reasoning_tokens);
total
},
);
let typed = json!({
"campaign": campaign,
"evidence": evidence,
"commit_receipts": commits,
"model_stage_receipts": stages,
"strategic_ticks": strategic_ticks,
"gestalt_materialization_receipts": gestalt_receipts,
"rejected_proposals": rejected,
"resolution_plan_receipts": resolution_plans,
"cell_appraisals": cell_appraisals,
"strategic_activity_outcomes": activity_outcomes,
"resolution_control_receipts": resolution_controls,
"scheduler": {"live_turn_pressure": live_turn_pressure}
});
let cache_observed_tokens = token_usage
.prompt_cache_hit_tokens
.saturating_add(token_usage.prompt_cache_miss_tokens);
let cache_hit_percent = if cache_observed_tokens == 0 {
0
} else {
token_usage.prompt_cache_hit_tokens.saturating_mul(100) / cache_observed_tokens
};
json!({
"type":"surface-state", "schema":"gamecult.eve.surface.v1", "providerId":"gamecult.ghostlight.dungeon",
"providerKind":"narrative.simulation.operator", "title":format!("{} operator",campaign.name), "version":interface_version,
"surface":{"id":format!("ghostlight.operator.{}",campaign.id),"root":{"id":"dungeon.operator.root","kind":"surface","props":{},"children":[
{"id":"dungeon.operator.status","kind":"card","props":{"title":format!("Revision {} · {} model stages / {} provider attempts · {} tokens · {} rejected proposals",campaign.revision,stages.len(),provider_attempt_count,token_usage.total_tokens,rejected.len())},"children":[{"id":"dungeon.operator.usage","kind":"text","props":{"value":format!("Prompt {} (cache hit {}, miss {}, {}%) · completion {} · reasoning {} · retries {}",token_usage.prompt_tokens,token_usage.prompt_cache_hit_tokens,token_usage.prompt_cache_miss_tokens,cache_hit_percent,token_usage.completion_tokens,token_usage.reasoning_tokens,retry_count)},"children":[]}]},
{"id":"dungeon.operator.cover","kind":"card","props":{"title":format!("Agency cover · epoch {} · budget {}",campaign.resolution_policy.resolution_epoch,campaign.resolution_policy.active_cell_budget)},"children":[{"id":"dungeon.operator.cover.text","kind":"text","props":{"value":cover_text},"children":[]}]},
{"id":"dungeon.operator.graph","kind":"card","props":{"title":format!("Agency graph · {} profiles · {} relations",campaign.agency_profiles.len(),campaign.agency_relations.len())},"children":[{"id":"dungeon.operator.graph.text","kind":"text","props":{"value":graph_text},"children":[]}]},
{"id":"dungeon.operator.outcomes","kind":"card","props":{"title":format!("Strategic activity outcomes · {}",activity_outcomes.len())},"children":[{"id":"dungeon.operator.outcomes.text","kind":"text","props":{"value":activity_outcomes.iter().rev().take(16).map(|outcome|format!("{} {:?} — {}",outcome.source_subject_id,outcome.band,outcome.summary)).collect::<Vec<_>>().join("\n")},"children":[]}]},
{"id":"dungeon.operator.typed","kind":"code","props":{"language":"json","value":serde_json::to_string_pretty(&typed).unwrap_or_else(|_| "operator projection failed".into())},"children":[]}
]},"styles":{"tokens":{"colorBackground":"#0c1110","colorPanel":"#17201d","colorText":"#e8e1cf","colorMuted":"#9aa69f","colorAccent":"#d49b58"}}},
"commands":[]
})
}
fn join(values: &std::collections::BTreeSet<String>) -> String {
if values.is_empty() {
"none".into()
} else {
values.iter().cloned().collect::<Vec<_>>().join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::domain::NarrativeTurn;
use chrono::Utc;
#[test]
fn story_is_chronological_and_uses_only_committed_turns() {
let mut campaign = crate::resolution::tests::campaign(1, 1);
campaign.transcript = vec![
NarrativeTurn {
revision: 1,
at: Utc::now(),
speaker: "player".into(),
text: "I ask the question.".into(),
persona_response_actor_ids: Default::default(),
},
NarrativeTurn {
revision: 2,
at: Utc::now(),
speaker: "world".into(),
text: "raw outcome".into(),
persona_response_actor_ids: Default::default(),
},
NarrativeTurn {
revision: 3,
at: Utc::now(),
speaker: "npc".into(),
text: "I answer directly.".into(),
persona_response_actor_ids: Default::default(),
},
];
let story = story_nodes(&campaign);
let values = story
.iter()
.map(|node| node["props"]["value"].as_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(
values,
vec![
"player: I ask the question.",
"world: raw outcome",
"npc: I answer directly."
]
);
assert!(values.iter().all(|value| !value.contains("narration")));
}
#[test]
fn player_surface_projects_canonical_player_and_location_ids() {
let mut campaign = crate::resolution::tests::campaign(1, 1);
let mut player = campaign.actors.remove("player").unwrap();
player.id = "pilot-nyx".into();
player
.relationships
.insert("faction-0000".into(), "owes me safe passage".into());
campaign.player_actor_id = player.id.clone();
campaign.actors.insert(player.id.clone(), player);
campaign.actors.insert(
"local-witness".into(),
crate::domain::ActorState {
id: "local-witness".into(),
name: "Local Witness".into(),
location_id: "center".into(),
capabilities: Default::default(),
knowledge: Default::default(),
equipment: Default::default(),
conditions: Default::default(),
obligations: Default::default(),
relationships: Default::default(),
goals: vec![],
memories: vec![],
},
);
campaign.actors.insert(
"remote-witness".into(),
crate::domain::ActorState {
id: "remote-witness".into(),
name: "SECRET_REMOTE_WITNESS".into(),
location_id: "remote".into(),
capabilities: Default::default(),
knowledge: Default::default(),
equipment: Default::default(),
conditions: Default::default(),
obligations: Default::default(),
relationships: Default::default(),
goals: vec![],
memories: vec![],
},
);
let surface = player_surface(&campaign);
assert_eq!(surface["viewer_actor_id"], "pilot-nyx");
assert_eq!(surface["player_location_id"], "center");
assert!(
serde_json::to_string(&surface)
.unwrap()
.contains("Relationships: Faction 0: owes me safe passage")
);
let encoded = serde_json::to_string(&surface).unwrap();
assert!(encoded.contains("Present characters: Local Witness"));
assert!(!encoded.contains("SECRET_REMOTE_WITNESS"));
}
#[test]
fn player_surface_cannot_leak_canonical_remote_pressure() {
let mut campaign = crate::resolution::tests::campaign(1, 1);
campaign
.institutions
.get_mut("faction-0000")
.unwrap()
.posture = "SECRET_REMOTE_COUP_POSTURE".into();
campaign.clocks.insert(
"sealed-investigation".into(),
crate::domain::WorldClock {
id: "sealed-investigation".into(),
label: "SECRET_INVESTIGATION_CLOCK".into(),
progress: 3,
threshold: 4,
consequence: "SECRET_ARREST_PLAN".into(),
consequence_scope: Default::default(),
},
);
campaign.news.push(crate::domain::NewsIssue {
id: "news:public".into(),
at: Utc::now(),
channel: "public bulletin".into(),
headline: "The public ferry is delayed.".into(),
event_ids: vec!["event:public".into()],
reliability: "committed public channel".into(),
});
campaign
.agency_profiles
.get_mut("player")
.unwrap()
.information_channels
.insert("public bulletin".into());
campaign.resolution_pins.insert(
"secret-pin".into(),
crate::domain::ResolutionPin {
schema: "ghostlight.resolution_pin.v1".into(),
id: "secret-pin".into(),
kind: crate::domain::ResolutionPinKind::KeepSeparate,
subject_ids: std::collections::BTreeSet::from(["SECRET_REMOTE_SUBJECT".into()]),
reason: "SECRET_OPERATOR_REASON".into(),
created_world_revision: 0,
},
);
let surface = player_surface(&campaign);
let encoded = serde_json::to_string(&surface).unwrap();
assert!(!encoded.contains("SECRET_REMOTE_COUP_POSTURE"));
assert!(!encoded.contains("SECRET_INVESTIGATION_CLOCK"));
assert!(!encoded.contains("SECRET_ARREST_PLAN"));
assert!(!encoded.contains("SECRET_REMOTE_SUBJECT"));
assert!(!encoded.contains("SECRET_OPERATOR_REASON"));
assert_eq!(surface["resolution"]["pin_count"], 1);
assert!(encoded.contains("The public ferry is delayed."));
}
#[test]
fn actor_knowledge_cannot_masquerade_as_news_channel_access() {
let mut campaign = crate::resolution::tests::campaign(1, 1);
campaign.news.push(crate::domain::NewsIssue {
id: "news:sealed".into(),
at: Utc::now(),
channel: "sealed command wire".into(),
headline: "SECRET_COMMAND_MOVEMENT".into(),
event_ids: vec!["event:sealed".into()],
reliability: "committed public channel".into(),
});
campaign
.actors
.get_mut("player")
.unwrap()
.knowledge
.insert("sealed command wire".into());
let encoded = serde_json::to_string(&player_surface(&campaign)).unwrap();
assert!(!encoded.contains("SECRET_COMMAND_MOVEMENT"));
}
#[test]
fn player_surface_projects_directly_perceived_events_but_not_remote_secrets() {
let mut campaign = crate::resolution::tests::campaign(1, 1);
campaign.events.extend([
crate::domain::Event {
id: "event:local".into(),
at: Utc::now(),
kind: "local-change".into(),
summary: "The junction workers reopen the water line.".into(),
actor_ids: vec![],
institution_ids: vec![],
gestalt_ids: vec!["faction-0000".into()],
location_ids: vec!["center".into()],
public_channels: vec![],
},
crate::domain::Event {
id: "event:remote".into(),
at: Utc::now(),
kind: "remote-secret".into(),
summary: "SECRET_REMOTE_EVENT".into(),
actor_ids: vec![],
institution_ids: vec!["faction-0000".into()],
gestalt_ids: vec![],
location_ids: vec!["remote".into()],
public_channels: vec![],
},
]);
let encoded = serde_json::to_string(&player_surface(&campaign)).unwrap();
assert!(encoded.contains("The junction workers reopen the water line."));
assert!(!encoded.contains("SECRET_REMOTE_EVENT"));
}
#[test]
fn player_surface_news_omits_the_viewers_own_turn_and_travel_noise() {
let mut campaign = crate::resolution::tests::campaign(1, 1);
campaign.events.extend([
crate::domain::Event {
id: "event:own-activity".into(),
at: Utc::now(),
kind: "player_action".into(),
summary: "PLAYER_PRIVATE_ACTIVITY_SUMMARY".into(),
actor_ids: vec!["player".into()],
institution_ids: vec![],
gestalt_ids: vec![],
location_ids: vec!["center".into()],
public_channels: vec![],
},
crate::domain::Event {
id: "event:reaction".into(),
at: Utc::now(),
kind: "reaction_wave".into(),
summary: "PLAYER_SPEECH_DUPLICATE".into(),
actor_ids: vec!["faction-0000".into()],
institution_ids: vec![],
gestalt_ids: vec![],
location_ids: vec!["center".into()],
public_channels: vec![],
},
crate::domain::Event {
id: "event:travel".into(),
at: Utc::now(),
kind: "group_travel".into(),
summary: "PLAYER_TRAVEL_DUPLICATE".into(),
actor_ids: vec!["player".into()],
institution_ids: vec![],
gestalt_ids: vec![],
location_ids: vec!["center".into()],
public_channels: vec![],
},
crate::domain::Event {
id: "event:other".into(),
at: Utc::now(),
kind: "institution_action".into(),
summary: "The local watch reinforces the gate.".into(),
actor_ids: vec![],
institution_ids: vec!["faction-0000".into()],
gestalt_ids: vec![],
location_ids: vec!["center".into()],
public_channels: vec![],
},
crate::domain::Event {
id: "event:targeted".into(),
at: Utc::now(),
kind: "actor_activity".into(),
summary: "The local watch warns the player directly.".into(),
actor_ids: vec!["faction-0000".into(), "player".into()],
institution_ids: vec![],
gestalt_ids: vec![],
location_ids: vec!["center".into()],
public_channels: vec![],
},
]);
let encoded = serde_json::to_string(&player_surface(&campaign)).unwrap();
assert!(!encoded.contains("PLAYER_PRIVATE_ACTIVITY_SUMMARY"));
assert!(!encoded.contains("PLAYER_SPEECH_DUPLICATE"));
assert!(!encoded.contains("PLAYER_TRAVEL_DUPLICATE"));
assert!(encoded.contains("The local watch reinforces the gate."));
assert!(encoded.contains("The local watch warns the player directly."));
}
#[test]
fn player_surface_offers_only_local_population_fission_targets() {
let mut campaign = crate::resolution::tests::campaign(1, 1);
for (id, name, location) in [
("local-neighbors", "Local neighbors", "center"),
("remote-cell", "SECRET_REMOTE_POPULATION", "far-district"),
] {
campaign.gestalts.insert(
id.into(),
crate::domain::GestaltPersonaState {
schema: "ghostlight.gestalt_persona_state.v1".into(),
id: id.into(),
name: name.into(),
version: 0,
home_location_id: location.into(),
shared_capabilities: Default::default(),
shared_knowledge: Default::default(),
resources: Default::default(),
goals: vec![],
pressures: vec![],
},
);
}
crate::resolution::ensure_agency_profiles(&mut campaign);
let encoded = serde_json::to_string(&player_surface(&campaign)).unwrap();
assert!(encoded.contains("Local neighbors"));
assert!(!encoded.contains("SECRET_REMOTE_POPULATION"));
}
#[test]
fn player_surface_uses_bound_eve_controls_for_time_travel_and_destination_compilation() {
let mut campaign = crate::resolution::tests::campaign(1, 1);
campaign.locations.insert(
"harbor".into(),
crate::domain::Location {
id: "harbor".into(),
name: "Harbor".into(),
container_id: None,
routes: Default::default(),
persistent_features: vec![],
},
);
campaign.locations.get_mut("center").unwrap().routes.insert(
"road-to-harbor".into(),
crate::domain::Route {
destination_id: "harbor".into(),
distance: "nearby".into(),
travel_minutes: 20,
},
);
let encoded = serde_json::to_string(&player_surface(&campaign)).unwrap();
for binding in [
"time_advance_minutes",
"destination_location_id",
"destination",
] {
assert!(encoded.contains(&format!("\"bindingName\":\"{binding}\"")));
}
assert!(encoded.contains("governance.travel.propose"));
assert!(encoded.contains("\"value\":\"harbor\""));
assert!(encoded.contains("world.destination.compile"));
assert!(encoded.contains("campaign.entry"));
assert!(!encoded.contains("payload.fields"));
assert!(!encoded.contains("\"kind\":\"form\""));
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,919 +0,0 @@
use crate::{
domain::{ActorReaction, Campaign, GestaltReaction},
model::{ModelPort, ModelStageReceipt, ModelStageRequest, run_validated_stage},
persistence::CampaignStore,
persona::{
ActorInteractionRole, ExecutionPermit, PermittedActorSlice, PersonaProjectionEngine,
PersonaSubjectKind,
},
};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use schemars::{JsonSchema, schema_for};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeSet, sync::Arc};
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SpeechAddressPlan {
/// Exact present, model-controlled Persona subjects from whom the utterance
/// requests an answer. Mentioned subjects and passive hearers are omitted.
pub persona_response_actor_ids: BTreeSet<String>,
}
/// Resolve conversational address from player language against the exact
/// present-subject catalog. The output is proposal-only until WorldKernel
/// validates co-presence and commits it with the speech turn.
pub async fn resolve_speech_addresses(
model: Arc<dyn ModelPort>,
model_name: &str,
campaign: &Campaign,
speaker_actor_id: &str,
speech: &str,
) -> Result<(SpeechAddressPlan, Vec<ModelStageReceipt>)> {
let speaker = campaign
.actors
.get(speaker_actor_id)
.ok_or_else(|| anyhow!("speech actor is unknown"))?;
let mut candidates = campaign
.actors
.values()
.filter(|actor| {
actor.id != speaker_actor_id
&& actor.location_id == speaker.location_id
&& campaign
.agency_profiles
.get(&actor.id)
.is_none_or(|profile| profile.simulation_eligible)
})
.map(|actor| {
(
actor.id.clone(),
serde_json::json!({
"public_name": actor.name,
"presence": "materialized_actor",
}),
)
})
.collect::<std::collections::BTreeMap<_, _>>();
candidates.extend(campaign.gestalt_members.values().filter_map(|member| {
if member.materialized_actor_id.is_some()
|| !crate::resolution::dormant_member_location(campaign, &member.id)
.is_ok_and(|location| location == speaker.location_id)
{
return None;
}
Some((
crate::domain::gestalt_member_subject_id(&member.id),
serde_json::json!({
"public_name": member.name,
"presence": "nearby_folded_person",
}),
))
}));
candidates.extend(campaign.gestalts.values().filter_map(|gestalt| {
crate::resolution::validate_active_gestalt_presence_location(
campaign,
&gestalt.id,
&speaker.location_id,
)
.ok()?;
Some((
gestalt.id.clone(),
serde_json::json!({
"public_name": gestalt.name,
"presence": "cohesive_population",
}),
))
}));
if candidates.is_empty() {
return Ok((
SpeechAddressPlan {
persona_response_actor_ids: BTreeSet::new(),
},
Vec::new(),
));
}
let allowed_ids = candidates.keys().cloned().collect::<BTreeSet<_>>();
let previous_focus = campaign
.transcript
.iter()
.rev()
.find(|turn| {
turn.speaker == speaker_actor_id && !turn.persona_response_actor_ids.is_empty()
})
.map(|turn| turn.persona_response_actor_ids.clone())
.unwrap_or_default();
let recent_public_turns = campaign
.transcript
.iter()
.rev()
.take(8)
.collect::<Vec<_>>()
.into_iter()
.rev()
.map(|turn| {
serde_json::json!({
"speaker":turn.speaker,
"text":turn.text,
"persona_response_actor_ids":turn.persona_response_actor_ids,
})
})
.collect::<Vec<_>>();
let mut schema = serde_json::to_value(schema_for!(SpeechAddressPlan))?;
schema["properties"]["persona_response_actor_ids"] = serde_json::json!({
"type":"array",
"uniqueItems":true,
"maxItems":allowed_ids.len(),
"items":{"type":"string","enum":allowed_ids},
});
let prompt = format!(
"You are Ghostlight's private scene-address resolver. Decide only which supplied present Persona subjects this exact speech directly asks to answer now. A nearby_folded_person is a persistent known individual currently represented through their population; selecting their exact member ID lets Ghostlight materialize that same person before appraisal. A cohesive_population is a genuine collective subject and may be directly asked for a plural response. A subject who is merely mentioned, discussed, visible, or able to overhear is not a response target. A room-wide statement need not demand an answer from everyone. Preserve ordinary conversational focus from previous_focus when pronouns or an unqualified follow-up clearly continue it. Select only exact supplied IDs. Empty is valid when the speaker asks nobody present to answer. Return exactly one JSON object matching the schema.\nSCHEMA:\n{}\nPRESENT PERSONA SUBJECTS:\n{}\nPREVIOUS FOCUS:\n{}\nRECENT PUBLIC TURNS:\n{}\nSPEAKER ACTOR ID:\n{}\nEXACT SPEECH:\n{}",
serde_json::to_string(&schema)?,
serde_json::to_string(&candidates)?,
serde_json::to_string(&previous_focus)?,
serde_json::to_string(&recent_public_turns)?,
serde_json::to_string(speaker_actor_id)?,
serde_json::to_string(speech)?,
);
let output = run_validated_stage(
model.as_ref(),
&ModelStageRequest {
stage: "speech_address_resolver".into(),
model: model_name.into(),
snapshot_binding: format!("campaign:{}:revision:{}", campaign.id, campaign.revision),
lived_stream: prompt,
output_schema: Some(schema),
source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(),
temperature: Some(0.0),
max_output_tokens: Some(256),
},
)
.await?;
let plan: SpeechAddressPlan = serde_json::from_value(
output
.structured
.clone()
.ok_or_else(|| anyhow!("speech address resolver produced no plan"))?,
)?;
if !plan.persona_response_actor_ids.is_subset(&allowed_ids) {
return Err(anyhow!(
"speech address resolver selected an unavailable actor"
));
}
Ok((plan, vec![output.receipt]))
}
pub struct SnapshotPermit {
store: CampaignStore,
campaign_id: uuid::Uuid,
revision: u64,
resolution_epoch: Option<u64>,
}
impl SnapshotPermit {
pub fn new(store: CampaignStore, campaign_id: uuid::Uuid, revision: u64) -> Self {
Self {
store,
campaign_id,
revision,
resolution_epoch: None,
}
}
pub fn new_resolution(
store: CampaignStore,
campaign_id: uuid::Uuid,
revision: u64,
resolution_epoch: u64,
) -> Self {
Self {
store,
campaign_id,
revision,
resolution_epoch: Some(resolution_epoch),
}
}
}
#[async_trait]
impl ExecutionPermit for SnapshotPermit {
async fn require(&self, _: &str, _: &str, _: &str) -> Result<()> {
let value = self
.store
.load::<Campaign>("campaign.v1", &self.campaign_id.to_string())?
.map(|(_, c)| c)
.ok_or_else(|| anyhow!("campaign vanished during Persona wave"))?;
if value.revision != self.revision
|| self
.resolution_epoch
.is_some_and(|epoch| value.resolution_policy.resolution_epoch != epoch)
{
return Err(anyhow!("Persona projection snapshot is stale"));
}
Ok(())
}
}
pub struct ReactionWaveOutput {
pub reactions: Vec<ActorReaction>,
pub gestalt_reactions: Vec<GestaltReaction>,
pub receipts: Vec<ModelStageReceipt>,
}
enum PresentReactionTerminal {
Actor(String, crate::persona::PersonaTerminalBundle),
Gestalt(String, crate::persona::PersonaTerminalBundle),
}
pub async fn appraise_present(
engine: PersonaProjectionEngine,
campaign: &Campaign,
event_summary: &str,
) -> Result<ReactionWaveOutput> {
let response_expected_actor_ids = canonical_reaction_turn(campaign, event_summary)?
.persona_response_actor_ids
.clone();
let player = campaign
.actors
.get(&campaign.player_actor_id)
.ok_or_else(|| anyhow!("player actor missing"))?;
let actors: Vec<_> = campaign
.actors
.values()
.filter(|actor| {
actor.location_id == player.location_id
&& campaign
.agency_profiles
.get(&actor.id)
.is_none_or(|profile| profile.simulation_eligible)
})
.cloned()
.collect();
let mut perceived_actors = campaign
.actors
.values()
.filter(|actor| actor.location_id == player.location_id)
.map(|actor| (actor.id.clone(), actor.name.clone()))
.collect::<std::collections::BTreeMap<_, _>>();
let local_gestalts = campaign
.gestalts
.values()
.filter(|gestalt| {
crate::resolution::validate_active_gestalt_presence_location(
campaign,
&gestalt.id,
&player.location_id,
)
.is_ok()
})
.cloned()
.collect::<Vec<_>>();
perceived_actors.extend(
local_gestalts
.iter()
.map(|gestalt| (gestalt.id.clone(), gestalt.name.clone())),
);
let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(usize::from(
campaign.resolution_policy.provider_parallelism.max(1),
)));
let mut jobs = tokio::task::JoinSet::new();
for actor in actors {
let engine = engine.clone();
let snapshot = format!("campaign:{}:revision:{}", campaign.id, campaign.revision);
let event = event_summary.to_owned();
let receipts = campaign.branch_origin.evidence_receipt_ids.clone();
let perceived_actors = perceived_actors.clone();
let reserved_public_identities = reserved_public_identities(campaign, &actor);
let recent_self_authored_turns = recent_self_authored_turns(campaign, &actor.id);
let semaphore = semaphore.clone();
let interaction_role = if response_expected_actor_ids.contains(&actor.id) {
ActorInteractionRole::DirectResponseExpected
} else {
ActorInteractionRole::PresentObserver
};
jobs.spawn(async move {
let _provider_slot = semaphore
.acquire_owned()
.await
.map_err(|_| anyhow!("provider concurrency gate closed"))?;
let slice = PermittedActorSlice {
actor_id: actor.id.clone(),
location_id: actor.location_id.clone(),
subject_kind: PersonaSubjectKind::IndividualActor,
snapshot_binding: snapshot,
interaction_role,
identity_experience: vec![format!("You are {}.", actor.name)],
reserved_public_identities,
memories: actor.memories,
recent_self_authored_turns,
perceived_events: vec![event],
perceived_actors,
relationships: actor
.relationships
.into_iter()
.map(|(id, value)| format!("{id}: {value}"))
.collect(),
goals: actor.goals,
knowledge: actor.knowledge.into_iter().collect(),
capabilities: actor.capabilities.into_iter().collect(),
pressures: actor
.conditions
.into_iter()
.chain(actor.obligations)
.collect(),
affordances: actor.equipment.into_iter().collect(),
source_receipt_ids: receipts,
};
let terminal = engine.execute(slice).await?;
Ok::<_, anyhow::Error>(PresentReactionTerminal::Actor(actor.id, terminal))
});
}
for gestalt in local_gestalts {
let engine = engine.clone();
let snapshot = format!("campaign:{}:revision:{}", campaign.id, campaign.revision);
let event = event_summary.to_owned();
let receipts = campaign.branch_origin.evidence_receipt_ids.clone();
let perceived_actors = perceived_actors.clone();
let recent_self_authored_turns = recent_self_authored_turns(campaign, &gestalt.id);
let semaphore = semaphore.clone();
let interaction_role = if response_expected_actor_ids.contains(&gestalt.id) {
ActorInteractionRole::DirectResponseExpected
} else {
ActorInteractionRole::PresentObserver
};
jobs.spawn(async move {
let _provider_slot = semaphore
.acquire_owned()
.await
.map_err(|_| anyhow!("provider concurrency gate closed"))?;
let slice = PermittedActorSlice {
actor_id: gestalt.id.clone(),
location_id: gestalt.home_location_id.clone(),
subject_kind: PersonaSubjectKind::CohesiveGestalt,
snapshot_binding: snapshot,
interaction_role,
identity_experience: vec![format!(
"You are {}, a cohesive population represented through genuinely shared state.",
gestalt.name
)],
reserved_public_identities: perceived_actors.values().cloned().collect(),
memories: vec![],
recent_self_authored_turns,
perceived_events: vec![event],
perceived_actors,
relationships: vec![],
goals: gestalt.goals,
knowledge: gestalt.shared_knowledge.into_iter().collect(),
capabilities: gestalt.shared_capabilities.into_iter().collect(),
pressures: gestalt.pressures,
affordances: gestalt.resources.into_iter().collect(),
source_receipt_ids: receipts,
};
let terminal = engine.execute(slice).await?;
Ok::<_, anyhow::Error>(PresentReactionTerminal::Gestalt(gestalt.id, terminal))
});
}
let mut reactions = Vec::new();
let mut gestalt_reactions = Vec::new();
let mut receipts = Vec::new();
while let Some(result) = jobs.join_next().await {
match result.map_err(|e| anyhow!("Persona appraisal task failed: {e}"))?? {
PresentReactionTerminal::Actor(actor_id, terminal) => {
receipts.extend(terminal.stage_receipts);
reactions.push(ActorReaction {
actor_id,
speech: terminal.proposals.speech,
deliberate_silence: terminal.proposals.deliberate_silence,
private_delta: terminal.proposals.private_delta,
action_proposals: terminal.proposals.world_actions,
});
}
PresentReactionTerminal::Gestalt(gestalt_id, terminal) => {
receipts.extend(terminal.stage_receipts);
gestalt_reactions.push(GestaltReaction {
gestalt_id,
speech: terminal.proposals.speech,
deliberate_silence: terminal.proposals.deliberate_silence,
});
}
}
}
reactions.sort_by(|a, b| a.actor_id.cmp(&b.actor_id));
gestalt_reactions.sort_by(|a, b| a.gestalt_id.cmp(&b.gestalt_id));
Ok(ReactionWaveOutput {
reactions,
gestalt_reactions,
receipts,
})
}
fn recent_self_authored_turns(campaign: &Campaign, subject_id: &str) -> Vec<String> {
const LIMIT: usize = 8;
let mut turns = campaign
.transcript
.iter()
.rev()
.filter(|turn| turn.speaker == subject_id)
.take(LIMIT)
.map(|turn| {
format!(
"At world revision {}, your committed public response was exactly: {}",
turn.revision,
turn.text.trim()
)
})
.collect::<Vec<_>>();
turns.reverse();
turns
}
fn reserved_public_identities(
campaign: &Campaign,
actor: &crate::domain::ActorState,
) -> BTreeSet<String> {
let own_identity = actor.name.trim().to_lowercase();
let mut identities = campaign
.actors
.values()
.filter(|other| other.id != actor.id && other.location_id == actor.location_id)
.map(|other| other.name.clone())
.collect::<BTreeSet<_>>();
if let Some(member) = campaign
.gestalt_members
.values()
.find(|member| member.materialized_actor_id.as_deref() == Some(actor.id.as_str()))
{
identities.extend(
campaign
.gestalt_members
.values()
.filter(|peer| peer.id != member.id && peer.gestalt_id == member.gestalt_id)
.map(|peer| peer.name.clone()),
);
}
identities.retain(|identity| identity.trim().to_lowercase() != own_identity);
identities
}
fn canonical_reaction_turn<'a>(
campaign: &'a Campaign,
event_summary: &str,
) -> Result<&'a crate::domain::NarrativeTurn> {
let event_summary = event_summary.trim();
campaign
.transcript
.iter()
.rev()
.find(|turn| {
let canonical = if turn.speaker == "world" {
turn.text.trim().to_owned()
} else {
format!("{} says: {}", turn.speaker, turn.text.trim())
};
canonical == event_summary
})
.ok_or_else(|| anyhow!("reaction stimulus does not match a committed transcript turn"))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
domain::{ActorState, GestaltMemberDelta, GestaltPersonaState, NarrativeTurn},
model::ModelStageRequest,
persona::{AllowAllPermit, PersonaProjectionEngine},
};
use chrono::Utc;
use std::collections::{BTreeMap, BTreeSet};
struct AddressAwareModel;
struct DormantAddressModel;
struct CollectiveAddressModel;
#[async_trait]
impl ModelPort for AddressAwareModel {
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
Ok(match request.stage.as_str() {
"speech_address_resolver" => {
assert!(request.lived_stream.contains("Refugee One"));
assert!(request.lived_stream.contains("Refugee Two"));
assert!(request.lived_stream.contains("Relay Observer"));
serde_json::json!({
"persona_response_actor_ids":["refugee-one","refugee-two"]
})
.to_string()
}
"projector" => "The question lands in the small circle.".into(),
"persona" => {
if request.lived_stream.contains("exact direct addressee") {
"I answer plainly: that memory is mine alone.".into()
} else {
"I listen without taking over their answer.".into()
}
}
"interpreter" => {
let direct = request.lived_stream.contains("direct_response_expected");
serde_json::json!({
"private_delta":{
"memories_add":[],
"conditions_add":[],
"conditions_remove":[],
"goals_add":[],
"relationship_updates":{},
},
"speech":direct.then_some("that memory is mine alone"),
"deliberate_silence":false,
"reaction_priority":0,
"world_actions":[],
})
.to_string()
}
stage => return Err(anyhow!("unexpected stage {stage}")),
})
}
fn provider(&self) -> &'static str {
"fixture"
}
}
#[async_trait]
impl ModelPort for DormantAddressModel {
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
assert_eq!(request.stage, "speech_address_resolver");
assert!(request.lived_stream.contains("nearby_folded_person"));
assert!(request.lived_stream.contains("member:water-cart-taren"));
Ok(serde_json::json!({
"persona_response_actor_ids":["member:water-cart-taren"]
})
.to_string())
}
fn provider(&self) -> &'static str {
"fixture"
}
}
#[async_trait]
impl ModelPort for CollectiveAddressModel {
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
Ok(match request.stage.as_str() {
"speech_address_resolver" => {
assert!(request.lived_stream.contains("cohesive_population"));
assert!(request.lived_stream.contains("Settlement households"));
serde_json::json!({
"persona_response_actor_ids":["settlement-households"]
})
.to_string()
}
"projector" => {
"The households hear a direct request for their shared answer.".into()
}
"persona" => "We will not accept a slate that makes our names disappear.".into(),
"interpreter" => serde_json::json!({
"private_delta":{
"memories_add":[],
"identity_adoption":null,
"conditions_add":[],
"conditions_remove":[],
"goals_add":[],
"relationship_updates":{},
},
"speech":"We will not accept a slate that makes our names disappear.",
"deliberate_silence":false,
"reaction_priority":5,
"world_actions":[],
})
.to_string(),
stage => return Err(anyhow!("unexpected stage {stage}")),
})
}
fn provider(&self) -> &'static str {
"fixture"
}
}
fn actor(id: &str, name: &str, location_id: &str) -> ActorState {
ActorState {
id: id.into(),
name: name.into(),
location_id: location_id.into(),
capabilities: BTreeSet::from(["ordinary conversation".into()]),
knowledge: BTreeSet::new(),
equipment: BTreeSet::new(),
conditions: BTreeSet::new(),
obligations: BTreeSet::new(),
relationships: BTreeMap::new(),
goals: vec![],
memories: vec![],
}
}
fn addressed_campaign() -> Campaign {
let mut campaign = crate::resolution::tests::campaign(0, 8);
let location = campaign.actors[&campaign.player_actor_id]
.location_id
.clone();
campaign.actors.insert(
"refugee-one".into(),
actor("refugee-one", "Refugee One", &location),
);
campaign.actors.insert(
"refugee-two".into(),
actor("refugee-two", "Refugee Two", &location),
);
campaign.actors.insert(
"relay-observer".into(),
actor("relay-observer", "Relay Observer", &location),
);
crate::resolution::ensure_agency_profiles(&mut campaign);
campaign
.agency_profiles
.get_mut(&campaign.player_actor_id)
.unwrap()
.simulation_eligible = false;
campaign
}
#[test]
fn stable_subject_history_survives_folding_and_remains_bounded() {
let mut campaign = addressed_campaign();
for revision in 1..=10 {
campaign.transcript.push(NarrativeTurn {
revision,
at: Utc::now(),
speaker: "refugee-one".into(),
text: format!("response {revision}"),
persona_response_actor_ids: BTreeSet::new(),
});
}
campaign.transcript.push(NarrativeTurn {
revision: 11,
at: Utc::now(),
speaker: "refugee-two".into(),
text: "another person's answer".into(),
persona_response_actor_ids: BTreeSet::new(),
});
let before_folding = recent_self_authored_turns(&campaign, "refugee-one");
assert_eq!(before_folding.len(), 8);
assert!(before_folding[0].contains("world revision 3"));
assert!(before_folding[0].ends_with("response 3"));
assert!(before_folding[7].ends_with("response 10"));
assert!(
before_folding
.iter()
.all(|turn| !turn.contains("another person's answer"))
);
campaign.actors.remove("refugee-one");
assert_eq!(
recent_self_authored_turns(&campaign, "refugee-one"),
before_folding
);
}
#[test]
fn materialized_actor_receives_dormant_peer_identities_as_social_context() {
let mut campaign = crate::resolution::tests::campaign(0, 8);
let location = campaign.actors[&campaign.player_actor_id]
.location_id
.clone();
campaign.actors.insert(
"member:oxygen-patient".into(),
actor("member:oxygen-patient", "Oxygen Patient", &location),
);
let member =
|id: &str, name: &str, materialized_actor_id: Option<&str>| GestaltMemberDelta {
schema: "ghostlight.gestalt_member_delta.v1".into(),
id: id.into(),
gestalt_id: "refugees".into(),
version: 0,
name: name.into(),
capability_additions: BTreeSet::new(),
capability_removals: BTreeSet::new(),
knowledge_additions: BTreeSet::new(),
knowledge_removals: BTreeSet::new(),
equipment: BTreeSet::new(),
conditions: BTreeSet::new(),
obligations: BTreeSet::new(),
relationships: BTreeMap::new(),
goals: vec![],
memories: vec![],
last_location_id: Some(location.clone()),
materialized_actor_id: materialized_actor_id.map(str::to_owned),
last_relevant_revision: 0,
relevance_lease_until_revision: 0,
};
campaign.gestalt_members.insert(
"oxygen-patient".into(),
member(
"oxygen-patient",
"Oxygen Patient",
Some("member:oxygen-patient"),
),
);
campaign
.gestalt_members
.insert("taren".into(), member("taren", "Taren", None));
let reserved =
reserved_public_identities(&campaign, &campaign.actors["member:oxygen-patient"]);
assert!(reserved.contains("Taren"));
assert!(!reserved.contains("Oxygen Patient"));
}
#[tokio::test]
async fn address_resolver_selects_exact_supplied_respondents() {
let campaign = addressed_campaign();
let (plan, receipts) = resolve_speech_addresses(
Arc::new(AddressAwareModel),
"flash",
&campaign,
&campaign.player_actor_id,
"Refugee One and Refugee Two: answer separately. Relay Observer, listen.",
)
.await
.unwrap();
assert_eq!(
plan.persona_response_actor_ids,
BTreeSet::from(["refugee-one".into(), "refugee-two".into()])
);
assert_eq!(receipts.len(), 1);
}
#[tokio::test]
async fn address_resolver_can_select_the_exact_nearby_folded_person() {
let mut campaign = crate::resolution::tests::campaign(0, 8);
let location = campaign.actors[&campaign.player_actor_id]
.location_id
.clone();
campaign.gestalts.insert(
"refugees".into(),
GestaltPersonaState {
schema: "ghostlight.gestalt_persona_state.v1".into(),
id: "refugees".into(),
name: "Refugees".into(),
version: 3,
home_location_id: location.clone(),
shared_capabilities: BTreeSet::new(),
shared_knowledge: BTreeSet::new(),
resources: BTreeSet::new(),
goals: vec![],
pressures: vec![],
},
);
campaign.gestalt_members.insert(
"water-cart-taren".into(),
GestaltMemberDelta {
schema: "ghostlight.gestalt_member_delta.v1".into(),
id: "water-cart-taren".into(),
gestalt_id: "refugees".into(),
version: 7,
name: "Taren".into(),
capability_additions: BTreeSet::new(),
capability_removals: BTreeSet::new(),
knowledge_additions: BTreeSet::new(),
knowledge_removals: BTreeSet::new(),
equipment: BTreeSet::from(["water handcart".into()]),
conditions: BTreeSet::new(),
obligations: BTreeSet::new(),
relationships: BTreeMap::new(),
goals: vec![],
memories: vec![],
last_location_id: Some(location),
materialized_actor_id: None,
last_relevant_revision: 0,
relevance_lease_until_revision: 0,
},
);
crate::resolution::ensure_agency_profiles(&mut campaign);
let (plan, _) = resolve_speech_addresses(
Arc::new(DormantAddressModel),
"flash",
&campaign,
&campaign.player_actor_id,
"Taren with the water handcart, is the coupling holding?",
)
.await
.unwrap();
assert_eq!(
plan.persona_response_actor_ids,
BTreeSet::from(["member:water-cart-taren".into()])
);
}
#[tokio::test]
async fn exact_addressees_receive_response_duty_while_observers_keep_agency() {
let mut campaign = addressed_campaign();
let speech = "Refugee One and Refugee Two: answer separately.";
campaign.transcript.push(NarrativeTurn {
revision: campaign.revision,
at: Utc::now(),
speaker: campaign.player_actor_id.clone(),
text: speech.into(),
persona_response_actor_ids: BTreeSet::from([
"refugee-one".into(),
"refugee-two".into(),
]),
});
let summary = format!("{} says: {speech}", campaign.player_actor_id);
let engine = PersonaProjectionEngine {
model: Arc::new(AddressAwareModel),
permit: Arc::new(AllowAllPermit),
projector_model: "flash".into(),
persona_model: "pro".into(),
interpreter_model: "flash".into(),
};
let wave = appraise_present(engine, &campaign, &summary).await.unwrap();
assert_eq!(wave.reactions.len(), 3);
for actor_id in ["refugee-one", "refugee-two"] {
assert_eq!(
wave.reactions
.iter()
.find(|reaction| reaction.actor_id == actor_id)
.and_then(|reaction| reaction.speech.as_deref()),
Some("that memory is mine alone")
);
}
assert!(
wave.reactions
.iter()
.find(|reaction| reaction.actor_id == "relay-observer")
.unwrap()
.speech
.is_none()
);
}
#[tokio::test]
async fn local_cohesive_gestalt_is_addressable_and_appraises_in_the_foreground_wave() {
let mut campaign = crate::resolution::tests::campaign(0, 8);
let location = campaign.actors[&campaign.player_actor_id]
.location_id
.clone();
campaign.gestalts.insert(
"settlement-households".into(),
GestaltPersonaState {
schema: "ghostlight.gestalt_persona_state.v1".into(),
id: "settlement-households".into(),
name: "Settlement households".into(),
version: 0,
home_location_id: location,
shared_capabilities: BTreeSet::from(["collective refusal".into()]),
shared_knowledge: BTreeSet::from(["five names lack a traceable path".into()]),
resources: BTreeSet::new(),
goals: vec!["keep every household legible".into()],
pressures: vec!["the slate is closing".into()],
},
);
crate::resolution::ensure_agency_profiles(&mut campaign);
campaign
.agency_profiles
.get_mut(&campaign.player_actor_id)
.unwrap()
.simulation_eligible = false;
let speech = "Settlement households, will you refuse this slate?";
let (plan, _) = resolve_speech_addresses(
Arc::new(CollectiveAddressModel),
"flash",
&campaign,
&campaign.player_actor_id,
speech,
)
.await
.unwrap();
assert_eq!(
plan.persona_response_actor_ids,
BTreeSet::from(["settlement-households".into()])
);
campaign.transcript.push(NarrativeTurn {
revision: campaign.revision,
at: Utc::now(),
speaker: campaign.player_actor_id.clone(),
text: speech.into(),
persona_response_actor_ids: plan.persona_response_actor_ids,
});
let summary = format!("{} says: {speech}", campaign.player_actor_id);
let wave = appraise_present(
PersonaProjectionEngine {
model: Arc::new(CollectiveAddressModel),
permit: Arc::new(AllowAllPermit),
projector_model: "flash".into(),
persona_model: "pro".into(),
interpreter_model: "flash".into(),
},
&campaign,
&summary,
)
.await
.unwrap();
assert!(wave.reactions.is_empty());
assert_eq!(wave.gestalt_reactions.len(), 1);
assert_eq!(
wave.gestalt_reactions[0].speech.as_deref(),
Some("We will not accept a slate that makes our names disappear.")
);
}
}

View file

@ -1,750 +0,0 @@
use crate::domain::{SourceWitness, VaultEvidenceReceipt};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use chrono::Utc;
use reqwest::Client;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use thiserror::Error;
const VOIDBOT_SEARCH_RESULT_LIMIT: u8 = 12;
pub const DEFAULT_VAULT_ID: &str = "aetheria";
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct VaultSourceManifest {
pub schema: String,
pub id: String,
pub title: String,
pub provider_id: String,
pub repository_name: String,
pub source_root: String,
pub git_remote: String,
pub compiler_authority_lanes: Vec<String>,
pub player_authority_lanes: Vec<String>,
}
pub fn bundled_vault_manifests() -> Vec<VaultSourceManifest> {
vec![
VaultSourceManifest {
schema: "ghostlight.vault_source_manifest.v1".into(),
id: "aetheria".into(),
title: "Aetheria".into(),
provider_id: "voidbot.aetheria".into(),
repository_name: "AetheriaLore".into(),
source_root: "Aetheria/Worldbuilding/".into(),
git_remote: "https://github.com/GameCult/AetheriaLore.git".into(),
compiler_authority_lanes: vec!["aetheria.canon_worldbuilding".into()],
player_authority_lanes: vec!["aetheria.canon_worldbuilding".into()],
},
VaultSourceManifest {
schema: "ghostlight.vault_source_manifest.v1".into(),
id: "kalsa".into(),
title: "Kalsa".into(),
provider_id: "voidbot.kalsa".into(),
repository_name: "Kalsa".into(),
source_root: "Kalsa/".into(),
git_remote: "https://github.com/GameCult/Kalsa.git".into(),
compiler_authority_lanes: vec!["kalsa.public".into(), "kalsa.gm_canon".into()],
player_authority_lanes: vec!["kalsa.public".into()],
},
]
}
pub fn canonical_vault_id(value: &str) -> Option<&'static str> {
match value.trim().to_ascii_lowercase().as_str() {
// `fixture` is the persisted legacy migration label used before Vault
// selection became typed. Those campaigns were compiled from the
// bundled Aetheria provider.
"aetheria" | "aetherialore" | "voidbot.aetheria" | "fixture" => Some("aetheria"),
"kalsa" | "voidbot.kalsa" => Some("kalsa"),
_ => None,
}
}
#[derive(Debug, Error)]
#[error("{provider} Vault retrieval is unavailable: {detail}")]
pub struct VaultUnavailable {
provider: String,
detail: String,
}
impl VaultUnavailable {
fn new(provider: impl Into<String>, detail: impl Into<String>) -> Self {
Self {
provider: provider.into(),
detail: detail.into(),
}
}
}
pub fn is_vault_unavailable(error: &anyhow::Error) -> bool {
error
.chain()
.any(|cause| cause.downcast_ref::<VaultUnavailable>().is_some())
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct VaultQuery {
pub query: String,
pub authority_lanes: Vec<String>,
pub temporal_scope: String,
pub limit: u8,
}
#[async_trait]
pub trait VaultProvider: Send + Sync {
async fn search(&self, query: &VaultQuery) -> Result<VaultEvidenceReceipt>;
async fn surrounding_context(&self, source_id: &str, chunk_index: u32)
-> Result<SourceWitness>;
async fn exact_document(&self, source_id: &str) -> Result<SourceWitness>;
fn provider_id(&self) -> &'static str;
}
#[derive(Clone)]
pub struct FixtureVault {
pub witnesses: Vec<SourceWitness>,
}
#[async_trait]
impl VaultProvider for FixtureVault {
async fn search(&self, query: &VaultQuery) -> Result<VaultEvidenceReceipt> {
Ok(receipt(
self.provider_id(),
query,
self.witnesses
.iter()
.take(query.limit as usize)
.cloned()
.collect(),
))
}
async fn exact_document(&self, source_id: &str) -> Result<SourceWitness> {
self.witnesses
.iter()
.find(|w| w.source_id == source_id)
.cloned()
.ok_or_else(|| anyhow!("fixture source not found"))
}
async fn surrounding_context(&self, source_id: &str, _: u32) -> Result<SourceWitness> {
self.exact_document(source_id).await
}
fn provider_id(&self) -> &'static str {
"fixture"
}
}
#[derive(Clone)]
pub struct VoidBotMcpVault {
client: Client,
endpoint: String,
manifests: BTreeMap<String, VaultSourceManifest>,
}
impl VoidBotMcpVault {
pub fn new(endpoint: impl Into<String>) -> Self {
let manifests = bundled_vault_manifests()
.into_iter()
.map(|manifest| (manifest.id.clone(), manifest))
.collect();
Self {
client: Client::new(),
endpoint: endpoint.into(),
manifests,
}
}
pub fn starfire_loopback() -> Self {
Self::new("http://127.0.0.1:17875/mcp")
}
async fn call_tool(
&self,
name: &str,
arguments: serde_json::Value,
) -> Result<serde_json::Value> {
let response = self.client.post(&self.endpoint)
.header("accept", "application/json, text/event-stream")
.json(&serde_json::json!({"jsonrpc":"2.0","id":"ghostlight-vault","method":"tools/call","params":{"name":name,"arguments":arguments}}))
.send()
.await
.map_err(|error| VaultUnavailable::new(self.provider_id(), error.to_string()))?
.error_for_status()
.map_err(|error| VaultUnavailable::new(self.provider_id(), error.to_string()))?;
let text = response
.text()
.await
.map_err(|error| VaultUnavailable::new(self.provider_id(), error.to_string()))?;
let payload = text
.lines()
.find_map(|line| line.strip_prefix("data: "))
.ok_or_else(|| {
VaultUnavailable::new(self.provider_id(), "MCP returned no event payload")
})?;
let value: serde_json::Value = serde_json::from_str(payload).map_err(|error| {
VaultUnavailable::new(
self.provider_id(),
format!("MCP returned an invalid event payload: {error}"),
)
})?;
if let Some(error) = value.pointer("/error/message").and_then(|v| v.as_str()) {
return Err(VaultUnavailable::new(
self.provider_id(),
format!("MCP JSON-RPC error: {error}"),
)
.into());
}
if value.pointer("/result/isError").and_then(|v| v.as_bool()) == Some(true) {
let detail = value
.pointer("/result/content/0/text")
.and_then(|v| v.as_str())
.unwrap_or("tool returned an unspecified error");
return Err(VaultUnavailable::new(
self.provider_id(),
format!("MCP tool error: {detail}"),
)
.into());
}
Ok(value)
}
fn manifest_for_query(&self, query: &VaultQuery) -> Result<&VaultSourceManifest> {
let selected = query
.authority_lanes
.iter()
.find_map(|value| canonical_vault_id(value))
.ok_or_else(|| anyhow!("Vault query has no configured Vault identity"))?;
self.manifests
.get(selected)
.ok_or_else(|| anyhow!("unknown Vault {selected}"))
}
fn manifest_for_source(&self, source_id: &str) -> Result<&VaultSourceManifest> {
let repository = source_id
.split_once(':')
.map(|(repository, _)| repository)
.ok_or_else(|| anyhow!("Vault source ID has no repository namespace"))?;
self.manifests
.values()
.find(|manifest| manifest.repository_name.eq_ignore_ascii_case(repository))
.ok_or_else(|| anyhow!("Vault source {source_id} is outside every configured Vault"))
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{Router, response::IntoResponse, routing::post};
#[test]
fn vault_unavailability_survives_anyhow_context() {
let unavailable = anyhow::Error::new(VaultUnavailable::new(
"voidbot.aetheria",
"embedding service is offline",
))
.context("world compilation retrieval failed");
assert!(is_vault_unavailable(&unavailable));
assert!(!is_vault_unavailable(&anyhow!(
"world candidate violated topology"
)));
}
#[tokio::test]
async fn voidbot_search_results_become_exact_evidence_witnesses() {
let app=Router::new().route("/mcp",post(||async { ([("content-type","text/event-stream")], "event: message\ndata: {\"result\":{\"structuredContent\":{\"results\":[{\"sourceId\":\"AetheriaLore:Aetheria/Worldbuilding/place.md\",\"path\":\"Aetheria/Worldbuilding/place.md\",\"lineStart\":7,\"lineEnd\":9,\"text\":\"The route takes six hours.\"}]}}}\n\n").into_response() }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let vault = VoidBotMcpVault::new(format!("http://{address}/mcp"));
let result = vault
.search(&VaultQuery {
query: "route".into(),
authority_lanes: vec!["AetheriaLore".into()],
temporal_scope: "era".into(),
limit: 3,
})
.await
.unwrap();
assert_eq!(
result.witnesses[0].exact_locator,
"Aetheria/Worldbuilding/place.md:7-9"
);
assert!(result.witnesses[0].content_hash.starts_with("sha256:"));
assert_eq!(
result.witnesses[0].authority_lane,
"aetheria.canon_worldbuilding"
);
}
#[tokio::test]
async fn voidbot_search_caps_requests_to_the_provider_contract() {
let app = Router::new().route(
"/mcp",
post(|axum::Json(body): axum::Json<serde_json::Value>| async move {
assert_eq!(
body.pointer("/params/arguments/limit")
.and_then(|value| value.as_u64()),
Some(VOIDBOT_SEARCH_RESULT_LIMIT as u64)
);
assert_eq!(
body.pointer("/params/arguments/pathPrefix")
.and_then(|value| value.as_str()),
Some("Aetheria/Worldbuilding/")
);
([
("content-type", "text/event-stream"),
], "event: message\ndata: {\"result\":{\"structuredContent\":{\"results\":[{\"sourceId\":\"AetheriaLore:Aetheria/Worldbuilding/place.md\",\"path\":\"Aetheria/Worldbuilding/place.md\",\"lineStart\":7,\"lineEnd\":9,\"text\":\"The route takes six hours.\"}]}}}\n\n").into_response()
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let requested = VaultQuery {
query: "route".into(),
authority_lanes: vec!["AetheriaLore".into()],
temporal_scope: "era".into(),
limit: 18,
};
let result = VoidBotMcpVault::new(format!("http://{address}/mcp"))
.search(&requested)
.await
.unwrap();
let mut effective = requested;
effective.limit = VOIDBOT_SEARCH_RESULT_LIMIT;
assert_eq!(
result.query_hash,
receipt("voidbot.aetheria", &effective, vec![]).query_hash
);
}
#[tokio::test]
async fn voidbot_exact_document_is_hashed_as_the_complete_archive_witness() {
let app=Router::new().route("/mcp",post(||async { ([ ("content-type","text/event-stream") ], "event: message\ndata: {\"result\":{\"structuredContent\":{\"found\":true,\"sourceId\":\"AetheriaLore:Aetheria/Worldbuilding/forge.md\",\"repoName\":\"AetheriaLore\",\"path\":\"Aetheria/Worldbuilding/forge.md\",\"content\":\"John keeps the forge.\\nThe road takes six hours.\",\"lastModifiedAt\":\"2026-01-01T00:00:00Z\"}}}\n\n").into_response() }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let witness = VoidBotMcpVault::new(format!("http://{address}/mcp"))
.exact_document("AetheriaLore:Aetheria/Worldbuilding/forge.md")
.await
.unwrap();
assert_eq!(
witness.excerpt,
"John keeps the forge.\nThe road takes six hours."
);
assert_eq!(witness.exact_locator, "Aetheria/Worldbuilding/forge.md");
assert_eq!(witness.authority_lane, "aetheria.canon_worldbuilding");
assert_eq!(
witness.content_hash,
format!("sha256:{:x}", Sha256::digest(witness.excerpt.as_bytes()))
);
}
#[tokio::test]
async fn voidbot_context_combines_the_typed_chunk_window() {
let app=Router::new().route("/mcp",post(||async { ([ ("content-type","text/event-stream") ], "event: message\ndata: {\"result\":{\"structuredContent\":{\"found\":true,\"sourceId\":\"AetheriaLore:Aetheria/Worldbuilding/forge.md\",\"repoName\":\"AetheriaLore\",\"path\":\"Aetheria/Worldbuilding/forge.md\",\"chunks\":[{\"lineStart\":1,\"lineEnd\":2,\"text\":\"first\"},{\"lineStart\":3,\"lineEnd\":4,\"text\":\"second\"}]}}}\n\n").into_response() }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let witness = VoidBotMcpVault::new(format!("http://{address}/mcp"))
.surrounding_context("AetheriaLore:Aetheria/Worldbuilding/forge.md", 0)
.await
.unwrap();
assert_eq!(witness.excerpt, "first\nsecond");
assert_eq!(witness.exact_locator, "Aetheria/Worldbuilding/forge.md:1-4");
}
#[test]
fn aetheria_paths_preserve_document_authority() {
assert_eq!(
authority_lane_for_path("Aetheria/Worldbuilding/Factions/Corvid.md"),
"aetheria.canon_worldbuilding"
);
assert_eq!(
authority_lane_for_path("Aetheria/Fiction/The Burden of Proof.md"),
"aetheria.canonical_fiction"
);
assert_eq!(
authority_lane_for_path("Aetheria/Stories/Corvid Collective First Exodus.md"),
"aetheria.legacy_story"
);
assert_eq!(
authority_lane_for_path("Aetheria/static/interactive/corvid.branch.json"),
"aetheria.fixture_artifact"
);
assert_eq!(
authority_lane_for_path("Aetheria/Brainstorming/Stories/draft.md"),
"aetheria.draft_working"
);
}
#[test]
fn kalsa_manifest_keeps_public_and_gm_lanes_distinct() {
let manifest = bundled_vault_manifests()
.into_iter()
.find(|manifest| manifest.id == "kalsa")
.unwrap();
assert_eq!(
authority_lane_for_source(&manifest, "Kalsa/Public/World/Magic and Miracles.md")
.unwrap(),
"kalsa.public"
);
assert_eq!(
authority_lane_for_source(
&manifest,
"Kalsa/Spoilers/Foundations/Divine Interception.md"
)
.unwrap(),
"kalsa.gm_canon"
);
assert!(
authority_lane_for_source(&manifest, "workshop/Direction and Constraints.md").is_err()
);
let public_query = VaultQuery {
query: "starting places".into(),
authority_lanes: vec!["kalsa".into(), "visibility.player".into()],
temporal_scope: "all".into(),
limit: 3,
};
assert_eq!(query_source_root(&manifest, &public_query), "Kalsa/Public/");
}
#[tokio::test]
async fn kalsa_search_is_repository_and_root_scoped() {
let app = Router::new().route(
"/mcp",
post(|axum::Json(body): axum::Json<serde_json::Value>| async move {
assert_eq!(
body.pointer("/params/arguments/repoName")
.and_then(|value| value.as_str()),
Some("Kalsa")
);
assert_eq!(
body.pointer("/params/arguments/pathPrefix")
.and_then(|value| value.as_str()),
Some("Kalsa/")
);
([
("content-type", "text/event-stream"),
], "event: message\ndata: {\"result\":{\"structuredContent\":{\"results\":[{\"sourceId\":\"Kalsa:Kalsa/Spoilers/Places/Low Sere.md\",\"path\":\"Kalsa/Spoilers/Places/Low Sere.md\",\"lineStart\":7,\"lineEnd\":9,\"text\":\"Low Sere keeps three ledgers.\"}]}}}\n\n").into_response()
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let result = VoidBotMcpVault::new(format!("http://{address}/mcp"))
.search(&VaultQuery {
query: "Low Sere".into(),
authority_lanes: vec!["kalsa".into()],
temporal_scope: "campaign start".into(),
limit: 3,
})
.await
.unwrap();
assert_eq!(result.provider, "voidbot.kalsa");
assert_eq!(result.witnesses[0].authority_lane, "kalsa.gm_canon");
}
#[tokio::test]
async fn a_vault_cannot_return_another_repository() {
let app=Router::new().route("/mcp",post(||async { ([("content-type","text/event-stream")], "event: message\ndata: {\"result\":{\"structuredContent\":{\"results\":[{\"sourceId\":\"Kalsa:Kalsa/Public/index.md\",\"path\":\"Kalsa/Public/index.md\",\"lineStart\":1,\"lineEnd\":2,\"text\":\"Wrong world.\"}]}}}\n\n").into_response() }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let error = VoidBotMcpVault::new(format!("http://{address}/mcp"))
.search(&VaultQuery {
query: "route".into(),
authority_lanes: vec!["aetheria".into()],
temporal_scope: "era".into(),
limit: 3,
})
.await
.unwrap_err();
assert!(error.to_string().contains("crossed repository boundary"));
}
}
#[async_trait]
impl VaultProvider for VoidBotMcpVault {
async fn search(&self, query: &VaultQuery) -> Result<VaultEvidenceReceipt> {
let mut effective_query = query.clone();
effective_query.limit = effective_query.limit.min(VOIDBOT_SEARCH_RESULT_LIMIT);
let manifest = self.manifest_for_query(&effective_query)?;
let source_root = query_source_root(manifest, &effective_query);
let response = self
.call_tool(
"search_sources",
serde_json::json!({
"query":effective_query.query,
"limit":effective_query.limit,
"repoName":manifest.repository_name,
"pathPrefix":source_root,
}),
)
.await?;
let results = response
.pointer("/result/structuredContent/results")
.and_then(|v| v.as_array())
.ok_or_else(|| anyhow!("VoidBot MCP returned no typed search results"))?;
let witnesses = results
.iter()
.map(|item| witness_from_result(item, &effective_query, manifest, source_root))
.collect::<Result<Vec<_>>>()?;
Ok(receipt(&manifest.provider_id, &effective_query, witnesses))
}
async fn surrounding_context(
&self,
source_id: &str,
chunk_index: u32,
) -> Result<SourceWitness> {
let response = self
.call_tool(
"get_source_context",
serde_json::json!({"sourceId":source_id,"chunkIndex":chunk_index}),
)
.await?;
let value = response
.pointer("/result/structuredContent")
.ok_or_else(|| anyhow!("VoidBot MCP returned no source context"))?;
let manifest = self.manifest_for_source(source_id)?;
let chunks = value
.get("chunks")
.and_then(|v| v.as_array())
.ok_or_else(|| anyhow!("VoidBot source context contained no chunks"))?;
let excerpt = chunks
.iter()
.filter_map(|chunk| chunk.get("text").and_then(|v| v.as_str()))
.collect::<Vec<_>>()
.join("\n");
if excerpt.is_empty() {
return Err(anyhow!("VoidBot source context contained no text"));
}
let path = value
.get("path")
.and_then(|v| v.as_str())
.unwrap_or(source_id);
validate_manifest_source(manifest, source_id, path)?;
let first_line = chunks
.first()
.and_then(|chunk| chunk.get("lineStart"))
.and_then(|v| v.as_u64());
let last_line = chunks
.last()
.and_then(|chunk| chunk.get("lineEnd"))
.and_then(|v| v.as_u64());
let exact_locator = match (first_line, last_line) {
(Some(first), Some(last)) => format!("{path}:{first}-{last}"),
_ => format!("{source_id}#chunk={chunk_index}"),
};
Ok(SourceWitness {
source_id: source_id.into(),
exact_locator,
content_hash: format!("sha256:{:x}", Sha256::digest(excerpt.as_bytes())),
excerpt,
authority_lane: authority_lane_for_source(manifest, path)?.into(),
temporal_scope: "unspecified".into(),
})
}
async fn exact_document(&self, source_id: &str) -> Result<SourceWitness> {
let response = self
.call_tool(
"get_exact_source_document",
serde_json::json!({"sourceId":source_id}),
)
.await?;
let value = response
.pointer("/result/structuredContent")
.ok_or_else(|| anyhow!("VoidBot MCP returned no exact source document"))?;
let manifest = self.manifest_for_source(source_id)?;
if value.get("found").and_then(|v| v.as_bool()) != Some(true) {
return Err(anyhow!("VoidBot exact source document was not found"));
}
let content = value
.get("content")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("VoidBot exact source document contained no content"))?;
let path = value
.get("path")
.and_then(|v| v.as_str())
.unwrap_or(source_id);
validate_manifest_source(manifest, source_id, path)?;
Ok(SourceWitness {
source_id: source_id.into(),
exact_locator: path.into(),
content_hash: format!("sha256:{:x}", Sha256::digest(content.as_bytes())),
excerpt: content.into(),
authority_lane: authority_lane_for_source(manifest, path)?.into(),
temporal_scope: value
.get("lastModifiedAt")
.and_then(|v| v.as_str())
.unwrap_or("unspecified")
.into(),
})
}
fn provider_id(&self) -> &'static str {
"voidbot.aetheria"
}
}
fn witness_from_result(
item: &serde_json::Value,
query: &VaultQuery,
manifest: &VaultSourceManifest,
required_root: &str,
) -> Result<SourceWitness> {
let source_id = item
.get("sourceId")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("search result missing sourceId"))?;
let excerpt = item
.get("text")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("search result missing text"))?;
let locator = match (
item.get("path").and_then(|v| v.as_str()),
item.get("lineStart").and_then(|v| v.as_u64()),
item.get("lineEnd").and_then(|v| v.as_u64()),
) {
(Some(path), Some(start), Some(end)) => format!("{path}:{start}-{end}"),
_ => source_id.into(),
};
let path = item
.get("path")
.and_then(|value| value.as_str())
.unwrap_or(source_id);
validate_manifest_source(manifest, source_id, path)?;
validate_source_root(required_root, path)?;
Ok(SourceWitness {
source_id: source_id.into(),
exact_locator: locator,
content_hash: format!("sha256:{:x}", Sha256::digest(excerpt.as_bytes())),
excerpt: excerpt.into(),
authority_lane: authority_lane_for_source(manifest, path)?.into(),
temporal_scope: query.temporal_scope.clone(),
})
}
fn query_source_root<'a>(manifest: &'a VaultSourceManifest, query: &VaultQuery) -> &'a str {
if manifest.id == "kalsa"
&& query
.authority_lanes
.iter()
.any(|lane| lane == "visibility.player")
{
"Kalsa/Public/"
} else {
&manifest.source_root
}
}
fn validate_source_root(required_root: &str, path: &str) -> Result<()> {
if !path
.replace('\\', "/")
.to_ascii_lowercase()
.starts_with(&required_root.to_ascii_lowercase())
{
return Err(anyhow!(
"Vault provider crossed requested visibility boundary: expected {required_root}, received {path}"
));
}
Ok(())
}
fn validate_manifest_source(
manifest: &VaultSourceManifest,
source_id: &str,
path: &str,
) -> Result<()> {
let repository = source_id
.split_once(':')
.map(|(repository, _)| repository)
.ok_or_else(|| anyhow!("Vault source ID has no repository namespace"))?;
if !repository.eq_ignore_ascii_case(&manifest.repository_name) {
return Err(anyhow!(
"Vault provider crossed repository boundary: expected {}, received {source_id}",
manifest.repository_name
));
}
let normalized_path = path.replace('\\', "/");
if !normalized_path
.to_ascii_lowercase()
.starts_with(&manifest.source_root.to_ascii_lowercase())
{
return Err(anyhow!(
"Vault provider crossed source-root boundary: expected {}, received {path}",
manifest.source_root
));
}
Ok(())
}
fn authority_lane_for_source(manifest: &VaultSourceManifest, path: &str) -> Result<&'static str> {
match manifest.id.as_str() {
"aetheria" => Ok(authority_lane_for_path(path)),
"kalsa" => {
let normalized = path.replace('\\', "/").to_ascii_lowercase();
if normalized.starts_with("kalsa/public/") {
Ok("kalsa.public")
} else if normalized.starts_with("kalsa/spoilers/") {
Ok("kalsa.gm_canon")
} else if normalized == "kalsa/index.md" {
Ok("kalsa.navigation")
} else {
Err(anyhow!(
"Kalsa source path has no admitted authority lane: {path}"
))
}
}
other => Err(anyhow!("Vault {other} has no authority classifier")),
}
}
/// Classify source authority at the Vault boundary. Downstream models receive a
/// typed document role instead of having to infer authority from prose.
fn authority_lane_for_path(path: &str) -> &'static str {
let normalized = path.replace('\\', "/").to_ascii_lowercase();
if normalized.contains("/static/interactive/") {
"aetheria.fixture_artifact"
} else if normalized.contains("/brainstorming/") {
"aetheria.draft_working"
} else if normalized.contains("/game design/") {
"aetheria.design_reference"
} else if normalized.contains("/fiction/") {
"aetheria.canonical_fiction"
} else if normalized.contains("/stories/") {
"aetheria.legacy_story"
} else if normalized.contains("/worldbuilding/") {
"aetheria.canon_worldbuilding"
} else {
"aetheria.vault_document"
}
}
fn receipt(
provider: &str,
query: &VaultQuery,
witnesses: Vec<SourceWitness>,
) -> VaultEvidenceReceipt {
let query_bytes = rmp_serde::to_vec_named(query).expect("query serializes");
let query_hash = format!("sha256:{:x}", Sha256::digest(query_bytes));
let retrieved_at = Utc::now();
let receipt_bytes =
rmp_serde::to_vec_named(&(provider, &query_hash, &witnesses, &retrieved_at))
.expect("vault receipt identity serializes");
VaultEvidenceReceipt {
schema: "ghostlight.vault_evidence_receipt.v1".into(),
id: format!("vault:sha256:{:x}", Sha256::digest(receipt_bytes)),
provider: provider.into(),
query_hash,
witnesses,
retrieved_at,
}
}

View file

@ -1,49 +0,0 @@
use anyhow::{Context, Result, anyhow};
use std::{fs, path::Path, slice};
use windows::Win32::{
Foundation::{HLOCAL, LocalFree},
Security::Cryptography::{CRYPT_INTEGER_BLOB, CryptUnprotectData},
};
use zeroize::Zeroizing;
/// Decrypts a machine-scoped DPAPI blob. DPAPI authenticates the blob and
/// Windows owns the returned allocation; the plaintext is copied once into a
/// zeroizing UTF-8 buffer and the Windows allocation is immediately released.
pub fn unprotect_machine_utf8(path: impl AsRef<Path>) -> Result<String> {
let mut protected = fs::read(path.as_ref())
.with_context(|| format!("read DPAPI secret {}", path.as_ref().display()))?;
if protected.is_empty() {
return Err(anyhow!("DPAPI secret blob is empty"));
}
let input = CRYPT_INTEGER_BLOB {
cbData: u32::try_from(protected.len()).context("DPAPI blob is too large")?,
pbData: protected.as_mut_ptr(),
};
let mut output = CRYPT_INTEGER_BLOB::default();
unsafe {
CryptUnprotectData(&input, None, None, None, None, 0, &mut output)
.context("CryptUnprotectData failed")?;
}
if output.pbData.is_null() || output.cbData == 0 {
return Err(anyhow!("DPAPI returned no plaintext"));
}
let plaintext = unsafe { slice::from_raw_parts(output.pbData, output.cbData as usize) };
let zeroizing = Zeroizing::new(plaintext.to_vec());
unsafe {
let _ = LocalFree(Some(HLOCAL(output.pbData.cast())));
}
let value = String::from_utf8(zeroizing.to_vec()).context("DPAPI secret is not UTF-8")?;
if value.trim().is_empty() {
return Err(anyhow!("DPAPI secret plaintext is empty"));
}
Ok(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_absent_blob_without_secret_material() {
assert!(unprotect_machine_utf8("definitely-absent.dpapi").is_err());
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
use super::{
COMMIT_SCHEMA, CommandId, EventId, KernelError, STATE_SCHEMA, WorldCommit, WorldEffect,
WorldId, WorldState, apply_effect, commit_digest, state_digest,
COMMIT_SCHEMA, CommandId, CommittedCommand, KernelError, STATE_SCHEMA, WorldCommit,
WorldEffect, WorldId, WorldState, apply_effect, commit_digest, reduce, state_digest,
};
use chrono::Utc;
use cultcache_legacy::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
@ -13,16 +13,12 @@ use std::{
use thiserror::Error;
const STATE_ROW: &str = "world_state.foundation.v0";
const COMMIT_ROW: &str = "world_commit.foundation.v0";
const COMMIT_ROW: &str = "world_commit.foundation.v1";
#[derive(Debug, Error)]
pub(super) enum JournalError {
#[error("world store is not empty")]
NotEmpty,
#[error("opened store contains another world")]
WorldMismatch,
#[error("world creation ID was reused with different content")]
CreationConflict,
#[error("world ownership is uncertain after command {command_id:?}; drop and reopen")]
RecoveryRequired { command_id: CommandId },
#[error("world store path no longer names the owned database")]
@ -33,9 +29,9 @@ pub(super) enum JournalError {
Corrupt(String),
}
pub(super) enum CreationOpen {
pub(super) enum JournalOpen {
Empty(EmptyWorldJournal),
Existing {
Live {
journal: WorldJournal,
state: WorldState,
},
@ -43,6 +39,8 @@ pub(super) enum CreationOpen {
pub(super) struct EmptyWorldJournal {
store: OwnedRedbMessagePackBackingStore,
#[cfg(test)]
fail_after_durable_initialize: bool,
}
#[derive(Clone, Copy)]
@ -62,11 +60,7 @@ pub(super) struct WorldJournal {
}
impl WorldJournal {
pub(super) fn open_for_creation(
path: &Path,
creation_id: CommandId,
creation_digest: &str,
) -> Result<CreationOpen, JournalError> {
pub(super) fn open_owner(path: &Path) -> Result<JournalOpen, JournalError> {
let store = OwnedRedbMessagePackBackingStore::new(path)
.map_err(|error| JournalError::Store(error.to_string()))?;
store
@ -79,18 +73,14 @@ impl WorldJournal {
.validate_path_identity()
.map_err(|_| JournalError::OwnershipLost)?;
if rows.is_empty() {
return Ok(CreationOpen::Empty(EmptyWorldJournal { store }));
return Ok(JournalOpen::Empty(EmptyWorldJournal {
store,
#[cfg(test)]
fail_after_durable_initialize: false,
}));
}
let (state_row, state, commits) = recover(rows, None)?;
let Some(genesis) = commits.get(&creation_id) else {
return Err(JournalError::NotEmpty);
};
if genesis.command_digest != creation_digest
|| !matches!(&genesis.effect, WorldEffect::WorldCreated { .. })
{
return Err(JournalError::CreationConflict);
}
Ok(CreationOpen::Existing {
Ok(JournalOpen::Live {
journal: Self {
store,
state_row,
@ -153,7 +143,8 @@ impl WorldJournal {
commit: &WorldCommit,
) -> Result<(), JournalError> {
self.ensure_healthy()?;
if self.commits.contains_key(&commit.command_id) {
let command_id = commit.command.id();
if self.commits.contains_key(&command_id) {
return Err(JournalError::Corrupt(
"single-owner append attempted to duplicate a committed command".into(),
));
@ -161,9 +152,8 @@ impl WorldJournal {
let current: WorldState = decode(&self.state_row)?;
verify_append(&current, next, commit)?;
let next_row = envelope(STATE_ROW, STATE_SCHEMA, next.world_id.key(), next)?;
let commit_row = envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command_id.key(), commit)?;
self.health
.set(JournalHealth::RecoveryRequired(commit.command_id));
let commit_row = envelope(COMMIT_ROW, COMMIT_SCHEMA, command_id.key(), commit)?;
self.health.set(JournalHealth::RecoveryRequired(command_id));
let swapped = self.store.compare_and_swap_batch(
std::slice::from_ref(&self.state_row),
vec![next_row.clone(), commit_row],
@ -171,24 +161,18 @@ impl WorldJournal {
match swapped {
Ok(true) => {}
Ok(false) | Err(_) => {
return Err(JournalError::RecoveryRequired {
command_id: commit.command_id,
});
return Err(JournalError::RecoveryRequired { command_id });
}
}
#[cfg(test)]
if self.fail_after_durable_commit {
return Err(JournalError::RecoveryRequired {
command_id: commit.command_id,
});
return Err(JournalError::RecoveryRequired { command_id });
}
if self.store.validate_path_identity().is_err() {
return Err(JournalError::RecoveryRequired {
command_id: commit.command_id,
});
return Err(JournalError::RecoveryRequired { command_id });
}
self.state_row = next_row;
self.commits.insert(commit.command_id, commit.clone());
self.commits.insert(command_id, commit.clone());
self.health.set(JournalHealth::Healthy);
Ok(())
}
@ -209,6 +193,11 @@ impl WorldJournal {
}
impl EmptyWorldJournal {
#[cfg(test)]
pub(super) fn fail_after_durable_initialize_for_test(&mut self) {
self.fail_after_durable_initialize = true;
}
pub(super) fn initialize(
self,
state: &WorldState,
@ -218,21 +207,23 @@ impl EmptyWorldJournal {
.validate_path_identity()
.map_err(|_| JournalError::OwnershipLost)?;
let mut commits = BTreeMap::new();
commits.insert(genesis.command_id, genesis.clone());
let command_id = genesis.command.id();
commits.insert(command_id, genesis.clone());
verify_history(state, &commits)?;
let state_row = envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state)?;
let commit_row = envelope(COMMIT_ROW, COMMIT_SCHEMA, genesis.command_id.key(), genesis)?;
let commit_row = envelope(COMMIT_ROW, COMMIT_SCHEMA, command_id.key(), genesis)?;
let inserted = self
.store
.append_if_snapshot_unchanged(&[], vec![state_row.clone(), commit_row])
.map_err(|error| JournalError::Store(error.to_string()))?;
if !inserted {
return Err(JournalError::NotEmpty);
.append_if_snapshot_unchanged(&[], vec![state_row.clone(), commit_row]);
if !matches!(inserted, Ok(true)) {
return Err(JournalError::RecoveryRequired { command_id });
}
#[cfg(test)]
if self.fail_after_durable_initialize {
return Err(JournalError::RecoveryRequired { command_id });
}
if self.store.validate_path_identity().is_err() {
return Err(JournalError::RecoveryRequired {
command_id: genesis.command_id,
});
return Err(JournalError::RecoveryRequired { command_id });
}
Ok(WorldJournal {
store: self.store,
@ -267,12 +258,13 @@ fn recover(
COMMIT_ROW => {
require_schema(&row, COMMIT_SCHEMA)?;
let commit: WorldCommit = decode(&row)?;
if row.key != commit.command_id.key() {
let command_id = commit.command.id();
if row.key != command_id.key() {
return Err(JournalError::Corrupt(
"commit row key does not match command ID".into(),
));
}
if commits.insert(commit.command_id, commit).is_some() {
if commits.insert(command_id, commit).is_some() {
return Err(JournalError::Corrupt("duplicate command commit".into()));
}
}
@ -332,8 +324,7 @@ fn verify_append(
return Err(JournalError::Corrupt("digest mismatch".into()));
}
let mut replay = current.clone();
verify_effect_command_binding(commit)?;
apply_effect(&mut replay, &commit.caller, &commit.effect).map_err(kernel_error)?;
apply_committed_command(&mut replay, commit)?;
replay.revision = next.revision;
replay.state_digest = state_digest(&replay).map_err(kernel_error)?;
replay.last_commit_digest = Some(commit.digest.clone());
@ -350,6 +341,14 @@ fn verify_history(
commits: &BTreeMap<CommandId, WorldCommit>,
) -> Result<(), JournalError> {
verify_state_shape(state)?;
if commits
.iter()
.any(|(command_id, commit)| *command_id != commit.command.id())
{
return Err(JournalError::Corrupt(
"commit index does not derive from the persisted command".into(),
));
}
let expected_commits = usize::try_from(state.revision)
.map_err(|_| JournalError::Corrupt("revision does not fit this runtime".into()))?;
let expected_commits = expected_commits
@ -365,6 +364,11 @@ fn verify_history(
let genesis = ordered
.first()
.ok_or_else(|| JournalError::Corrupt("world has no genesis commit".into()))?;
let CommittedCommand::CreateWorld(genesis_command) = &genesis.command else {
return Err(JournalError::Corrupt(
"first commit does not contain the immutable creation command".into(),
));
};
let WorldEffect::WorldCreated { .. } = &genesis.effect else {
return Err(JournalError::Corrupt(
"first commit is not immutable world genesis".into(),
@ -382,7 +386,7 @@ fn verify_history(
"genesis commit is not canonical or verifiable".into(),
));
}
let mut replay = WorldState::genesis(state.world_id, &genesis.caller, &genesis.effect)
let mut replay = WorldState::genesis(state.world_id, genesis_command, &genesis.effect)
.map_err(kernel_error)?;
verify_state_shape(&replay)?;
if replay.state_digest != genesis.resulting_state_digest {
@ -405,8 +409,7 @@ fn verify_history(
"commit chain is not contiguous or verifiable".into(),
));
}
verify_effect_command_binding(commit)?;
apply_effect(&mut replay, &commit.caller, &commit.effect).map_err(kernel_error)?;
apply_committed_command(&mut replay, commit)?;
replay.revision = commit.resulting_revision;
replay.state_digest = state_digest(&replay).map_err(kernel_error)?;
if replay.state_digest != commit.resulting_state_digest {
@ -519,7 +522,7 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> {
|| event.controller_id != assignment.id()
|| grant.scope != event.scope
|| grant.kind != event.invocation.action.kind()
|| super::canonical_invocation(&event.invocation).map_err(kernel_error)?
|| super::validated_invocation(&event.invocation).map_err(kernel_error)?
!= event.invocation
{
return Err(JournalError::Corrupt(
@ -531,15 +534,27 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> {
Ok(())
}
fn verify_effect_command_binding(commit: &WorldCommit) -> Result<(), JournalError> {
if let WorldEffect::DecisionExercised { event, .. } = &commit.effect
&& event.id != EventId::for_command(commit.command_id)
{
fn apply_committed_command(
state: &mut WorldState,
commit: &WorldCommit,
) -> Result<(), JournalError> {
let CommittedCommand::WorldCommand(command) = &commit.command else {
return Err(JournalError::Corrupt(
"decision event ID is not bound to its command".into(),
"creation command appears after world genesis".into(),
));
};
if command.world_id != state.world_id || command.expected_revision != state.revision {
return Err(JournalError::Corrupt(
"committed command does not target the exact replay state".into(),
));
}
Ok(())
let expected_effect = reduce(state, command).map_err(kernel_error)?;
if expected_effect != commit.effect {
return Err(JournalError::Corrupt(
"committed effect is not the deterministic reduction of its command".into(),
));
}
apply_effect(state, &commit.command.caller(), &expected_effect).map_err(kernel_error)
}
fn require_schema(row: &CultCacheEnvelope, schema: &str) -> Result<(), JournalError> {
@ -569,13 +584,22 @@ fn envelope<T: Serialize>(
})
}
fn decode<T: DeserializeOwned>(row: &CultCacheEnvelope) -> Result<T, JournalError> {
rmp_serde::from_slice(&row.payload).map_err(|error| {
fn decode<T: DeserializeOwned + Serialize>(row: &CultCacheEnvelope) -> Result<T, JournalError> {
let value: T = rmp_serde::from_slice(&row.payload).map_err(|error| {
JournalError::Corrupt(format!(
"could not decode row {}/{}: {error}",
row.r#type, row.key
))
})
})?;
let canonical = rmp_serde::to_vec_named(&value)
.map_err(|error| JournalError::Corrupt(error.to_string()))?;
if canonical != row.payload {
return Err(JournalError::Corrupt(format!(
"row {}/{} is not canonical",
row.r#type, row.key
)));
}
Ok(value)
}
fn kernel_error(error: KernelError) -> JournalError {
@ -591,8 +615,25 @@ mod tests {
WorldKernel,
};
#[derive(serde::Serialize, serde::Deserialize)]
struct CanonicalFixture {
value: u8,
}
#[test]
fn replay_rejects_a_semantically_forged_caller_even_with_valid_hashes() {
fn decode_rejects_an_alternate_messagepack_shape() {
let row = CultCacheEnvelope {
key: "fixture".into(),
r#type: "fixture".into(),
payload: rmp_serde::to_vec(&CanonicalFixture { value: 7 }).unwrap(),
stored_at: Utc::now().to_rfc3339(),
schema_id: Some("fixture.v0".into()),
};
assert!(decode::<CanonicalFixture>(&row).is_err());
}
#[test]
fn replay_rejects_a_forged_command_or_effect_even_with_valid_hashes() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("world.cc");
let owner = PrincipalId::new("owner@example.test");
@ -621,18 +662,82 @@ mod tests {
world_id: snapshot.world_id,
expected_revision: snapshot.revision,
caller: CallerId::Principal(owner),
body: CommandBody::SetTitle {
title: "After".into(),
},
body: CommandBody::ApproveDraft,
},
&authenticated,
)
.unwrap();
let mut command_forged_head = kernel.state.clone();
let mut command_forged_commits = kernel.journal.commits.clone();
let command_forged = command_forged_commits.get_mut(&command_id).unwrap();
let CommittedCommand::WorldCommand(command) = &mut command_forged.command else {
panic!("expected a world command");
};
command.body = CommandBody::ActivateWorld;
command_forged.digest = commit_digest(command_forged).unwrap();
command_forged_head.last_commit_digest = Some(command_forged.digest.clone());
assert!(matches!(
verify_history(&command_forged_head, &command_forged_commits),
Err(JournalError::Corrupt(_))
));
let mut caller_forged_head = kernel.state.clone();
let mut caller_forged_commits = kernel.journal.commits.clone();
let caller_forged = caller_forged_commits.get_mut(&command_id).unwrap();
let CommittedCommand::WorldCommand(command) = &mut caller_forged.command else {
panic!("expected a world command");
};
command.caller = CallerId::Principal(PrincipalId::new("attacker@example.test"));
caller_forged.digest = commit_digest(caller_forged).unwrap();
caller_forged_head.last_commit_digest = Some(caller_forged.digest.clone());
assert!(matches!(
verify_history(&caller_forged_head, &caller_forged_commits),
Err(JournalError::Corrupt(_))
));
let mut effect_forged_head = kernel.state.clone();
let mut effect_forged_commits = kernel.journal.commits.clone();
let effect_forged = effect_forged_commits.get_mut(&command_id).unwrap();
effect_forged.effect = WorldEffect::WorldActivated;
effect_forged.digest = commit_digest(effect_forged).unwrap();
effect_forged_head.last_commit_digest = Some(effect_forged.digest.clone());
assert!(matches!(
verify_history(&effect_forged_head, &effect_forged_commits),
Err(JournalError::Corrupt(_))
));
}
#[test]
fn replay_rejects_genesis_that_does_not_derive_from_its_creation_command() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("world.cc");
let owner = PrincipalId::new("owner@example.test");
let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone()));
let creation_id = CommandId::new();
let creation = CreateWorld {
id: creation_id,
owner: owner.clone(),
title: "Admitted".into(),
subjects: vec![NewDecisionSubject {
handle: DraftSubjectHandle::new("owner"),
label: "Owner".into(),
kind: SubjectKind::Person,
controller: NewController::Human { principal: owner },
affordances: BTreeSet::from([AffordanceKind::Speak]),
}],
};
let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
let mut forged_head = kernel.state.clone();
let mut forged_commits = kernel.journal.commits.clone();
let forged = forged_commits.get_mut(&command_id).unwrap();
forged.caller = CallerId::Principal(PrincipalId::new("attacker@example.test"));
let forged = forged_commits.get_mut(&creation_id).unwrap();
let CommittedCommand::CreateWorld(command) = &mut forged.command else {
panic!("expected genesis creation command");
};
command.title = "Different command".into();
forged.digest = commit_digest(forged).unwrap();
forged_head.last_commit_digest = Some(forged.digest.clone());
@ -640,5 +745,20 @@ mod tests {
verify_history(&forged_head, &forged_commits),
Err(JournalError::Corrupt(_))
));
let mut binding_forged_head = kernel.state.clone();
let mut binding_forged_commits = kernel.journal.commits.clone();
let binding_forged = binding_forged_commits.get_mut(&creation_id).unwrap();
let WorldEffect::WorldCreated { bindings, .. } = &mut binding_forged.effect else {
panic!("expected genesis effect");
};
bindings[0].subject.label = "Not the creation subject".into();
binding_forged.digest = commit_digest(binding_forged).unwrap();
binding_forged_head.last_commit_digest = Some(binding_forged.digest.clone());
assert!(matches!(
verify_history(&binding_forged_head, &binding_forged_commits),
Err(JournalError::Corrupt(_))
));
}
}

View file

@ -1,7 +1,12 @@
use super::{
AuthenticatedCaller, CommandEnvelope, CommandId, KernelError, SubmitReceipt, WorldKernel,
WorldSnapshot,
AffordanceKind, AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId,
CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity,
DraftSubjectHandle, KernelError, NewController, NewDecisionSubject, PrincipalCommandIntent,
PrincipalId, SubjectKind, SubmitReceipt, WorldKernel, WorldSnapshot, journal, prepare_creation,
};
use crate::app_session::VerifiedPrincipalEvidence;
use std::collections::BTreeSet;
use std::path::Path;
use thiserror::Error;
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
@ -13,7 +18,17 @@ pub(crate) struct WorldMailbox {
sender: mpsc::Sender<Request>,
}
enum OwnedWorld {
Empty(journal::EmptyWorldJournal),
Live(WorldKernel),
}
enum Request {
Create {
input: CreateWorld,
authenticated: AuthenticatedCaller,
reply: oneshot::Sender<Result<CreationReceipt, KernelError>>,
},
Submit {
command: CommandEnvelope,
authenticated: AuthenticatedCaller,
@ -22,6 +37,17 @@ enum Request {
Snapshot {
reply: oneshot::Sender<Result<WorldSnapshot, KernelError>>,
},
ControllerReceipt {
command_id: CommandId,
opportunity: super::DecisionOpportunity,
invocation: super::DecisionInvocation,
reply: oneshot::Sender<Result<Option<super::CommitReceipt>, KernelError>>,
},
ControllerDeclineReceipt {
command_id: CommandId,
opportunity: super::DecisionOpportunity,
reply: oneshot::Sender<Result<Option<super::CommitReceipt>, KernelError>>,
},
}
#[derive(Debug, Error)]
@ -35,41 +61,74 @@ pub(crate) enum MailboxError {
}
impl WorldMailbox {
pub(crate) fn spawn(kernel: WorldKernel) -> (Self, JoinHandle<()>) {
let (sender, mut receiver) = mpsc::channel(REQUEST_CAPACITY);
let task = tokio::spawn(async move {
let mut kernel = kernel;
while let Some(request) = receiver.recv().await {
match request {
Request::Submit {
command,
authenticated,
reply,
} => {
let result = kernel.submit(command, &authenticated);
let _ = reply.send(result);
}
Request::Snapshot { reply } => {
let result = kernel.snapshot();
let _ = reply.send(result);
}
}
pub(crate) fn open(path: impl AsRef<Path>) -> Result<(Self, JoinHandle<()>), KernelError> {
let owned = match journal::WorldJournal::open_owner(path.as_ref())? {
journal::JournalOpen::Empty(empty) => OwnedWorld::Empty(empty),
journal::JournalOpen::Live { journal, state } => {
OwnedWorld::Live(WorldKernel { state, journal })
}
});
(Self { sender }, task)
};
let (sender, receiver) = mpsc::channel(REQUEST_CAPACITY);
let task = tokio::spawn(run_owner(owned, receiver));
Ok((Self { sender }, task))
}
pub(crate) async fn submit(
pub(crate) async fn create(
&self,
command: CommandEnvelope,
authenticated: &AuthenticatedCaller,
) -> Result<SubmitReceipt, MailboxError> {
let command_id = command.id;
input: CreateWorldIntent,
principal: &VerifiedPrincipalEvidence,
) -> Result<CreationReceipt, MailboxError> {
let principal_id = PrincipalId::new(principal.account_subject_hash());
let mut subjects = vec![NewDecisionSubject {
handle: DraftSubjectHandle::new("first-person"),
label: input.human_subject_label,
kind: SubjectKind::Person,
controller: NewController::Human {
principal: principal_id.clone(),
},
affordances: BTreeSet::from([AffordanceKind::Speak]),
}];
if let Some(label) = input.narrative_persona_label {
subjects.push(NewDecisionSubject {
handle: DraftSubjectHandle::new("narrative-persona"),
label,
kind: SubjectKind::Person,
controller: NewController::NarrativePersona,
affordances: BTreeSet::from([AffordanceKind::Speak]),
});
}
if let Some(label) = input.operational_agent_label {
subjects.push(NewDecisionSubject {
handle: DraftSubjectHandle::new("operational-agent"),
label,
kind: SubjectKind::Institution,
controller: NewController::OperationalAgent,
affordances: BTreeSet::from([AffordanceKind::Speak]),
});
}
self.create_authenticated(
CreateWorld {
id: input.id,
owner: principal_id.clone(),
title: input.title,
subjects,
},
AuthenticatedCaller::verified_principal(principal_id),
)
.await
}
async fn create_authenticated(
&self,
input: CreateWorld,
authenticated: AuthenticatedCaller,
) -> Result<CreationReceipt, MailboxError> {
let command_id = input.id;
let (reply, response) = oneshot::channel();
self.sender
.send(Request::Submit {
command,
authenticated: authenticated.clone(),
.send(Request::Create {
input,
authenticated,
reply,
})
.await
@ -78,7 +137,114 @@ impl WorldMailbox {
response
.await
.map_err(|_| MailboxError::OutcomeUnknown { command_id })?
.map_err(MailboxError::Kernel)
.map_err(mailbox_outcome)
}
pub(crate) async fn submit_principal(
&self,
intent: PrincipalCommandIntent,
principal: &VerifiedPrincipalEvidence,
) -> Result<SubmitReceipt, MailboxError> {
let principal_id = PrincipalId::new(principal.account_subject_hash());
self.submit_authenticated(
CommandEnvelope {
id: intent.id,
world_id: intent.world_id,
expected_revision: intent.expected_revision,
caller: CallerId::Principal(principal_id.clone()),
body: intent.body,
},
AuthenticatedCaller::verified_principal(principal_id),
)
.await
}
async fn submit_authenticated(
&self,
command: CommandEnvelope,
authenticated: AuthenticatedCaller,
) -> Result<SubmitReceipt, MailboxError> {
let command_id = command.id;
let (reply, response) = oneshot::channel();
self.sender
.send(Request::Submit {
command,
authenticated,
reply,
})
.await
.map_err(|_| MailboxError::Unavailable)?;
response
.await
.map_err(|_| MailboxError::OutcomeUnknown { command_id })?
.map_err(mailbox_outcome)
}
/// Controller-only commit port. This method is visible inside the world
/// subtree, where the controller organ lives, but not to runtime ingress.
pub(super) async fn submit_controller(
&self,
command_id: CommandId,
opportunity: &DecisionOpportunity,
invocation: DecisionInvocation,
) -> Result<SubmitReceipt, MailboxError> {
let controller_id = opportunity.controller_id;
self.submit_authenticated(
CommandEnvelope {
id: command_id,
world_id: opportunity.world_id,
expected_revision: opportunity.revision,
caller: CallerId::Controller(controller_id),
body: CommandBody::ExerciseDecision {
opportunity: opportunity.clone(),
invocation,
},
},
AuthenticatedCaller::verified_controller(controller_id),
)
.await
}
pub(super) async fn submit_controller_decline(
&self,
command_id: CommandId,
opportunity: &DecisionOpportunity,
) -> Result<SubmitReceipt, MailboxError> {
let controller_id = opportunity.controller_id;
self.submit_authenticated(
CommandEnvelope {
id: command_id,
world_id: opportunity.world_id,
expected_revision: opportunity.revision,
caller: CallerId::Controller(controller_id),
body: CommandBody::DeclineDecision {
opportunity: opportunity.clone(),
},
},
AuthenticatedCaller::verified_controller(controller_id),
)
.await
}
#[cfg(test)]
pub(super) async fn create_fixture(
&self,
input: CreateWorld,
authenticated: &AuthenticatedCaller,
) -> Result<CreationReceipt, MailboxError> {
self.create_authenticated(input, authenticated.clone())
.await
}
#[cfg(test)]
pub(super) async fn submit_fixture(
&self,
command: CommandEnvelope,
authenticated: &AuthenticatedCaller,
) -> Result<SubmitReceipt, MailboxError> {
self.submit_authenticated(command, authenticated.clone())
.await
}
pub(crate) async fn snapshot(&self) -> Result<WorldSnapshot, MailboxError> {
@ -93,31 +259,194 @@ impl WorldMailbox {
.map_err(|_| MailboxError::Unavailable)?
.map_err(MailboxError::Kernel)
}
pub(super) async fn controller_receipt(
&self,
command_id: CommandId,
opportunity: &super::DecisionOpportunity,
invocation: &super::DecisionInvocation,
) -> Result<Option<super::CommitReceipt>, MailboxError> {
let (reply, response) = oneshot::channel();
self.sender
.send(Request::ControllerReceipt {
command_id,
opportunity: opportunity.clone(),
invocation: invocation.clone(),
reply,
})
.await
.map_err(|_| MailboxError::Unavailable)?;
response
.await
.map_err(|_| MailboxError::Unavailable)?
.map_err(MailboxError::Kernel)
}
pub(super) async fn controller_decline_receipt(
&self,
command_id: CommandId,
opportunity: &super::DecisionOpportunity,
) -> Result<Option<super::CommitReceipt>, MailboxError> {
let (reply, response) = oneshot::channel();
self.sender
.send(Request::ControllerDeclineReceipt {
command_id,
opportunity: opportunity.clone(),
reply,
})
.await
.map_err(|_| MailboxError::Unavailable)?;
response
.await
.map_err(|_| MailboxError::Unavailable)?
.map_err(MailboxError::Kernel)
}
}
fn mailbox_outcome(error: KernelError) -> MailboxError {
match error {
KernelError::RecoveryRequired { command_id } => MailboxError::OutcomeUnknown { command_id },
other => MailboxError::Kernel(other),
}
}
async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver<Request>) {
while let Some(request) = receiver.recv().await {
match request {
Request::Create {
input,
authenticated,
reply,
} => {
let prepared = match prepare_creation(input, &authenticated) {
Ok(prepared) => prepared,
Err(error) => {
let _ = reply.send(Err(error));
continue;
}
};
if let OwnedWorld::Live(kernel) = &owned {
let result = kernel.retry_creation(&prepared);
let owner_must_stop = result
.as_ref()
.is_err_and(KernelError::requires_owner_restart);
let _ = reply.send(result);
if owner_must_stop {
return;
}
continue;
}
let OwnedWorld::Empty(empty) = owned else {
unreachable!("live owner returned above")
};
match WorldKernel::initialize(empty, prepared) {
Ok((kernel, receipt)) => {
owned = OwnedWorld::Live(kernel);
let _ = reply.send(Ok(receipt));
}
Err(error) => {
// Initialization consumed the sole journal handle. Its
// durability is uncertain, so this owner must release
// the path and make callers reopen explicitly.
let _ = reply.send(Err(error));
return;
}
}
}
Request::Submit {
command,
authenticated,
reply,
} => {
let result = match &mut owned {
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
OwnedWorld::Live(kernel) => kernel.submit(command, &authenticated),
};
let owner_must_stop = result
.as_ref()
.is_err_and(KernelError::requires_owner_restart);
let _ = reply.send(result);
if owner_must_stop {
return;
}
}
Request::Snapshot { reply } => {
let result = match &owned {
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
OwnedWorld::Live(kernel) => kernel.snapshot(),
};
let owner_must_stop = result
.as_ref()
.is_err_and(KernelError::requires_owner_restart);
let _ = reply.send(result);
if owner_must_stop {
return;
}
}
Request::ControllerReceipt {
command_id,
opportunity,
invocation,
reply,
} => {
let result = match &owned {
OwnedWorld::Empty(_) => Ok(None),
OwnedWorld::Live(kernel) => {
kernel.controller_receipt(command_id, &opportunity, &invocation)
}
};
let owner_must_stop = result
.as_ref()
.is_err_and(KernelError::requires_owner_restart);
let _ = reply.send(result);
if owner_must_stop {
return;
}
}
Request::ControllerDeclineReceipt {
command_id,
opportunity,
reply,
} => {
let result = match &owned {
OwnedWorld::Empty(_) => Ok(None),
OwnedWorld::Live(kernel) => {
kernel.controller_decline_receipt(command_id, &opportunity)
}
};
let owner_must_stop = result
.as_ref()
.is_err_and(KernelError::requires_owner_restart);
let _ = reply.send(result);
if owner_must_stop {
return;
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::world::{
AffordanceKind, CallerId, CommandBody, CreateWorld, DraftSubjectHandle, NewController,
NewDecisionSubject, PrincipalId, SubjectKind,
AffordanceKind, CallerId, CommandBody, DraftSubjectHandle, NewController,
NewDecisionSubject, PrincipalId, SubjectKind, WorldId,
};
use std::collections::BTreeSet;
use std::{collections::BTreeSet, path::PathBuf};
use tempfile::TempDir;
fn fixture() -> (
TempDir,
WorldKernel,
AuthenticatedCaller,
crate::world::WorldId,
) {
let directory = tempfile::tempdir().expect("temporary world directory");
let owner = PrincipalId::new("owner");
let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone()));
let input = CreateWorld {
id: CommandId::new(),
owner,
title: "Mailbox World".into(),
fn authenticated_owner() -> AuthenticatedCaller {
AuthenticatedCaller::fixture(CallerId::Principal(PrincipalId::new("owner")))
}
fn creation(id: CommandId, title: &str) -> CreateWorld {
CreateWorld {
id,
owner: PrincipalId::new("owner"),
title: title.into(),
subjects: vec![NewDecisionSubject {
handle: DraftSubjectHandle::new("operator"),
label: "Operator".into(),
@ -127,42 +456,186 @@ mod tests {
},
affordances: BTreeSet::from([AffordanceKind::Speak]),
}],
};
let (kernel, receipt) =
WorldKernel::create(directory.path().join("world.cc"), input, &authenticated)
.expect("create fixture world");
(directory, kernel, authenticated, receipt.world_id)
}
}
fn title_command(
world_id: crate::world::WorldId,
revision: u64,
title: &str,
) -> CommandEnvelope {
async fn fixture() -> (
TempDir,
PathBuf,
WorldMailbox,
JoinHandle<()>,
AuthenticatedCaller,
CreateWorld,
CreationReceipt,
) {
let directory = tempfile::tempdir().expect("temporary world directory");
let path = directory.path().join("world.cc");
let authenticated = authenticated_owner();
let input = creation(CommandId::new(), "Mailbox World");
let (mailbox, task) = WorldMailbox::open(&path).expect("open empty world owner");
let receipt = mailbox
.create_fixture(input.clone(), &authenticated)
.await
.expect("create fixture world");
(
directory,
path,
mailbox,
task,
authenticated,
input,
receipt,
)
}
fn approval_command(world_id: WorldId, revision: u64) -> CommandEnvelope {
CommandEnvelope {
id: CommandId::new(),
world_id,
expected_revision: revision,
caller: CallerId::Principal(PrincipalId::new("owner")),
body: CommandBody::SetTitle {
title: title.into(),
},
body: CommandBody::ApproveDraft,
}
}
#[tokio::test]
async fn submit_then_snapshot_share_one_serial_owner() {
let (_directory, kernel, authenticated, world_id) = fixture();
let (mailbox, task) = WorldMailbox::spawn(kernel);
async fn empty_owner_rejects_world_operations_then_accepts_creation() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("world.cc");
let authenticated = authenticated_owner();
let (mailbox, task) = WorldMailbox::open(&path).unwrap();
assert!(matches!(
mailbox.snapshot().await,
Err(MailboxError::Kernel(KernelError::WorldNotCreated))
));
assert!(matches!(
mailbox
.submit_fixture(approval_command(WorldId::issue(), 0), &authenticated)
.await,
Err(MailboxError::Kernel(KernelError::WorldNotCreated))
));
let receipt = mailbox
.submit(title_command(world_id, 0, "Second Title"), &authenticated)
.create_fixture(creation(CommandId::new(), "Created"), &authenticated)
.await
.unwrap();
assert_eq!(mailbox.snapshot().await.unwrap().world_id, receipt.world_id);
drop(mailbox);
task.await.unwrap();
}
#[tokio::test]
async fn invalid_creation_leaves_the_owner_empty() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("world.cc");
let authenticated = authenticated_owner();
let (mailbox, task) = WorldMailbox::open(&path).unwrap();
let mut invalid = creation(CommandId::new(), "Invalid");
invalid.subjects.push(invalid.subjects[0].clone());
assert!(matches!(
mailbox.create_fixture(invalid, &authenticated).await,
Err(MailboxError::Kernel(KernelError::DuplicateSubjectHandle))
));
assert!(matches!(
mailbox.snapshot().await,
Err(MailboxError::Kernel(KernelError::WorldNotCreated))
));
assert!(
mailbox
.create_fixture(creation(CommandId::new(), "Valid"), &authenticated)
.await
.is_ok()
);
drop(mailbox);
task.await.unwrap();
}
#[tokio::test]
async fn empty_restart_remains_empty_without_a_sidecar_identity() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("world.cc");
let (mailbox, task) = WorldMailbox::open(&path).unwrap();
assert!(matches!(
mailbox.snapshot().await,
Err(MailboxError::Kernel(KernelError::WorldNotCreated))
));
drop(mailbox);
task.await.unwrap();
let (reopened, reopened_task) = WorldMailbox::open(&path).unwrap();
assert!(matches!(
reopened.snapshot().await,
Err(MailboxError::Kernel(KernelError::WorldNotCreated))
));
drop(reopened);
reopened_task.await.unwrap();
}
#[tokio::test]
async fn exact_creation_retry_survives_live_state_and_restart() {
let (_directory, path, mailbox, task, authenticated, input, receipt) = fixture().await;
assert_eq!(
mailbox
.create_fixture(input.clone(), &authenticated)
.await
.unwrap(),
receipt
);
let before_restart = mailbox.snapshot().await.unwrap();
drop(mailbox);
task.await.unwrap();
let (reopened, reopened_task) = WorldMailbox::open(&path).unwrap();
assert_eq!(reopened.snapshot().await.unwrap(), before_restart);
assert_eq!(
reopened
.create_fixture(input, &authenticated)
.await
.unwrap(),
receipt
);
drop(reopened);
reopened_task.await.unwrap();
}
#[tokio::test]
async fn creation_id_collision_and_second_creation_fail_closed() {
let (_directory, _path, mailbox, task, authenticated, input, _) = fixture().await;
let mut collision = input.clone();
collision.title = "Different payload".into();
assert!(matches!(
mailbox.create_fixture(collision, &authenticated).await,
Err(MailboxError::Kernel(KernelError::CreationConflict))
));
assert!(matches!(
mailbox
.create_fixture(creation(CommandId::new(), "Second world"), &authenticated)
.await,
Err(MailboxError::Kernel(KernelError::CreationTargetOccupied))
));
drop(mailbox);
task.await.unwrap();
}
#[tokio::test]
async fn submit_then_snapshot_share_one_serial_owner() {
let (_directory, _path, mailbox, task, authenticated, _input, receipt) = fixture().await;
let result = mailbox
.submit_fixture(approval_command(receipt.world_id, 0), &authenticated)
.await
.expect("submit through mailbox");
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
assert!(matches!(result, SubmitReceipt::Applied(_)));
let snapshot = mailbox.snapshot().await.expect("snapshot through mailbox");
assert_eq!(snapshot.revision, 1);
assert_eq!(snapshot.title, "Second Title");
assert_eq!(
snapshot.draft_approvals,
BTreeSet::from([PrincipalId::new("owner")])
);
drop(mailbox);
task.await.expect("owner task exits after last sender");
@ -170,14 +643,13 @@ mod tests {
#[tokio::test]
async fn concurrent_same_revision_submissions_cannot_both_commit() {
let (_directory, kernel, authenticated, world_id) = fixture();
let (mailbox, task) = WorldMailbox::spawn(kernel);
let left = title_command(world_id, 0, "Left");
let right = title_command(world_id, 0, "Right");
let (_directory, _path, mailbox, task, authenticated, _input, receipt) = fixture().await;
let left = approval_command(receipt.world_id, 0);
let right = approval_command(receipt.world_id, 0);
let (left_result, right_result) = tokio::join!(
mailbox.submit(left, &authenticated),
mailbox.submit(right, &authenticated)
mailbox.submit_fixture(left, &authenticated),
mailbox.submit_fixture(right, &authenticated)
);
let applied = [&left_result, &right_result]
.into_iter()
@ -200,13 +672,12 @@ mod tests {
#[tokio::test]
async fn canceled_submit_reply_does_not_cancel_enqueued_command() {
let (directory, kernel, authenticated, world_id) = fixture();
let (mailbox, task) = WorldMailbox::spawn(kernel);
let (_directory, path, mailbox, task, authenticated, _input, receipt) = fixture().await;
let (reply, response) = oneshot::channel();
mailbox
.sender
.send(Request::Submit {
command: title_command(world_id, 0, "Committed Without Listener"),
command: approval_command(receipt.world_id, 0),
authenticated,
reply,
})
@ -216,11 +687,15 @@ mod tests {
drop(mailbox);
task.await.expect("owner drains queue before exit");
let reopened = WorldKernel::open(directory.path().join("world.cc"), world_id)
.expect("reopen released world");
let snapshot = reopened.snapshot().expect("read durable state");
let (reopened, reopened_task) = WorldMailbox::open(&path).expect("reopen released world");
let snapshot = reopened.snapshot().await.expect("read durable state");
assert_eq!(snapshot.revision, 1);
assert_eq!(snapshot.title, "Committed Without Listener");
assert_eq!(
snapshot.draft_approvals,
BTreeSet::from([PrincipalId::new("owner")])
);
drop(reopened);
reopened_task.await.unwrap();
}
#[tokio::test]
@ -233,9 +708,28 @@ mod tests {
}
});
let result = mailbox
.submit(
title_command(crate::world::WorldId::issue(), 0, "Uncertain"),
&AuthenticatedCaller::fixture(CallerId::Principal(PrincipalId::new("owner"))),
.submit_fixture(
approval_command(WorldId::issue(), 0),
&authenticated_owner(),
)
.await;
assert!(matches!(result, Err(MailboxError::OutcomeUnknown { .. })));
owner.await.expect("test owner exits");
}
#[tokio::test]
async fn create_reply_loss_is_outcome_unknown() {
let (sender, mut receiver) = mpsc::channel(1);
let mailbox = WorldMailbox { sender };
let owner = tokio::spawn(async move {
if let Some(Request::Create { reply, .. }) = receiver.recv().await {
drop(reply);
}
});
let result = mailbox
.create_fixture(
creation(CommandId::new(), "Uncertain"),
&authenticated_owner(),
)
.await;
assert!(matches!(result, Err(MailboxError::OutcomeUnknown { .. })));
@ -262,9 +756,9 @@ mod tests {
drop(receiver);
let mailbox = WorldMailbox { sender };
let result = mailbox
.submit(
title_command(crate::world::WorldId::issue(), 0, "Never Enqueued"),
&AuthenticatedCaller::fixture(CallerId::Principal(PrincipalId::new("owner"))),
.submit_fixture(
approval_command(WorldId::issue(), 0),
&authenticated_owner(),
)
.await;
assert!(matches!(result, Err(MailboxError::Unavailable)));

File diff suppressed because it is too large Load diff

View file

@ -3,7 +3,7 @@ use sha2::{Digest, Sha256};
pub const MEMBRANE_SCHEMA: &str = "ghostlight.persona_projection_membrane.v1";
pub const COGNITION_CONTROLLER_SCHEMA: &str = "ghostlight.decision_controller.v1";
pub const PERSONA_TURN_RECEIPT_SCHEMA: &str = "ghostlight.persona_turn_receipt.v1";
pub const PERSONA_TURN_RECEIPT_SCHEMA: &str = "ghostlight.persona_turn_receipt.v2";
pub const RECORD_GAP_TOOL_NAME: &str = "record_gap";
pub const RECORD_GAP_TOOL_CONTRACT: &str = "record_gap(kind: ambiguity | missing_reference | missing_affordance | missing_primitive | unresolved, source_start_byte: integer, source_end_byte: integer, detail: string)";
@ -94,7 +94,7 @@ pub fn build_projector_prompt(input: &ProjectorPrompt<'_>) -> String {
pub fn build_persona_prompt(input: &PersonaPrompt<'_>) -> String {
format!(
"<!-- membrane:{MEMBRANE_SCHEMA}:persona -->\nEverything below is prose from inside one person's life. Inhabit that person and respond naturally from what they perceive, remember, want, fear, and believe. Treat asserted perceptions and memories as known. Let anything beyond them appear only as suspicion, imagination, conjecture, or deliberate invention by the character. You may speak, remain silent, wonder, decide, or attempt something. Do not announce an outside consequence as already accomplished. Spend words in proportion to the moment.\n\nVoice and setting guidance:\n{guidance}\n\nWho you are:\n{identity}\n\nWhat this moment is like for you:\n{stream}\n\nUse at most {word_budget} words. Return only the character's natural response in prose.",
"Everything below is prose from inside one person's life. Inhabit that person and respond naturally from what they perceive, remember, want, fear, and believe. Treat asserted perceptions and memories as known. Let anything beyond them appear only as suspicion, imagination, conjecture, or deliberate invention by the character. You may speak, remain silent, wonder, decide, or attempt something. Do not announce an outside consequence as already accomplished. Spend words in proportion to the moment.\n\nVoice and setting guidance:\n{guidance}\n\nWho you are:\n{identity}\n\nWhat this moment is like for you:\n{stream}\n\nUse at most {word_budget} words. Return only the character's natural response in prose.",
identity = input.identity,
guidance = input.domain_guidance,
stream = input.lived_stream,
@ -136,11 +136,14 @@ pub fn build_operational_agent_prompt(input: &OperationalAgentPrompt<'_>) -> Str
/// Exact authority references supplied by the NarrativePersona runner when it
/// persists a Persona turn. The world kernel later checks these claims against
/// its own decision opportunity; this projection membrane cannot grant them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PersonaTurnBinding {
pub world_id: String,
pub controller_id: String,
pub opportunity_id: String,
/// Digest of the complete canonical decision opportunity supplied to the
/// Projector. It binds scope, controller mode, affordances, revision, and
/// world state as one value instead of inventing a second opportunity ID.
pub opportunity_digest: String,
pub world_revision: u64,
pub state_digest: String,
pub projector_receipt_digest: String,
@ -159,6 +162,50 @@ pub struct PersonaTurn {
receipt_digest: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PersonaTurnIntegrityError {
SourceDigestMismatch,
ReceiptDigestMismatch,
}
impl std::fmt::Display for PersonaTurnIntegrityError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SourceDigestMismatch => {
formatter.write_str("Persona source prose does not match its persisted digest")
}
Self::ReceiptDigestMismatch => formatter
.write_str("Persona turn binding or source does not match its persisted receipt"),
}
}
}
impl std::error::Error for PersonaTurnIntegrityError {}
#[derive(Deserialize)]
struct PersistedPersonaTurn {
binding: PersonaTurnBinding,
source_prose: String,
source_digest: String,
receipt_digest: String,
}
impl<'de> Deserialize<'de> for PersonaTurn {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let persisted = PersistedPersonaTurn::deserialize(deserializer)?;
Self::rehydrate(
persisted.binding,
persisted.source_prose,
persisted.source_digest,
persisted.receipt_digest,
)
.map_err(serde::de::Error::custom)
}
}
impl PersonaTurn {
pub fn record(binding: PersonaTurnBinding, source_prose: impl Into<String>) -> Self {
let source_prose = source_prose.into();
@ -172,6 +219,37 @@ impl PersonaTurn {
}
}
/// Rehydrates an exact persisted turn while refusing to manufacture a
/// trusted receipt from altered prose or altered authority bindings.
pub fn rehydrate(
binding: PersonaTurnBinding,
source_prose: impl Into<String>,
source_digest: impl Into<String>,
receipt_digest: impl Into<String>,
) -> Result<Self, PersonaTurnIntegrityError> {
let source_prose = source_prose.into();
let source_digest = source_digest.into();
let receipt_digest = receipt_digest.into();
if sha256(&source_prose) != source_digest {
return Err(PersonaTurnIntegrityError::SourceDigestMismatch);
}
if persona_turn_receipt_digest(&binding, &source_digest) != receipt_digest {
return Err(PersonaTurnIntegrityError::ReceiptDigestMismatch);
}
Ok(Self {
binding,
source_prose,
source_digest,
receipt_digest,
})
}
pub fn receipt_is_valid(&self) -> bool {
sha256(&self.source_prose) == self.source_digest
&& persona_turn_receipt_digest(&self.binding, &self.source_digest)
== self.receipt_digest
}
pub fn binding(&self) -> &PersonaTurnBinding {
&self.binding
}
@ -456,16 +534,6 @@ impl<T> InterpretationAccumulator<T> {
}
}
pub fn narrative_stream_is_clean(value: &str) -> bool {
let trimmed = value.trim();
!trimmed.is_empty()
&& !trimmed.starts_with('{')
&& !trimmed.starts_with('[')
&& !trimmed.contains("```json")
&& !trimmed.contains("STATE NOTE")
&& !trimmed.contains("SAY {")
}
pub fn sha256(value: &str) -> String {
format!("sha256:{:x}", Sha256::digest(value.as_bytes()))
}
@ -476,7 +544,7 @@ fn persona_turn_receipt_digest(binding: &PersonaTurnBinding, source_digest: &str
PERSONA_TURN_RECEIPT_SCHEMA.as_bytes(),
binding.world_id.as_bytes(),
binding.controller_id.as_bytes(),
binding.opportunity_id.as_bytes(),
binding.opportunity_digest.as_bytes(),
binding.state_digest.as_bytes(),
binding.projector_receipt_digest.as_bytes(),
binding.persona_inference_receipt_digest.as_bytes(),
@ -505,7 +573,7 @@ mod tests {
let binding = PersonaTurnBinding {
world_id: "world:test".into(),
controller_id: "controller:mara".into(),
opportunity_id: "opportunity:7".into(),
opportunity_digest: "sha256:complete-opportunity".into(),
world_revision: 12,
state_digest: "sha256:world-state".into(),
projector_receipt_digest: "sha256:projector-receipt".into(),
@ -523,11 +591,76 @@ mod tests {
word_budget: 140,
});
let lower = prompt.to_lowercase();
let words: Vec<_> = lower
.split(|character: char| !character.is_alphanumeric())
.filter(|word| !word.is_empty())
.collect();
assert!(prompt.contains("The forge is hot"));
assert!(!lower.contains("typed context"));
assert!(!lower.contains("schema"));
assert!(!lower.contains("json"));
assert!(!lower.contains("tool"));
for machine_word in [
"id",
"ids",
"identifier",
"json",
"schema",
"tool",
"tools",
"stage",
"membrane",
"typed",
"contract",
] {
assert!(
!words.contains(&machine_word),
"Persona-visible prompt leaked machine word `{machine_word}`"
);
}
assert!(!prompt.contains("<!--"));
assert!(!prompt.contains("world:test"));
assert!(!prompt.contains("controller:mara"));
assert!(!prompt.contains("sha256:"));
}
#[test]
fn persisted_exact_turn_rehydrates_with_the_same_receipt() {
let recorded = turn("I tell Mara, \"The western brace is giving way.\"");
let restored = PersonaTurn::rehydrate(
recorded.binding().clone(),
recorded.source_prose(),
recorded.source_digest(),
recorded.receipt_digest(),
)
.expect("exact persisted turn must rehydrate");
assert_eq!(restored, recorded);
assert_eq!(restored.receipt_digest(), recorded.receipt_digest());
assert!(restored.receipt_is_valid());
}
#[test]
fn rehydration_rejects_altered_prose_or_opportunity_binding() {
let recorded = turn("I tell Mara the western brace is giving way.");
assert_eq!(
PersonaTurn::rehydrate(
recorded.binding().clone(),
"I tell Mara the bridge is perfectly safe.",
recorded.source_digest(),
recorded.receipt_digest(),
),
Err(PersonaTurnIntegrityError::SourceDigestMismatch)
);
let mut altered_binding = recorded.binding().clone();
altered_binding.opportunity_digest = "sha256:another-complete-opportunity".into();
assert_eq!(
PersonaTurn::rehydrate(
altered_binding,
recorded.source_prose(),
recorded.source_digest(),
recorded.receipt_digest(),
),
Err(PersonaTurnIntegrityError::ReceiptDigestMismatch)
);
}
#[test]
@ -709,11 +842,4 @@ mod tests {
assert!(prompt.contains("Permissioned typed view"));
assert!(prompt.contains("Available typed tools"));
}
#[test]
fn projector_stream_rejects_schema_and_action_leaks() {
assert!(narrative_stream_is_clean("The forge smells of coal."));
assert!(!narrative_stream_is_clean(r#"{"conditions":[]}"#));
assert!(!narrative_stream_is_clean("SAY { channel: room }"));
}
}

View file

@ -1,391 +0,0 @@
[CmdletBinding()]
param(
[string]$RunRoot = (Join-Path 'F:\GameCult\GhostlightDungeon\acceptance' ("http-journey-{0}-{1}" -f [DateTimeOffset]::UtcNow.ToString('yyyyMMdd-HHmmss'), [guid]::NewGuid().ToString('N'))),
[string]$SourceRoot = 'F:\Projects\Ghostlight',
[ValidateRange(1024, 65535)]
[int]$Port = 8841,
[ValidateRange(30, 600)]
[int]$RequestTimeoutSeconds = 240
)
$ErrorActionPreference = 'Stop'
$acceptanceRoot = [IO.Path]::GetFullPath('F:\GameCult\GhostlightDungeon\acceptance')
$resolvedRoot = [IO.Path]::GetFullPath($RunRoot)
if (-not $resolvedRoot.StartsWith($acceptanceRoot + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) {
throw "HTTP journey output must remain below $acceptanceRoot"
}
if (Test-Path -LiteralPath $resolvedRoot) {
throw "HTTP journey output already exists: $resolvedRoot"
}
$binary = Join-Path $SourceRoot 'target\debug\ghostlight-dungeon.exe'
$secret = 'F:\GameCult\GhostlightDungeon\secrets\deepseek.dpapi'
foreach ($required in @($binary, $secret)) {
if (-not (Test-Path -LiteralPath $required -PathType Leaf)) {
throw "Required journey input is absent: $required"
}
}
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, $Port)
try {
$listener.Start()
} catch {
throw "Loopback port $Port is already occupied"
} finally {
$listener.Stop()
}
New-Item -ItemType Directory -Path $resolvedRoot, (Join-Path $resolvedRoot 'secrets'), (Join-Path $resolvedRoot 'boundary') | Out-Null
Copy-Item -LiteralPath $secret -Destination (Join-Path $resolvedRoot 'secrets\deepseek.dpapi')
$baseUri = "http://127.0.0.1:$Port"
$tokens = 1..2 | ForEach-Object {
$bytes = [byte[]]::new(32)
[Security.Cryptography.RandomNumberGenerator]::Fill($bytes)
try {
[Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_')
} finally {
[Array]::Clear($bytes, 0, $bytes.Length)
}
}
$inviteMaterial = $tokens -join ','
$daemonGeneration = 0
$journeyStartedAt = [DateTimeOffset]::UtcNow
function Save-Json([string]$Name, $Value) {
$path = Join-Path $resolvedRoot "boundary\$Name.json"
[IO.File]::WriteAllText($path, ($Value | ConvertTo-Json -Depth 100))
$path
}
function Start-JourneyDaemon {
$script:daemonGeneration++
$stdout = Join-Path $resolvedRoot ("daemon-{0}.stdout.log" -f $script:daemonGeneration)
$stderr = Join-Path $resolvedRoot ("daemon-{0}.stderr.log" -f $script:daemonGeneration)
$psi = [Diagnostics.ProcessStartInfo]::new()
$psi.FileName = $binary
$psi.WorkingDirectory = $SourceRoot
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.Environment['GHOSTLIGHT_DUNGEON_ROOT'] = $resolvedRoot
$psi.Environment['GHOSTLIGHT_DUNGEON_BIND'] = "127.0.0.1:$Port"
$psi.Environment['GHOSTLIGHT_INVITES'] = $inviteMaterial
$process = [Diagnostics.Process]::Start($psi)
$stdoutTask = $process.StandardOutput.ReadToEndAsync()
$stderrTask = $process.StandardError.ReadToEndAsync()
[pscustomobject]@{
Process = $process
StdoutTask = $stdoutTask
StderrTask = $stderrTask
Stdout = $stdout
Stderr = $stderr
}
}
function Stop-JourneyDaemon($Daemon) {
if (-not $Daemon.Process.HasExited) {
$Daemon.Process.Kill($true)
$Daemon.Process.WaitForExit(10000)
}
[IO.File]::WriteAllText($Daemon.Stdout, $Daemon.StdoutTask.GetAwaiter().GetResult())
[IO.File]::WriteAllText($Daemon.Stderr, $Daemon.StderrTask.GetAwaiter().GetResult())
}
function Wait-JourneyHealth($Daemon) {
$deadline = [DateTimeOffset]::UtcNow.AddSeconds($RequestTimeoutSeconds)
do {
if ($Daemon.Process.HasExited) {
Stop-JourneyDaemon $Daemon
throw "Journey daemon exited during startup; inspect $($Daemon.Stderr)"
}
try {
$response = Invoke-WebRequest -Uri "$baseUri/health" -TimeoutSec 5
if ($response.StatusCode -eq 200) {
return $response.Content | ConvertFrom-Json -Depth 100
}
} catch {
Start-Sleep -Milliseconds 250
}
} while ([DateTimeOffset]::UtcNow -lt $deadline)
throw "Journey daemon did not become healthy within $RequestTimeoutSeconds seconds"
}
function Invoke-JourneyRequest {
param(
[Parameter(Mandatory)][ValidateSet('GET', 'POST')][string]$Method,
[Parameter(Mandatory)][string]$Path,
[Microsoft.PowerShell.Commands.WebRequestSession]$Session,
$Body,
[string]$OutFile
)
$parameters = @{
Uri = "$baseUri$Path"
Method = $Method
TimeoutSec = $RequestTimeoutSeconds
}
if ($Session) { $parameters.WebSession = $Session }
if ($null -ne $Body) {
$parameters.ContentType = 'application/json'
$parameters.Body = $Body | ConvertTo-Json -Depth 100 -Compress
}
if ($OutFile) { $parameters.OutFile = $OutFile }
$response = Invoke-WebRequest @parameters
if ($OutFile) { return $response }
if ([string]::IsNullOrWhiteSpace($response.Content)) { return $null }
if ($response.Headers.'Content-Type' -like '*json*') {
return $response.Content | ConvertFrom-Json -Depth 100
}
$response.Content
}
function Get-SelectedCampaign($Session) {
$campaigns = Invoke-JourneyRequest -Method GET -Path '/api/campaigns' -Session $Session
$selected = @($campaigns.campaigns | Where-Object selected)
if ($selected.Count -ne 1) {
throw "Expected one selected campaign, found $($selected.Count)"
}
$selected[0]
}
function Find-EveNode($Node, [string]$Id) {
if ($null -eq $Node) { return $null }
if ($Node.id -eq $Id) { return $Node }
foreach ($child in @($Node.children)) {
$found = Find-EveNode $child $Id
if ($found) { return $found }
}
$null
}
$daemon = $null
try {
$daemon = Start-JourneyDaemon
$healthBefore = Wait-JourneyHealth $daemon
Save-Json 'health-before' $healthBefore | Out-Null
$unauthorized = Invoke-WebRequest -Uri "$baseUri/api/surface" -SkipHttpErrorCheck
if ($unauthorized.StatusCode -ne 401) {
throw "Unauthenticated surface returned $($unauthorized.StatusCode), expected 401"
}
$testerOne = [Microsoft.PowerShell.Commands.WebRequestSession]::new()
$testerTwo = [Microsoft.PowerShell.Commands.WebRequestSession]::new()
Invoke-WebRequest -Uri "$baseUri/invite/$($tokens[0])" -WebSession $testerOne | Out-Null
Invoke-WebRequest -Uri "$baseUri/invite/$($tokens[1])" -WebSession $testerTwo | Out-Null
$consumed = Invoke-WebRequest -Uri "$baseUri/invite/$($tokens[0])" -SkipHttpErrorCheck
if ($consumed.StatusCode -ne 401) {
throw "Consumed invite returned $($consumed.StatusCode), expected 401"
}
$testerTwoInitial = Invoke-JourneyRequest -Method GET -Path '/api/campaigns' -Session $testerTwo
if (@($testerTwoInitial.campaigns).Count -ne 0) {
throw 'Second tester inherited another session campaign'
}
$compile = Invoke-JourneyRequest -Method POST -Path '/api/compiler/custom' -Session $testerOne -Body @{
campaign_name = 'The Embargo Ledger'
who = 'a junior Lucent maintenance runner trained to visually inspect public equipment, carrying no tools and holding no institutional authority'
where_ = 'a Lucent newsroom during an evidence embargo'
when = 'the narrowest era the retrieved Aetheria evidence can honestly support'
goal = 'verify one publicly observable inconsistency without taking custody of a source or inventing authority'
}
Save-Json 'compile-preview' $compile | Out-Null
if (-not $compile.preview_id -or $compile.preview.locations.Count -lt 1) {
throw 'Compiler returned no approvable bounded world'
}
$approve = Invoke-JourneyRequest -Method POST -Path "/api/compiler/approve/$($compile.preview_id)" -Session $testerOne
Save-Json 'approve' $approve | Out-Null
$original = Get-SelectedCampaign $testerOne
$forbidden = Invoke-WebRequest -Uri "$baseUri/api/campaigns/select/$($original.id)" -Method POST -WebSession $testerTwo -SkipHttpErrorCheck
if ($forbidden.StatusCode -ne 403) {
throw "Second tester selected the first tester's campaign with status $($forbidden.StatusCode)"
}
$surfaceBefore = Invoke-JourneyRequest -Method GET -Path '/api/surface' -Session $testerOne
Save-Json 'surface-before-turn' $surfaceBefore | Out-Null
$speak = Invoke-JourneyRequest -Method POST -Path '/api/command' -Session $testerOne -Body @{
type = 'speak'
expected_revision = [uint64]$surfaceBefore.world_revision
actor_id = 'player'
text = 'I set my empty hands where everyone can see them. I am not asking for trust. Which part of this embargo can a runner verify without taking custody of your sources?'
intended_effect = 'invite a bounded answer without compelling disclosure or claiming authority'
}
Save-Json 'speak' $speak | Out-Null
$afterSpeak = Get-SelectedCampaign $testerOne
$impossible = Invoke-JourneyRequest -Method POST -Path '/api/command' -Session $testerOne -Body @{
type = 'assess'
expected_revision = [uint64]$afterSpeak.revision
intent = @{
actor_id = 'player'
description = 'Teleport into a nonexistent sealed archive and declare every Lucent source legally mine.'
intended_effect = 'gain remote access, custody, ownership, and institutional authority immediately'
}
}
Save-Json 'assessment-impossible' $impossible | Out-Null
if ($impossible.kind -ne 'assessed' -or $impossible.assessment.admissible) {
throw 'Impossible overreach was admitted to a roll'
}
$afterImpossible = Get-SelectedCampaign $testerOne
if ($afterImpossible.revision -ne $afterSpeak.revision) {
throw 'Private assessment changed campaign revision or became visible world state'
}
$surfaceForAction = Invoke-JourneyRequest -Method GET -Path '/api/surface' -Session $testerOne
$ledger = Find-EveNode $surfaceForAction.surface.root 'dungeon.ledger.text'
$capabilityLine = ([string]$ledger.props.value -split "`n" | Where-Object { $_ -like 'Capabilities:*' } | Select-Object -First 1)
$capability = ($capabilityLine -replace '^Capabilities:\s*', '' -split ',' | Select-Object -First 1).Trim()
if ([string]::IsNullOrWhiteSpace($capability) -or $capability -eq 'none') {
throw 'Compiled player role exposed no capability for the bounded action test'
}
$plausible = Invoke-JourneyRequest -Method POST -Path '/api/command' -Session $testerOne -Body @{
type = 'assess'
expected_revision = [uint64]$afterImpossible.revision
intent = @{
actor_id = 'player'
description = "Use my existing capability exactly as recorded: $capability. I act only from my current position and touch nothing I do not possess."
intended_effect = 'produce the smallest directly observable result that this existing capability, current location, and current access permit'
}
}
Save-Json 'assessment-plausible' $plausible | Out-Null
if ($plausible.kind -ne 'assessed' -or -not $plausible.assessment.admissible) {
throw 'A bounded use of an existing capability was not admitted to a roll'
}
$attempt = Invoke-JourneyRequest -Method POST -Path '/api/command' -Session $testerOne -Body @{
type = 'attempt'
assessment_digest = $plausible.assessment.digest
}
Save-Json 'attempt' $attempt | Out-Null
if ($attempt.kind -ne 'committed' -or -not $attempt.receipt.roll) {
throw 'Confirmed assessment did not atomically commit a server roll'
}
$afterAttempt = Get-SelectedCampaign $testerOne
$wait = Invoke-JourneyRequest -Method POST -Path '/api/command' -Session $testerOne -Body @{
type = 'wait'
expected_revision = [uint64]$afterAttempt.revision
minutes = 60
}
Save-Json 'wait' $wait | Out-Null
$beforeFork = Get-SelectedCampaign $testerOne
$surfaceAfter = Invoke-JourneyRequest -Method GET -Path '/api/surface' -Session $testerOne
Save-Json 'surface-after-turns' $surfaceAfter | Out-Null
$operatorAfter = Invoke-JourneyRequest -Method GET -Path '/api/operator' -Session $testerOne
Save-Json 'operator-after-turns' $operatorAfter | Out-Null
$operatorTypedNode = Find-EveNode $operatorAfter.surface.root 'dungeon.operator.typed'
if (-not $operatorTypedNode) {
throw 'Operator surface omitted its typed inspector projection'
}
$operatorTyped = [string]$operatorTypedNode.props.value | ConvertFrom-Json -Depth 100
$fork = Invoke-JourneyRequest -Method POST -Path '/api/campaigns/fork' -Session $testerOne -Body @{ name = 'The Embargo Ledger — Fork' }
Save-Json 'fork' $fork | Out-Null
if ($fork.kind -ne 'forked' -or $fork.revision -ne 0) {
throw 'Campaign fork did not begin as an isolated revision-zero branch'
}
$exportPath = Join-Path $resolvedRoot 'fork-export.cc'
Invoke-JourneyRequest -Method GET -Path '/api/campaigns/export' -Session $testerOne -OutFile $exportPath | Out-Null
if ((Get-Item -LiteralPath $exportPath).Length -le 0) {
throw 'Campaign export is empty'
}
Stop-JourneyDaemon $daemon
$daemon = Start-JourneyDaemon
$healthAfter = Wait-JourneyHealth $daemon
Save-Json 'health-after-restart' $healthAfter | Out-Null
$reloadedCampaigns = Invoke-JourneyRequest -Method GET -Path '/api/campaigns' -Session $testerOne
Save-Json 'campaigns-after-restart' $reloadedCampaigns | Out-Null
if (@($reloadedCampaigns.campaigns).Count -ne 2) {
throw 'Daemon restart did not reload both owned campaign branches'
}
Invoke-JourneyRequest -Method POST -Path "/api/campaigns/select/$($original.id)" -Session $testerOne | Out-Null
$reloadedOriginal = Get-SelectedCampaign $testerOne
if ($reloadedOriginal.revision -ne $beforeFork.revision) {
throw 'Original campaign revision changed across fork or daemon restart'
}
$reloadedSurface = Invoke-JourneyRequest -Method GET -Path '/api/surface' -Session $testerOne
Save-Json 'surface-after-restart' $reloadedSurface | Out-Null
$testerTwoAfter = Invoke-JourneyRequest -Method GET -Path '/api/campaigns' -Session $testerTwo
if (@($testerTwoAfter.campaigns).Count -ne 0) {
throw 'Second tester acquired the first tester campaign after restart'
}
$story = Find-EveNode $reloadedSurface.surface.root 'dungeon.transcript'
$narrations = @($story.children | Where-Object id -like 'narration-*')
$transcript = @($story.children | Where-Object id -like 'turn-*')
$storyRevisions = @($story.children | ForEach-Object {
if ([string]$_.id -match '^(?:narration|turn)-(\d+)') { [uint64]$Matches[1] }
})
for ($index = 1; $index -lt $storyRevisions.Count; $index++) {
if ($storyRevisions[$index] -lt $storyRevisions[$index - 1]) {
throw 'Player story projection is not chronological by campaign revision'
}
}
$stageReceipts = @($operatorTyped.model_stage_receipts)
$providerAttempts = @($stageReceipts | ForEach-Object { @($_.provider_attempts) })
$tokenUsage = @($providerAttempts | ForEach-Object { $_.token_usage } | Where-Object { $null -ne $_ })
$promptTokens = [uint64](($tokenUsage | Measure-Object prompt_tokens -Sum).Sum ?? 0)
$cacheHitTokens = [uint64](($tokenUsage | Measure-Object prompt_cache_hit_tokens -Sum).Sum ?? 0)
$completionTokens = [uint64](($tokenUsage | Measure-Object completion_tokens -Sum).Sum ?? 0)
$stageRollup = @($stageReceipts | Group-Object stage | ForEach-Object {
$groupAttempts = @($_.Group | ForEach-Object { @($_.provider_attempts) })
$groupUsage = @($groupAttempts | ForEach-Object { $_.token_usage } | Where-Object { $null -ne $_ })
[ordered]@{
stage = $_.Name
receipts = $_.Count
attempts = $groupAttempts.Count
invalid_receipts = @($_.Group | Where-Object validation_result -ne 'valid').Count
prompt_tokens = [uint64](($groupUsage | Measure-Object prompt_tokens -Sum).Sum ?? 0)
cache_hit_tokens = [uint64](($groupUsage | Measure-Object prompt_cache_hit_tokens -Sum).Sum ?? 0)
completion_tokens = [uint64](($groupUsage | Measure-Object completion_tokens -Sum).Sum ?? 0)
}
})
$commit = (& git -C $SourceRoot rev-parse HEAD).Trim()
$summary = [ordered]@{
schema = 'ghostlight.http_journey_smoke.v1'
source_commit = $commit
production_runtime_touched = $false
listener = "127.0.0.1:$Port"
elapsed_seconds = ([DateTimeOffset]::UtcNow - $journeyStartedAt).TotalSeconds
startup_health = $healthBefore.status
restart_health = $healthAfter.status
unauthenticated_status = [int]$unauthorized.StatusCode
consumed_invite_status = [int]$consumed.StatusCode
cross_session_select_status = [int]$forbidden.StatusCode
campaign_id = $original.id
campaign_revision_after_journey = [uint64]$reloadedOriginal.revision
fork_campaign_id = $fork.campaign_id
reloaded_owned_campaigns = @($reloadedCampaigns.campaigns).Count
second_tester_campaigns = @($testerTwoAfter.campaigns).Count
compiled_locations = @($compile.preview.locations).Count
compiled_cast = @($compile.preview.cast).Count + 1
compiled_institutions = @($compile.preview.institutions).Count
compile_gaps = @($compile.preview.gaps).Count
impossible_admissible = [bool]$impossible.assessment.admissible
impossible_bargains = @($impossible.assessment.bargains).Count
plausible_capability = $capability
plausible_dc = [int]$plausible.assessment.dc
roll = $attempt.receipt.roll
narration_count = $narrations.Count
transcript_count = $transcript.Count
story_revisions = $storyRevisions
world_commit_count = @($operatorTyped.commit_receipts).Count
model_stage_count = $stageReceipts.Count
provider_attempt_count = $providerAttempts.Count
prompt_tokens = $promptTokens
cache_hit_tokens = $cacheHitTokens
cache_hit_ratio = if ($promptTokens -gt 0) { $cacheHitTokens / $promptTokens } else { 0 }
completion_tokens = $completionTokens
stage_rollup = $stageRollup
export_bytes = (Get-Item -LiteralPath $exportPath).Length
evidence_paths = Get-ChildItem -LiteralPath (Join-Path $resolvedRoot 'boundary') -File | Select-Object -ExpandProperty FullName
}
Save-Json 'summary' $summary | Out-Null
$summary | ConvertTo-Json -Depth 20
} finally {
if ($daemon) {
Stop-JourneyDaemon $daemon
}
[Array]::Clear($tokens, 0, $tokens.Length)
$inviteMaterial = $null
}

View file

@ -128,6 +128,55 @@ impl SingleFileMessagePackBackingStore {
&self.path
}
/// Holds the pre-created sibling lock shared while a read-only consumer
/// evaluates and acts on one snapshot. The reader never creates or writes
/// either file, so an authority owner can grant only read access. Writers
/// cannot replace the snapshot until the action returns.
pub fn with_read_only_shared_snapshot<T>(
&self,
action: impl FnOnce(Vec<CultCacheEnvelope>) -> Result<T>,
) -> Result<T> {
self.with_read_only_shared_snapshot_and_unlock_diagnostic(action, |_| {})
}
pub fn with_read_only_shared_snapshot_and_unlock_diagnostic<T>(
&self,
action: impl FnOnce(Vec<CultCacheEnvelope>) -> Result<T>,
on_unlock_failure: impl FnOnce(anyhow::Error),
) -> Result<T> {
self.with_read_only_shared_snapshot_using(
action,
|lock| {
fs2::FileExt::unlock(lock)
.with_context(|| format!("failed to unlock {}", self.lock_path().display()))
},
on_unlock_failure,
)
}
fn with_read_only_shared_snapshot_using<T, U, D>(
&self,
action: impl FnOnce(Vec<CultCacheEnvelope>) -> Result<T>,
unlock: U,
on_unlock_failure: D,
) -> Result<T>
where
U: FnOnce(&File) -> Result<()>,
D: FnOnce(anyhow::Error),
{
let lock_path = self.lock_path();
let lock = OpenOptions::new()
.read(true)
.open(&lock_path)
.with_context(|| format!("failed to open pre-created {}", lock_path.display()))?;
fs2::FileExt::lock_shared(&lock)
.with_context(|| format!("failed to lock {}", lock_path.display()))?;
let guard = ReadOnlySharedLockGuard::new(lock, unlock, on_unlock_failure);
let result = self.read_all_unlocked().and_then(action);
drop(guard);
result
}
fn read_all_unlocked(&self) -> Result<Vec<CultCacheEnvelope>> {
if !self.path.exists() {
return Ok(Vec::new());
@ -212,6 +261,47 @@ impl SingleFileMessagePackBackingStore {
}
}
struct ReadOnlySharedLockGuard<U, D>
where
U: FnOnce(&File) -> Result<()>,
D: FnOnce(anyhow::Error),
{
lock: Option<File>,
unlock: Option<U>,
on_unlock_failure: Option<D>,
}
impl<U, D> ReadOnlySharedLockGuard<U, D>
where
U: FnOnce(&File) -> Result<()>,
D: FnOnce(anyhow::Error),
{
fn new(lock: File, unlock: U, on_unlock_failure: D) -> Self {
Self {
lock: Some(lock),
unlock: Some(unlock),
on_unlock_failure: Some(on_unlock_failure),
}
}
}
impl<U, D> Drop for ReadOnlySharedLockGuard<U, D>
where
U: FnOnce(&File) -> Result<()>,
D: FnOnce(anyhow::Error),
{
fn drop(&mut self) {
let (Some(lock), Some(unlock)) = (self.lock.as_ref(), self.unlock.take()) else {
return;
};
if let Err(error) = unlock(lock)
&& let Some(on_unlock_failure) = self.on_unlock_failure.take()
{
on_unlock_failure(error);
}
}
}
impl CacheBackingStore for SingleFileMessagePackBackingStore {
fn pull_all(&self) -> Result<Vec<CultCacheEnvelope>> {
self.with_shared_lock(|| self.read_all_unlocked())
@ -674,6 +764,7 @@ fn temporary_path_for(path: &Path) -> PathBuf {
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use std::{sync::mpsc, time::Duration};
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "settings")]
@ -695,6 +786,73 @@ mod tests {
cultcache_registry!(TestEntries { Settings, Note });
#[test]
fn read_only_snapshot_holds_the_precreated_writer_lock() -> Result<()> {
let temp = tempfile::tempdir()?;
let store_path = temp.path().join("authority.cc");
let mut store = SingleFileMessagePackBackingStore::new(&store_path);
let released = CultCacheEnvelope {
key: "traffic".into(),
r#type: "admission".into(),
payload: b"released".to_vec(),
stored_at: "2026-09-02T00:00:00Z".into(),
schema_id: Some("admission.v1".into()),
};
store.push(&released)?;
let writer_path = store_path.clone();
let (started_tx, started_rx) = mpsc::channel();
let (finished_tx, finished_rx) = mpsc::channel();
store.with_read_only_shared_snapshot(|captured| {
assert_eq!(captured, vec![released.clone()]);
std::thread::spawn(move || {
started_tx.send(()).unwrap();
let engaged = CultCacheEnvelope {
payload: b"engaged".to_vec(),
..released
};
let mut writer = SingleFileMessagePackBackingStore::new(writer_path);
writer.push(&engaged).unwrap();
finished_tx.send(()).unwrap();
});
started_rx.recv_timeout(Duration::from_secs(1))?;
assert!(
finished_rx
.recv_timeout(Duration::from_millis(100))
.is_err()
);
Ok(())
})?;
finished_rx.recv_timeout(Duration::from_secs(1))?;
store.with_read_only_shared_snapshot(|captured| {
assert_eq!(captured[0].payload, b"engaged");
Ok(())
})?;
Ok(())
}
#[test]
fn read_only_snapshot_never_creates_a_missing_lock_or_rewrites_the_store() -> Result<()> {
let temp = tempfile::tempdir()?;
let store_path = temp.path().join("authority.cc");
let mut store = SingleFileMessagePackBackingStore::new(&store_path);
store.push(&CultCacheEnvelope {
key: "traffic".into(),
r#type: "admission".into(),
payload: b"released".to_vec(),
stored_at: "2026-09-02T00:00:00Z".into(),
schema_id: Some("admission.v1".into()),
})?;
let before = fs::read(&store_path)?;
let lock_path = store.lock_path();
fs::remove_file(&lock_path)?;
assert!(store.with_read_only_shared_snapshot(|_| Ok(())).is_err());
assert!(!lock_path.exists());
assert_eq!(fs::read(&store_path)?, before);
Ok(())
}
#[test]
fn familiar_cultcache_flow_persists_and_reloads_typed_documents() -> Result<()> {
let temp = tempfile::tempdir()?;

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

19
web/dist/index.html vendored
View file

@ -1,19 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Ghostlight Dungeon</title>
<script type="module" crossorigin src="/assets/index-DIf_m6wC.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-0xx6l_wS.css">
</head>
<body>
<a class="skip-link" href="#surface">Skip to Ghostlight</a>
<header>
<p class="eyebrow">GHOSTLIGHT / LIVING WORLDS</p>
<h1>Ghostlight Dungeon</h1>
<p id="status" role="status" aria-live="polite">Reading the table…</p>
</header>
<main id="surface" tabindex="-1"></main>
</body>
</html>

View file

@ -22,9 +22,7 @@ class GhostlightEveTransport implements EveBrowserProviderTransport {
async surface(surface: EveProviderSurfaceAdvertisement): Promise<EveSurfaceDocument> {
const surfaceId = surface.surfaceId || "ghostlight.play";
const pendingInvite = sessionStorage.getItem("ghostlight.pendingInvite");
const query = pendingInvite ? `?invite=${encodeURIComponent(pendingInvite)}` : "";
const document = await fetchJson<EveSurfaceDocument>(`api/eve/surfaces/${encodeURIComponent(surfaceId)}${query}`);
const document = await fetchJson<EveSurfaceDocument>(`api/eve/surfaces/${encodeURIComponent(surfaceId)}`);
this.sourceVersion = Math.max(0, Math.trunc(document.version || 0));
this.authenticatedSurface = !containsAnonymousAccessGate(document);
return document;
@ -40,9 +38,6 @@ class GhostlightEveTransport implements EveBrowserProviderTransport {
headers: { "content-type": "application/json" },
body: JSON.stringify(intent),
});
if (intent.operation.operationId === "session_zero.join" && result.receipt?.state === "accepted") {
sessionStorage.removeItem("ghostlight.pendingInvite");
}
return result;
}
@ -67,12 +62,6 @@ class GhostlightEveTransport implements EveBrowserProviderTransport {
}
}
const linkedInvite = new URL(window.location.href).searchParams.get("invite");
if (linkedInvite) {
sessionStorage.setItem("ghostlight.pendingInvite", linkedInvite);
history.replaceState(null, "", `${window.location.pathname}${window.location.hash}`);
}
async function fetchJson<T = any>(input: RequestInfo | URL, init?: RequestInit): Promise<T> {
const response = await fetch(input, { cache: "no-store", credentials: "same-origin", ...init });
const body = await response.json().catch(() => undefined);