From 6bb686981050e048c070376e7f7ac86d177e8f18 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Sep 2026 07:21:11 +0200 Subject: [PATCH] Rebuild Ghostlight around explicit world authority --- .gitignore | 1 + Cargo.lock | 2 +- Cargo.toml | 5 +- crates/ghostlight-dungeon/Cargo.toml | 10 +- .../ghostlight-dungeon/src/agency_corpus.rs | 635 - crates/ghostlight-dungeon/src/agent.rs | 865 -- crates/ghostlight-dungeon/src/app_session.rs | 1083 +- crates/ghostlight-dungeon/src/assessor.rs | 4430 ------ .../src/bin/ghostlight-agency-corpus.rs | 34 - .../src/bin/ghostlight-campaign-inspect.rs | 262 - .../src/bin/ghostlight-mesh-inspect.rs | 25 - .../src/bin/ghostlight-native-client.rs | 483 - .../ghostlight-provider-health-identity.rs | 35 - .../bin/ghostlight-session-zero-inspect.rs | 88 - .../src/bin/ghostlight-world-explore.rs | 1033 -- crates/ghostlight-dungeon/src/clock.rs | 739 - crates/ghostlight-dungeon/src/compiler.rs | 12395 ---------------- crates/ghostlight-dungeon/src/consumer.rs | 441 - crates/ghostlight-dungeon/src/d20.rs | 76 - crates/ghostlight-dungeon/src/domain.rs | 1602 -- crates/ghostlight-dungeon/src/elaboration.rs | 6378 -------- crates/ghostlight-dungeon/src/eve.rs | 572 + .../ghostlight-dungeon/src/follow_through.rs | 1422 -- crates/ghostlight-dungeon/src/gestalt.rs | 937 -- crates/ghostlight-dungeon/src/heimdall.rs | 228 +- crates/ghostlight-dungeon/src/idunn_health.rs | 844 +- crates/ghostlight-dungeon/src/initiative.rs | 35 - crates/ghostlight-dungeon/src/kernel.rs | 10950 -------------- .../src/legacy_transition.rs | 4879 ------ crates/ghostlight-dungeon/src/lib.rs | 39 - crates/ghostlight-dungeon/src/main.rs | 7784 +--------- crates/ghostlight-dungeon/src/mesh.rs | 766 +- crates/ghostlight-dungeon/src/model.rs | 1788 --- .../ghostlight-dungeon/src/model_connector.rs | 1084 -- .../ghostlight-dungeon/src/model_runtime.rs | 124 - .../ghostlight-dungeon/src/native_cultmesh.rs | 608 - crates/ghostlight-dungeon/src/newspaper.rs | 6120 -------- crates/ghostlight-dungeon/src/outcome.rs | 4387 ------ crates/ghostlight-dungeon/src/persistence.rs | 1410 -- crates/ghostlight-dungeon/src/persona.rs | 6540 -------- crates/ghostlight-dungeon/src/registry.rs | 1821 --- crates/ghostlight-dungeon/src/resolution.rs | 5505 ------- crates/ghostlight-dungeon/src/runtime.rs | 1976 +++ crates/ghostlight-dungeon/src/scheduler.rs | 3336 ----- crates/ghostlight-dungeon/src/session_zero.rs | 7607 ---------- crates/ghostlight-dungeon/src/surface.rs | 848 -- crates/ghostlight-dungeon/src/transition.rs | 5406 ------- crates/ghostlight-dungeon/src/turn.rs | 919 -- crates/ghostlight-dungeon/src/vault.rs | 750 - .../ghostlight-dungeon/src/windows_secret.rs | 49 - .../src/world/controllers.rs | 4672 ++++++ .../ghostlight-dungeon/src/world/journal.rs | 260 +- .../ghostlight-dungeon/src/world/mailbox.rs | 666 +- crates/ghostlight-dungeon/src/world/mod.rs | 863 +- .../ghostlight-persona-projection/src/lib.rs | 180 +- tools/run_ghostlight_http_journey.ps1 | 391 - vendor/cultcache-rs/src/lib.rs | 158 + web/dist/assets/index-0xx6l_wS.css | 1 - web/dist/assets/index-DIf_m6wC.js | 160 - web/dist/index.html | 19 - web/src/main.ts | 13 +- 61 files changed, 10712 insertions(+), 106027 deletions(-) delete mode 100644 crates/ghostlight-dungeon/src/agency_corpus.rs delete mode 100644 crates/ghostlight-dungeon/src/agent.rs delete mode 100644 crates/ghostlight-dungeon/src/assessor.rs delete mode 100644 crates/ghostlight-dungeon/src/bin/ghostlight-agency-corpus.rs delete mode 100644 crates/ghostlight-dungeon/src/bin/ghostlight-campaign-inspect.rs delete mode 100644 crates/ghostlight-dungeon/src/bin/ghostlight-mesh-inspect.rs delete mode 100644 crates/ghostlight-dungeon/src/bin/ghostlight-native-client.rs delete mode 100644 crates/ghostlight-dungeon/src/bin/ghostlight-provider-health-identity.rs delete mode 100644 crates/ghostlight-dungeon/src/bin/ghostlight-session-zero-inspect.rs delete mode 100644 crates/ghostlight-dungeon/src/bin/ghostlight-world-explore.rs delete mode 100644 crates/ghostlight-dungeon/src/clock.rs delete mode 100644 crates/ghostlight-dungeon/src/compiler.rs delete mode 100644 crates/ghostlight-dungeon/src/consumer.rs delete mode 100644 crates/ghostlight-dungeon/src/d20.rs delete mode 100644 crates/ghostlight-dungeon/src/domain.rs delete mode 100644 crates/ghostlight-dungeon/src/elaboration.rs create mode 100644 crates/ghostlight-dungeon/src/eve.rs delete mode 100644 crates/ghostlight-dungeon/src/follow_through.rs delete mode 100644 crates/ghostlight-dungeon/src/gestalt.rs delete mode 100644 crates/ghostlight-dungeon/src/initiative.rs delete mode 100644 crates/ghostlight-dungeon/src/kernel.rs delete mode 100644 crates/ghostlight-dungeon/src/legacy_transition.rs delete mode 100644 crates/ghostlight-dungeon/src/lib.rs delete mode 100644 crates/ghostlight-dungeon/src/model.rs delete mode 100644 crates/ghostlight-dungeon/src/model_connector.rs delete mode 100644 crates/ghostlight-dungeon/src/model_runtime.rs delete mode 100644 crates/ghostlight-dungeon/src/native_cultmesh.rs delete mode 100644 crates/ghostlight-dungeon/src/newspaper.rs delete mode 100644 crates/ghostlight-dungeon/src/outcome.rs delete mode 100644 crates/ghostlight-dungeon/src/persistence.rs delete mode 100644 crates/ghostlight-dungeon/src/persona.rs delete mode 100644 crates/ghostlight-dungeon/src/registry.rs delete mode 100644 crates/ghostlight-dungeon/src/resolution.rs create mode 100644 crates/ghostlight-dungeon/src/runtime.rs delete mode 100644 crates/ghostlight-dungeon/src/scheduler.rs delete mode 100644 crates/ghostlight-dungeon/src/session_zero.rs delete mode 100644 crates/ghostlight-dungeon/src/surface.rs delete mode 100644 crates/ghostlight-dungeon/src/transition.rs delete mode 100644 crates/ghostlight-dungeon/src/turn.rs delete mode 100644 crates/ghostlight-dungeon/src/vault.rs delete mode 100644 crates/ghostlight-dungeon/src/windows_secret.rs create mode 100644 crates/ghostlight-dungeon/src/world/controllers.rs delete mode 100644 tools/run_ghostlight_http_journey.ps1 delete mode 100644 web/dist/assets/index-0xx6l_wS.css delete mode 100644 web/dist/assets/index-DIf_m6wC.js delete mode 100644 web/dist/index.html diff --git a/.gitignore b/.gitignore index 8d7aa6c..5a27af3 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ __pycache__/ *.pyc .venv/ node_modules/ +web/dist/ state/scratch-compaction-*.md experiments/images/ target/ diff --git a/Cargo.lock b/Cargo.lock index c94a93b..b19d785 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index 00670ad..64d35a5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/crates/ghostlight-dungeon/Cargo.toml b/crates/ghostlight-dungeon/Cargo.toml index 2670ccb..510c53f 100644 --- a/crates/ghostlight-dungeon/Cargo.toml +++ b/crates/ghostlight-dungeon/Cargo.toml @@ -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"] } diff --git a/crates/ghostlight-dungeon/src/agency_corpus.rs b/crates/ghostlight-dungeon/src/agency_corpus.rs deleted file mode 100644 index b76d6e6..0000000 --- a/crates/ghostlight-dungeon/src/agency_corpus.rs +++ /dev/null @@ -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 { - 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::>(); - 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::("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 - ); - } - } - } -} diff --git a/crates/ghostlight-dungeon/src/agent.rs b/crates/ghostlight-dungeon/src/agent.rs deleted file mode 100644 index e68dc12..0000000 --- a/crates/ghostlight-dungeon/src/agent.rs +++ /dev/null @@ -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, - pub temperature: Option, - pub max_output_tokens: Option, - pub max_steps: usize, -} - -#[derive(Debug)] -pub struct ModelAgentRun { - pub output: Output, - pub receipts: Vec, -} - -#[derive(Debug)] -pub enum ModelAgentProgress { - Accepted(ModelAgentRun), - Exhausted(ModelAgentExhausted), -} - -#[derive(Debug)] -pub struct ModelAgentExhausted { - pub stage: String, - pub max_steps: usize, - pub final_observation: Option, - pub receipts: Vec, -} - -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, -} - -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, - /// 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, -} - -pub enum ModelAgentToolOutcome { - /// 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, - }, - Accepted { - output: Output, - receipts: Vec, - }, - Rejected { - finding: Finding, - receipts: Vec, - }, - Failed { - message: String, - receipts: Vec, - }, -} - -#[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; - - /// 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 { - 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 { - None - } - - async fn invoke( - &mut self, - action: Self::Action, - context: &ModelAgentToolContext, - ) -> ModelAgentToolOutcome; -} - -pub async fn run_model_agent( - port: &dyn ModelPort, - spec: &ModelAgentSpec, - tool: &mut Tool, -) -> std::result::Result, 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( - port: &dyn ModelPort, - spec: &ModelAgentSpec, - tool: &mut Tool, -) -> std::result::Result, 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::(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::>(), - ), - 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 { - base.iter() - .cloned() - .chain( - receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()), - ) - .collect::>() - .into_iter() - .collect() -} - -fn append_agent_observation( - input: &mut Vec, - 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, - assistant_output: &str, - step: usize, - max_steps: usize, - status: &str, - observation: &serde_json::Value, - context_snapshot: Option, -) { - 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>, - requests: Mutex>, - } - - #[async_trait] - impl ModelPort for ScriptedModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.requests.lock().unwrap().push(request.clone()); - Ok(self.outputs.lock().unwrap().remove(0)) - } - - async fn run_observed(&self, request: &ModelStageRequest) -> Result { - 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::to_value(schema_for!(CandidateAction)).map_err(|error| error.to_string()) - } - - async fn invoke( - &mut self, - action: Self::Action, - _context: &ModelAgentToolContext, - ) -> ModelAgentToolOutcome { - 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::to_value(schema_for!(CandidateAction)).map_err(|error| error.to_string()) - } - - fn initial_context_snapshot(&self) -> Option { - Some(serde_json::json!({"assignment":"immutable facts", "step":self.step})) - } - - fn context_snapshot(&self) -> Option { - Some(serde_json::json!({"assignment":"immutable facts", "step":self.step})) - } - - async fn invoke( - &mut self, - action: Self::Action, - _context: &ModelAgentToolContext, - ) -> ModelAgentToolOutcome { - 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 { - 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 { - 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"); - } -} diff --git a/crates/ghostlight-dungeon/src/app_session.rs b/crates/ghostlight-dungeon/src/app_session.rs index 9863fad..769c2a4 100644 --- a/crates/ghostlight-dungeon/src/app_session.rs +++ b/crates/ghostlight-dungeon/src/app_session.rs @@ -1,243 +1,266 @@ +//! Local custody for authenticated Heimdall sessions. +//! +//! This store owns only browser-session continuity. It does not own world +//! selection, commands, idempotency, exports, or fictional state. + +use crate::heimdall::{VerifiedSessionAdmission, VerifiedSessionRefresh}; use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead}; use anyhow::{Context, bail}; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use chrono::{DateTime, Utc}; -use ghostlight_dungeon::persistence::CampaignStore; +use cultcache_legacy::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; use rand::RngCore; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::{collections::BTreeMap, path::Path}; +const STORE_TYPE: &str = "ghostlight.app_session_store.v2"; +const STORE_SCHEMA: &str = "ghostlight.app_session_store.v2"; +const STORE_KEY: &str = "primary"; +const MAX_SESSION_RECORDS: usize = 1_024; + #[derive(Clone, Serialize, Deserialize)] -pub struct AppSessionState { - pub schema: String, - pub sessions: BTreeMap, - pub account_preferences: BTreeMap, - #[serde(default)] - pub command_receipts: BTreeMap, - #[serde(default)] - pub campaign_export_grants: BTreeMap, +#[serde(deny_unknown_fields)] +struct AppSessionState { + schema: String, + sessions: BTreeMap, } #[derive(Clone, Serialize, Deserialize)] -pub struct CampaignExportGrant { - pub schema: String, - pub token_hash: String, - pub account_subject_hash: String, - pub campaign_id: uuid::Uuid, - pub export_path: std::path::PathBuf, - pub filename: String, - pub created_at: DateTime, - pub expires_at: DateTime, - pub consumed_at: Option>, +#[serde(deny_unknown_fields)] +struct AppSession { + schema: String, + cookie_hash: String, + account_subject_hash: String, + heimdall_session_id: String, + access_revision: u64, + verified_capabilities: Vec, + access_expires_at: DateTime, + refresh_expires_at: DateTime, + encrypted_refresh_claim: String, + created_at: DateTime, + last_refresh_at: DateTime, + revoked_at: Option>, } -pub struct CampaignExportResource { - pub campaign_id: uuid::Uuid, - pub export_path: std::path::PathBuf, - pub filename: String, +pub(crate) struct RefreshCandidate { + pub(crate) cookie_hash: String, + pub(crate) account_subject_hash: String, + pub(crate) heimdall_session_id: String, + pub(crate) access_revision: u64, + pub(crate) refresh_claim: String, } -#[derive(Clone, Serialize, Deserialize)] -pub struct EveCommandCacheEntry { - pub schema: String, - pub account_subject_hash: String, - pub idempotency_key: String, - pub operation_id: String, - #[serde(default)] - pub command_result_messagepack: Option>, - pub created_at: DateTime, +/// Opaque proof that the session owner verified a live Heimdall principal. +/// +/// The account hash is intentionally readable by world ingress, but this type +/// can only be constructed while `AppSessionOwner` holds valid custody. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct VerifiedPrincipalEvidence { + account_subject_hash: String, } -pub enum CommandReservation { - Reserved, - Pending, - Cached(serde_json::Value), +impl VerifiedPrincipalEvidence { + pub(crate) fn account_subject_hash(&self) -> &str { + &self.account_subject_hash + } } -pub struct RefreshCandidate { - pub cookie_hash: String, - pub account_subject_hash: String, - pub heimdall_session_id: String, - pub access_revision: u64, - pub refresh_claim: String, -} - -pub struct RefreshedSession<'a> { - pub expected_access_revision: u64, - pub access_revision: u64, - pub capabilities: Vec, - pub access_expires_at: DateTime, - pub refresh_expires_at: DateTime, - pub refresh_claim: &'a str, -} - -#[derive(Clone, Serialize, Deserialize)] -pub struct AppSession { - pub schema: String, - pub cookie_hash: String, - pub account_subject_hash: String, - pub heimdall_session_id: String, - pub access_revision: u64, - pub verified_capabilities: Vec, - pub access_expires_at: DateTime, - pub refresh_expires_at: DateTime, - pub encrypted_refresh_claim: String, - pub created_at: DateTime, - pub last_refresh_at: DateTime, - pub revoked_at: Option>, -} - -#[derive(Clone, Serialize, Deserialize)] -pub struct AccountPreferences { - pub schema: String, - pub account_subject_hash: String, - pub selected_campaign_id: Option, - pub updated_at: DateTime, -} - -pub struct NewSession<'a> { - pub account_id: &'a str, - pub heimdall_session_id: &'a str, - pub access_revision: u64, - pub capabilities: Vec, - pub access_expires_at: DateTime, - pub refresh_expires_at: DateTime, - pub refresh_claim: &'a str, -} - -pub struct AppSessionOwner { - store: CampaignStore, - row: cultcache_legacy::CultCacheEnvelope, +pub(crate) struct AppSessionOwner { + store: OwnedRedbMessagePackBackingStore, + row: CultCacheEnvelope, state: AppSessionState, wrapping_key: [u8; 32], + healthy: bool, } impl AppSessionOwner { - #[cfg(test)] - pub fn persisted_bytes_contain(&self, needle: &str) -> anyhow::Result { - let directory = tempfile::tempdir()?; - let snapshot = directory.path().join("app-session-inspection.cc"); - self.store.snapshot_to(&snapshot)?; - let bytes = std::fs::read(snapshot)?; - Ok(bytes - .windows(needle.len()) - .any(|window| window == needle.as_bytes())) - } - - pub fn open( + pub(crate) fn open( store_path: impl AsRef, wrapping_key_path: impl AsRef, ) -> anyhow::Result { - let store = CampaignStore::open(store_path)?; - let (row, state) = match store.load::("app_session_store.v1", "primary")? { - Some(value) => value, - None => { + let wrapping_key = read_wrapping_key(wrapping_key_path.as_ref())?; + let store = OwnedRedbMessagePackBackingStore::new(store_path.as_ref())?; + store + .validate_path_identity() + .context("app-session store path identity is invalid")?; + let rows = store.pull_all()?; + let (row, state) = match rows.as_slice() { + [] => { let state = AppSessionState { - schema: "ghostlight.app_session_store.v1".into(), + schema: STORE_SCHEMA.into(), sessions: BTreeMap::new(), - account_preferences: BTreeMap::new(), - command_receipts: BTreeMap::new(), - campaign_export_grants: BTreeMap::new(), }; - let row = store.insert( - "app_session_store.v1", - "ghostlight.app_session_store.v1", - "primary", - &state, - )?; + let row = envelope(&state)?; + if !store.compare_and_swap_batch(&[], std::slice::from_ref(&row))? { + bail!("app-session store changed during initialization"); + } (row, state) } + [row] + if row.r#type == STORE_TYPE + && row.key == STORE_KEY + && row.schema_id.as_deref() == Some(STORE_SCHEMA) => + { + let state: AppSessionState = + rmp_serde::from_slice(&row.payload).context("app-session state is corrupt")?; + if rmp_serde::to_vec_named(&state)? != row.payload { + bail!("app-session state is not canonical"); + } + if state.schema != STORE_SCHEMA { + bail!("app-session state schema is invalid"); + } + validate_state(&state, &wrapping_key)?; + (row.clone(), state) + } + _ => bail!( + "app-session v2 store contains foreign or legacy records; start with a fresh store" + ), }; Ok(Self { store, row, state, - wrapping_key: read_wrapping_key(wrapping_key_path.as_ref())?, + wrapping_key, + healthy: true, }) } - pub fn create_session(&mut self, input: NewSession<'_>) -> anyhow::Result { - if !input.capabilities.iter().any(|value| value == "app_access") { + pub(crate) fn create_session( + &mut self, + input: VerifiedSessionAdmission, + ) -> anyhow::Result { + if !input + .capabilities() + .iter() + .any(|value| value == "app_access") + { bail!("Heimdall session lacks app_access"); } + if input.account_id().trim().is_empty() + || input.heimdall_session_id().trim().is_empty() + || input.refresh_claim().is_empty() + || input.refresh_expires_at() <= input.access_expires_at() + { + bail!("Heimdall session material is invalid"); + } let mut cookie = [0_u8; 32]; rand::rng().fill_bytes(&mut cookie); let raw_cookie = URL_SAFE_NO_PAD.encode(cookie); let cookie_hash = secret_hash(&raw_cookie); - let account_subject_hash = secret_hash(&format!("heimdall-account:{}", input.account_id)); + let account_subject_hash = secret_hash(&format!("heimdall-account:{}", input.account_id())); let now = Utc::now(); let session = AppSession { - schema: "ghostlight.app_session.v1".into(), + schema: "ghostlight.app_session.v2".into(), cookie_hash: cookie_hash.clone(), account_subject_hash: account_subject_hash.clone(), - heimdall_session_id: input.heimdall_session_id.into(), - access_revision: input.access_revision, - verified_capabilities: input.capabilities, - access_expires_at: input.access_expires_at, - refresh_expires_at: input.refresh_expires_at, + heimdall_session_id: input.heimdall_session_id().to_owned(), + access_revision: input.access_revision(), + verified_capabilities: input.capabilities().to_vec(), + access_expires_at: input.access_expires_at(), + refresh_expires_at: input.refresh_expires_at(), encrypted_refresh_claim: wrap_refresh( &self.wrapping_key, &account_subject_hash, - input.heimdall_session_id, - input.refresh_claim, + input.heimdall_session_id(), + input.refresh_claim(), )?, created_at: now, last_refresh_at: now, revoked_at: None, }; let mut next = self.state.clone(); + for previous in next.sessions.values_mut().filter(|previous| { + previous.revoked_at.is_none() + && previous.heimdall_session_id == input.heimdall_session_id() + }) { + previous.revoked_at = Some(now); + } next.sessions.insert(cookie_hash, session); - next.account_preferences - .entry(account_subject_hash.clone()) - .or_insert(AccountPreferences { - schema: "ghostlight.account_preferences.v1".into(), - account_subject_hash, - selected_campaign_id: None, - updated_at: now, - }); self.commit(next)?; Ok(raw_cookie) } - pub fn account_for_cookie(&self, raw_cookie: &str, now: DateTime) -> Option { - let session = self.state.sessions.get(&secret_hash(raw_cookie))?; - (session.revoked_at.is_none() + pub(crate) fn is_healthy(&self) -> bool { + self.healthy + } + + pub(crate) fn validate_custody(&mut self) -> anyhow::Result<()> { + self.ensure_owned() + } + + pub(crate) fn account_for_cookie( + &mut self, + raw_cookie: &str, + now: DateTime, + ) -> anyhow::Result> { + self.ensure_owned()?; + let Some(session) = self.state.sessions.get(&secret_hash(raw_cookie)) else { + return Ok(None); + }; + Ok((session.revoked_at.is_none() && session.access_expires_at > now + && session.refresh_expires_at > now && session .verified_capabilities .iter() .any(|value| value == "app_access")) - .then(|| session.account_subject_hash.clone()) + .then(|| VerifiedPrincipalEvidence { + account_subject_hash: session.account_subject_hash.clone(), + })) } - pub fn revoke_cookie(&mut self, raw_cookie: &str) -> anyhow::Result { - let hash = secret_hash(raw_cookie); + pub(crate) fn revoke_cookie(&mut self, raw_cookie: &str) -> anyhow::Result { + self.ensure_owned()?; + let cookie_hash = secret_hash(raw_cookie); let mut next = self.state.clone(); - let Some(session) = next.sessions.get_mut(&hash) else { + let Some(session) = next.sessions.get_mut(&cookie_hash) else { return Ok(false); }; + if session.revoked_at.is_some() { + return Ok(false); + } session.revoked_at = Some(Utc::now()); self.commit(next)?; Ok(true) } - pub fn revoke_cookie_hash(&mut self, cookie_hash: &str) -> anyhow::Result { + pub(crate) fn revoke_cookie_hash(&mut self, cookie_hash: &str) -> anyhow::Result { + self.ensure_owned()?; let mut next = self.state.clone(); let Some(session) = next.sessions.get_mut(cookie_hash) else { return Ok(false); }; + if session.revoked_at.is_some() { + return Ok(false); + } session.revoked_at = Some(Utc::now()); self.commit(next)?; Ok(true) } - pub fn sessions_due_for_refresh( - &self, + pub(crate) fn session_for_logout( + &mut self, + raw_cookie: &str, + ) -> anyhow::Result> { + self.ensure_owned()?; + let Some(session) = self.state.sessions.get(&secret_hash(raw_cookie)) else { + return Ok(None); + }; + match self.refresh_candidate(session) { + Ok(candidate) => Ok(Some(candidate)), + Err(error) => self.poison(error), + } + } + + pub(crate) fn sessions_due_for_refresh( + &mut self, now: DateTime, refresh_before: chrono::Duration, ) -> anyhow::Result> { - self.state + self.ensure_owned()?; + let candidates = self + .state .sessions .values() .filter(|session| { @@ -245,31 +268,62 @@ impl AppSessionOwner { && session.refresh_expires_at > now && session.access_expires_at <= now + refresh_before }) - .map(|session| { - Ok(RefreshCandidate { - cookie_hash: session.cookie_hash.clone(), - account_subject_hash: session.account_subject_hash.clone(), - heimdall_session_id: session.heimdall_session_id.clone(), - access_revision: session.access_revision, - refresh_claim: unwrap_refresh( - &self.wrapping_key, - &session.account_subject_hash, - &session.heimdall_session_id, - &session.encrypted_refresh_claim, - )?, - }) - }) - .collect() + .map(|session| self.refresh_candidate(session)) + .collect::>>(); + match candidates { + Ok(candidates) => Ok(candidates), + Err(error) => self.poison(error), + } } - pub fn session_for_logout(&self, raw_cookie: &str) -> anyhow::Result> { - let Some(session) = self.state.sessions.get(&secret_hash(raw_cookie)) else { - return Ok(None); - }; - if session.revoked_at.is_some() { - return Ok(None); + pub(crate) fn apply_refresh( + &mut self, + cookie_hash: &str, + expected_access_revision: u64, + input: VerifiedSessionRefresh, + ) -> anyhow::Result<()> { + if !input + .capabilities() + .iter() + .any(|value| value == "app_access") + { + bail!("refreshed Heimdall session lacks app_access"); } - Ok(Some(RefreshCandidate { + if input.refresh_claim().is_empty() + || input.refresh_expires_at() <= input.access_expires_at() + { + bail!("refreshed Heimdall session material is invalid"); + } + let mut next = self.state.clone(); + let session = next + .sessions + .get_mut(cookie_hash) + .context("local session vanished during refresh")?; + if session.revoked_at.is_some() + || session.access_revision != expected_access_revision + || input.access_revision() <= expected_access_revision + || session.heimdall_session_id != input.heimdall_session_id() + || session.account_subject_hash + != secret_hash(&format!("heimdall-account:{}", input.account_id())) + { + bail!("local session changed during refresh"); + } + session.access_revision = input.access_revision(); + session.verified_capabilities = input.capabilities().to_vec(); + session.access_expires_at = input.access_expires_at(); + session.refresh_expires_at = input.refresh_expires_at(); + session.encrypted_refresh_claim = wrap_refresh( + &self.wrapping_key, + &session.account_subject_hash, + &session.heimdall_session_id, + input.refresh_claim(), + )?; + session.last_refresh_at = Utc::now(); + self.commit(next) + } + + fn refresh_candidate(&self, session: &AppSession) -> anyhow::Result { + Ok(RefreshCandidate { cookie_hash: session.cookie_hash.clone(), account_subject_hash: session.account_subject_hash.clone(), heimdall_session_id: session.heimdall_session_id.clone(), @@ -280,256 +334,141 @@ impl AppSessionOwner { &session.heimdall_session_id, &session.encrypted_refresh_claim, )?, - })) + }) } - pub fn apply_refresh( - &mut self, - cookie_hash: &str, - input: RefreshedSession<'_>, - ) -> anyhow::Result<()> { - if !input.capabilities.iter().any(|value| value == "app_access") { - bail!("refreshed Heimdall session lacks app_access"); - } - let mut next = self.state.clone(); - let session = next - .sessions - .get_mut(cookie_hash) - .context("local session vanished during refresh")?; - if session.revoked_at.is_some() || session.access_revision != input.expected_access_revision - { - bail!("local session changed during refresh"); - } - session.access_revision = input.access_revision; - session.verified_capabilities = input.capabilities; - session.access_expires_at = input.access_expires_at; - session.refresh_expires_at = input.refresh_expires_at; - session.encrypted_refresh_claim = wrap_refresh( - &self.wrapping_key, - &session.account_subject_hash, - &session.heimdall_session_id, - input.refresh_claim, - )?; - session.last_refresh_at = Utc::now(); - self.commit(next) - } - - pub fn selected_campaign(&self, account_subject_hash: &str) -> Option { - self.state - .account_preferences - .get(account_subject_hash)? - .selected_campaign_id - } - - pub fn select_campaign( - &mut self, - account_subject_hash: &str, - campaign_id: uuid::Uuid, - ) -> anyhow::Result<()> { - let mut next = self.state.clone(); - let preferences = next - .account_preferences - .entry(account_subject_hash.into()) - .or_insert(AccountPreferences { - schema: "ghostlight.account_preferences.v1".into(), - account_subject_hash: account_subject_hash.into(), - selected_campaign_id: None, - updated_at: Utc::now(), - }); - preferences.selected_campaign_id = Some(campaign_id); - preferences.updated_at = Utc::now(); - self.commit(next) - } - - pub fn clear_selected_campaign(&mut self, account_subject_hash: &str) -> anyhow::Result<()> { - let mut next = self.state.clone(); - let preferences = next - .account_preferences - .entry(account_subject_hash.into()) - .or_insert(AccountPreferences { - schema: "ghostlight.account_preferences.v1".into(), - account_subject_hash: account_subject_hash.into(), - selected_campaign_id: None, - updated_at: Utc::now(), - }); - preferences.selected_campaign_id = None; - preferences.updated_at = Utc::now(); - self.commit(next) - } - - pub fn migrate_preference( - &mut self, - account_subject_hash: &str, - campaign_id: uuid::Uuid, - ) -> anyhow::Result<()> { - if self.selected_campaign(account_subject_hash).is_none() { - self.select_campaign(account_subject_hash, campaign_id)?; - } - Ok(()) - } - - pub fn reserve_command( - &mut self, - account_subject_hash: &str, - idempotency_key: &str, - operation_id: &str, - ) -> anyhow::Result { - let key = command_cache_key(account_subject_hash, idempotency_key); - if let Some(entry) = self.state.command_receipts.get(&key) { - if entry.operation_id != operation_id - || entry.account_subject_hash != account_subject_hash - { - bail!("idempotency key is already bound to another operation"); - } - return match &entry.command_result_messagepack { - Some(bytes) => Ok(CommandReservation::Cached(rmp_serde::from_slice(bytes)?)), - None => Ok(CommandReservation::Pending), - }; - } - let mut next = self.state.clone(); - next.command_receipts.insert( - key, - EveCommandCacheEntry { - schema: "ghostlight.eve_command_cache_entry.v1".into(), - account_subject_hash: account_subject_hash.into(), - idempotency_key: idempotency_key.into(), - operation_id: operation_id.into(), - command_result_messagepack: None, - created_at: Utc::now(), - }, + fn commit(&mut self, mut next: AppSessionState) -> anyhow::Result<()> { + self.ensure_owned()?; + prune_sessions(&mut next, Utc::now()); + let next_row = envelope(&next)?; + let swapped = self.store.compare_and_swap_batch( + std::slice::from_ref(&self.row), + std::slice::from_ref(&next_row), ); - self.commit(next)?; - Ok(CommandReservation::Reserved) - } - - pub fn record_command_result( - &mut self, - account_subject_hash: &str, - idempotency_key: &str, - operation_id: &str, - result: &serde_json::Value, - ) -> anyhow::Result<()> { - let key = command_cache_key(account_subject_hash, idempotency_key); - let mut next = self.state.clone(); - let entry = next - .command_receipts - .get_mut(&key) - .ok_or_else(|| anyhow::anyhow!("command result has no reservation"))?; - if entry.operation_id != operation_id || entry.account_subject_hash != account_subject_hash - { - bail!("command result disagrees with its reservation"); + if !matches!(swapped, Ok(true)) { + return self.poison(anyhow::anyhow!( + "app-session commit outcome is uncertain; sole ownership was lost" + )); } - entry.command_result_messagepack = Some(rmp_serde::to_vec_named(result)?); - self.commit(next) - } - - pub fn issue_campaign_export_grant( - &mut self, - account_subject_hash: &str, - campaign_id: uuid::Uuid, - export_path: std::path::PathBuf, - filename: String, - now: DateTime, - lifetime: chrono::Duration, - ) -> anyhow::Result { - if lifetime <= chrono::Duration::zero() { - bail!("campaign export grant lifetime must be positive"); + if self.store.validate_path_identity().is_err() { + return self.poison(anyhow::anyhow!( + "app-session store path changed after durable commit" + )); } - if filename.is_empty() - || filename.contains('/') - || filename.contains('\\') - || filename.chars().any(char::is_control) - { - bail!("campaign export filename is invalid"); - } - let mut token_bytes = [0_u8; 32]; - rand::rng().fill_bytes(&mut token_bytes); - let raw_token = URL_SAFE_NO_PAD.encode(token_bytes); - let token_hash = secret_hash(&format!("campaign-export:{raw_token}")); - let mut next = self.state.clone(); - next.campaign_export_grants.retain(|_, grant| { - grant.expires_at > now - || grant - .consumed_at - .is_some_and(|at| at > now - chrono::Duration::days(1)) - }); - next.campaign_export_grants.insert( - token_hash.clone(), - CampaignExportGrant { - schema: "ghostlight.campaign_export_grant.v1".into(), - token_hash, - account_subject_hash: account_subject_hash.into(), - campaign_id, - export_path, - filename, - created_at: now, - expires_at: now + lifetime, - consumed_at: None, - }, - ); - self.commit(next)?; - Ok(raw_token) - } - - pub fn consume_campaign_export_grant( - &mut self, - raw_token: &str, - account_subject_hash: &str, - now: DateTime, - ) -> anyhow::Result> { - let token_hash = secret_hash(&format!("campaign-export:{raw_token}")); - let Some(grant) = self.state.campaign_export_grants.get(&token_hash) else { - return Ok(None); - }; - if grant.account_subject_hash != account_subject_hash - || grant.expires_at <= now - || grant.consumed_at.is_some() - { - return Ok(None); - } - let resource = CampaignExportResource { - campaign_id: grant.campaign_id, - export_path: grant.export_path.clone(), - filename: grant.filename.clone(), - }; - let mut next = self.state.clone(); - next.campaign_export_grants - .get_mut(&token_hash) - .context("campaign export grant vanished during consumption")? - .consumed_at = Some(now); - self.commit(next)?; - Ok(Some(resource)) - } - - fn commit(&mut self, next: AppSessionState) -> anyhow::Result<()> { - let next_row = self - .store - .replace(&self.row, "ghostlight.app_session_store.v1", &next)?; self.row = next_row; self.state = next; Ok(()) } + + fn ensure_owned(&mut self) -> anyhow::Result<()> { + if !self.healthy { + bail!("app-session custody is poisoned; reopen the owner"); + } + if self.store.validate_path_identity().is_err() { + self.healthy = false; + bail!("app-session store ownership was lost"); + } + Ok(()) + } + + fn poison(&mut self, error: anyhow::Error) -> anyhow::Result { + self.healthy = false; + Err(error) + } } -fn command_cache_key(account_subject_hash: &str, idempotency_key: &str) -> String { - secret_hash(&format!( - "eve-command:{account_subject_hash}:{idempotency_key}" - )) -} - -pub fn secret_hash(value: &str) -> String { +pub(crate) fn secret_hash(value: &str) -> String { format!("sha256:{:x}", Sha256::digest(value.as_bytes())) } +fn envelope(state: &AppSessionState) -> anyhow::Result { + Ok(CultCacheEnvelope { + key: STORE_KEY.into(), + r#type: STORE_TYPE.into(), + payload: rmp_serde::to_vec_named(state)?, + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(STORE_SCHEMA.into()), + }) +} + +fn validate_state(state: &AppSessionState, wrapping_key: &[u8; 32]) -> anyhow::Result<()> { + if state.schema != STORE_SCHEMA { + bail!("app-session state schema is invalid"); + } + for (key, session) in &state.sessions { + if key != &session.cookie_hash + || !is_secret_hash(key) + || !is_secret_hash(&session.account_subject_hash) + || session.schema != "ghostlight.app_session.v2" + || session.heimdall_session_id.trim().is_empty() + || session.heimdall_session_id.trim() != session.heimdall_session_id + || !session + .verified_capabilities + .iter() + .any(|value| value == "app_access") + || session.refresh_expires_at <= session.access_expires_at + || session.last_refresh_at < session.created_at + || session + .revoked_at + .is_some_and(|revoked_at| revoked_at < session.created_at) + { + bail!("app-session state contains a noncanonical session"); + } + unwrap_refresh( + wrapping_key, + &session.account_subject_hash, + &session.heimdall_session_id, + &session.encrypted_refresh_claim, + ) + .context("app-session state contains an unreadable refresh claim")?; + } + Ok(()) +} + +fn is_secret_hash(value: &str) -> bool { + value.len() == 71 + && value.strip_prefix("sha256:").is_some_and(|hex| { + hex.bytes() + .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) + }) +} + +fn prune_sessions(state: &mut AppSessionState, now: DateTime) { + let retention_floor = now - chrono::Duration::days(7); + state.sessions.retain(|_, session| { + session.refresh_expires_at > retention_floor + && session + .revoked_at + .is_none_or(|revoked_at| revoked_at > retention_floor) + }); + if state.sessions.len() <= MAX_SESSION_RECORDS { + return; + } + let mut oldest = state + .sessions + .iter() + .map(|(key, session)| { + let live = session.revoked_at.is_none() && session.refresh_expires_at > now; + (live, session.last_refresh_at, key.clone()) + }) + .collect::>(); + oldest.sort(); + for (_, _, key) in oldest + .into_iter() + .take(state.sessions.len() - MAX_SESSION_RECORDS) + { + state.sessions.remove(&key); + } +} + fn read_wrapping_key(path: &Path) -> anyhow::Result<[u8; 32]> { - let source = - std::fs::read(path).with_context(|| format!("failed to read {}", path.display()))?; + let source = std::fs::read(path) + .with_context(|| format!("failed to read session wrapping key {}", path.display()))?; let decoded = if source.len() == 32 { source } else { - let text = std::str::from_utf8(&source)?.trim(); URL_SAFE_NO_PAD - .decode(text) + .decode(std::str::from_utf8(&source)?.trim()) .context("session wrapping key must be 32 raw bytes or base64url")? }; decoded @@ -545,7 +484,7 @@ fn wrap_refresh( ) -> anyhow::Result { let mut iv = [0_u8; 12]; rand::rng().fill_bytes(&mut iv); - let aad = format!("ghostlight.app_session.refresh.v1\n{account_hash}\n{session_id}"); + let aad = format!("ghostlight.app_session.refresh.v2\n{account_hash}\n{session_id}"); let ciphertext = Aes256Gcm::new_from_slice(key)? .encrypt( (&iv).into(), @@ -571,12 +510,12 @@ fn unwrap_refresh( let (iv, ciphertext) = wrapped .split_once('.') .context("wrapped refresh claim is malformed")?; - let iv = URL_SAFE_NO_PAD.decode(iv)?; - let iv: [u8; 12] = iv + let iv: [u8; 12] = URL_SAFE_NO_PAD + .decode(iv)? .try_into() .map_err(|_| anyhow::anyhow!("wrapped refresh IV is invalid"))?; let ciphertext = URL_SAFE_NO_PAD.decode(ciphertext)?; - let aad = format!("ghostlight.app_session.refresh.v1\n{account_hash}\n{session_id}"); + let aad = format!("ghostlight.app_session.refresh.v2\n{account_hash}\n{session_id}"); let plaintext = Aes256Gcm::new_from_slice(key)? .decrypt( (&iv).into(), @@ -592,200 +531,202 @@ fn unwrap_refresh( #[cfg(test)] mod tests { use super::*; - use tempfile::tempdir; + + fn session(claim: &str) -> VerifiedSessionAdmission { + VerifiedSessionAdmission::fixture( + "account-1", + "heimdall-session-1", + 3, + Utc::now() + chrono::Duration::minutes(5), + Utc::now() + chrono::Duration::days(7), + claim, + ) + } #[test] - fn app_session_persists_cookie_hash_and_selected_campaign_without_campaign_lists() { - let directory = tempdir().unwrap(); + fn store_rejects_an_alternate_messagepack_shape() { + let directory = tempfile::tempdir().unwrap(); + let key = directory.path().join("session.key"); + std::fs::write(&key, [5_u8; 32]).unwrap(); + let store_path = directory.path().join("app-sessions-v2.cc"); + let store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); + let state = AppSessionState { + schema: STORE_SCHEMA.into(), + sessions: BTreeMap::new(), + }; + let row = CultCacheEnvelope { + key: STORE_KEY.into(), + r#type: STORE_TYPE.into(), + payload: rmp_serde::to_vec(&state).unwrap(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(STORE_SCHEMA.into()), + }; + assert!(store.compare_and_swap_batch(&[], &[row]).unwrap()); + drop(store); + assert!(AppSessionOwner::open(&store_path, &key).is_err()); + } + + #[test] + fn stores_only_session_custody_and_reopens() { + let directory = tempfile::tempdir().unwrap(); let key = directory.path().join("session.key"); std::fs::write(&key, [7_u8; 32]).unwrap(); - let store = directory.path().join("app-sessions.cc"); + let store = directory.path().join("app-sessions-v2.cc"); let mut owner = AppSessionOwner::open(&store, &key).unwrap(); let cookie = owner - .create_session(NewSession { - account_id: "account-1", - heimdall_session_id: "heimdall-session-1", - access_revision: 3, - capabilities: vec!["app_access".into()], - access_expires_at: Utc::now() + chrono::Duration::minutes(5), - refresh_expires_at: Utc::now() + chrono::Duration::days(7), - refresh_claim: "private-refresh-claim", - }) + .create_session(session("private-refresh-claim")) .unwrap(); - let account = owner.account_for_cookie(&cookie, Utc::now()).unwrap(); - assert!(!store.to_string_lossy().contains(&cookie)); - let campaign = uuid::Uuid::new_v4(); - owner.select_campaign(&account, campaign).unwrap(); - drop(owner); - let reopened = AppSessionOwner::open(&store, &key).unwrap(); - assert_eq!( - reopened.account_for_cookie(&cookie, Utc::now()), - Some(account.clone()) - ); - assert_eq!(reopened.selected_campaign(&account), Some(campaign)); - drop(reopened); - let bytes = std::fs::read(&store).unwrap(); - assert!( - !bytes - .windows(cookie.len()) - .any(|window| window == cookie.as_bytes()) - ); - assert!( - !bytes - .windows("private-refresh-claim".len()) - .any(|window| window == b"private-refresh-claim") - ); - } - - #[test] - fn campaign_entry_clears_only_the_selected_preference() { - let directory = tempdir().unwrap(); - let key = directory.path().join("session.key"); - std::fs::write(&key, [7_u8; 32]).unwrap(); - let store = directory.path().join("app-sessions.cc"); - let mut owner = AppSessionOwner::open(&store, &key).unwrap(); - let account = "sha256:player"; - owner - .select_campaign(account, uuid::Uuid::new_v4()) - .unwrap(); - - owner.clear_selected_campaign(account).unwrap(); - - assert_eq!(owner.selected_campaign(account), None); - assert!(owner.state.account_preferences.contains_key(account)); - } - - #[test] - fn campaign_export_grant_is_hashed_account_bound_expiring_and_single_use() { - let directory = tempdir().unwrap(); - let key = directory.path().join("session.key"); - std::fs::write(&key, [7_u8; 32]).unwrap(); - let store = directory.path().join("app-sessions.cc"); - let mut owner = AppSessionOwner::open(&store, &key).unwrap(); - let campaign_id = uuid::Uuid::new_v4(); - let export_path = directory.path().join("campaign.cc"); - let now = Utc::now(); - let token = owner - .issue_campaign_export_grant( - "sha256:owner", - campaign_id, - export_path.clone(), - "campaign.cc".into(), - now, - chrono::Duration::minutes(15), - ) - .unwrap(); - - assert!( - owner - .consume_campaign_export_grant(&token, "sha256:intruder", now) - .unwrap() - .is_none() - ); - let resource = owner - .consume_campaign_export_grant(&token, "sha256:owner", now) + let account = owner + .account_for_cookie(&cookie, Utc::now()) .unwrap() .unwrap(); - assert_eq!(resource.campaign_id, campaign_id); - assert_eq!(resource.export_path, export_path); + let account_hash = account.account_subject_hash().to_owned(); + drop(owner); + + let mut reopened = AppSessionOwner::open(&store, &key).unwrap(); + assert_eq!( + reopened + .account_for_cookie(&cookie, Utc::now()) + .unwrap() + .unwrap() + .account_subject_hash(), + account_hash + ); + assert!(reopened.revoke_cookie(&cookie).unwrap()); + assert_eq!( + reopened.account_for_cookie(&cookie, Utc::now()).unwrap(), + None + ); + } + + #[test] + fn exact_heimdall_adoption_retry_rotates_the_only_live_cookie() { + let directory = tempfile::tempdir().unwrap(); + let key = directory.path().join("session.key"); + std::fs::write(&key, [9_u8; 32]).unwrap(); + let store = directory.path().join("app-sessions-v2.cc"); + let mut owner = AppSessionOwner::open(&store, &key).unwrap(); + let first = owner + .create_session(session("same-refresh-receipt")) + .unwrap(); + let second = owner + .create_session(session("same-refresh-receipt")) + .unwrap(); + + assert_ne!(first, second); + assert_eq!(owner.account_for_cookie(&first, Utc::now()).unwrap(), None); assert!( owner - .consume_campaign_export_grant(&token, "sha256:owner", now) + .account_for_cookie(&second, Utc::now()) .unwrap() - .is_none() + .is_some() ); + assert_eq!( + owner + .state + .sessions + .values() + .filter(|session| session.revoked_at.is_none()) + .count(), + 1 + ); + } + + #[test] + fn rejects_legacy_or_foreign_store_instead_of_migrating_it() { + let directory = tempfile::tempdir().unwrap(); + let key = directory.path().join("session.key"); + std::fs::write(&key, [3_u8; 32]).unwrap(); + let store_path = directory.path().join("app-sessions-v2.cc"); + let store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap(); + let foreign = CultCacheEnvelope { + key: "primary".into(), + r#type: "app_session_store.v1".into(), + payload: vec![], + stored_at: Utc::now().to_rfc3339(), + schema_id: Some("ghostlight.app_session_store.v1".into()), + }; + assert!(store.compare_and_swap_batch(&[], &[foreign]).unwrap()); + assert!(AppSessionOwner::open(&store_path, &key).is_err()); + } + + #[test] + fn refresh_claim_is_encrypted_and_exactly_bound() { + let directory = tempfile::tempdir().unwrap(); + let key = directory.path().join("session.key"); + std::fs::write(&key, [11_u8; 32]).unwrap(); + let store = directory.path().join("app-sessions-v2.cc"); + let mut owner = AppSessionOwner::open(&store, &key).unwrap(); + let cookie = owner + .create_session(session("needle-private-refresh")) + .unwrap(); + let candidate = owner.session_for_logout(&cookie).unwrap().unwrap(); + assert_eq!(candidate.refresh_claim, "needle-private-refresh"); drop(owner); let bytes = std::fs::read(store).unwrap(); assert!( !bytes - .windows(token.len()) - .any(|window| window == token.as_bytes()) - ); - - let mut reopened = - AppSessionOwner::open(directory.path().join("app-sessions-expired.cc"), &key).unwrap(); - let expired = reopened - .issue_campaign_export_grant( - "sha256:owner", - campaign_id, - directory.path().join("expired.cc"), - "expired.cc".into(), - now, - chrono::Duration::seconds(1), - ) - .unwrap(); - assert!( - reopened - .consume_campaign_export_grant( - &expired, - "sha256:owner", - now + chrono::Duration::seconds(2), - ) - .unwrap() - .is_none() + .windows("needle-private-refresh".len()) + .any(|window| window == b"needle-private-refresh") ); } #[test] - fn refresh_is_exact_session_cas_and_rotates_private_claim() { - let directory = tempdir().unwrap(); + fn replacing_the_store_path_revokes_session_authentication_until_reopen() { + let directory = tempfile::tempdir().unwrap(); let key = directory.path().join("session.key"); - std::fs::write(&key, [11_u8; 32]).unwrap(); - let mut owner = - AppSessionOwner::open(directory.path().join("app-sessions.cc"), &key).unwrap(); - let now = Utc::now(); + std::fs::write(&key, [19_u8; 32]).unwrap(); + let path = directory.path().join("app-sessions-v2.cc"); + let displaced = directory.path().join("displaced.cc"); + let mut owner = AppSessionOwner::open(&path, &key).unwrap(); let cookie = owner - .create_session(NewSession { - account_id: "account-1", - heimdall_session_id: "session-1", - access_revision: 4, - capabilities: vec!["app_access".into()], - access_expires_at: now + chrono::Duration::minutes(2), - refresh_expires_at: now + chrono::Duration::days(7), - refresh_claim: "refresh-before", - }) + .create_session(session("private-refresh-claim")) .unwrap(); - let due = owner - .sessions_due_for_refresh(now, chrono::Duration::minutes(5)) - .unwrap(); - assert_eq!(due.len(), 1); - assert_eq!(due[0].refresh_claim, "refresh-before"); - owner - .apply_refresh( - &due[0].cookie_hash, - RefreshedSession { - expected_access_revision: 4, - access_revision: 5, - capabilities: vec!["app_access".into()], - access_expires_at: now + chrono::Duration::hours(1), - refresh_expires_at: now + chrono::Duration::days(7), - refresh_claim: "refresh-after", - }, - ) - .unwrap(); + std::fs::rename(&path, &displaced).unwrap(); + std::fs::File::create(&path).unwrap(); + assert!(owner.account_for_cookie(&cookie, Utc::now()).is_err()); + assert!(!owner.is_healthy()); + + std::fs::remove_file(&path).unwrap(); + std::fs::rename(&displaced, &path).unwrap(); + assert!(owner.account_for_cookie(&cookie, Utc::now()).is_err()); + drop(owner); + + let mut reopened = AppSessionOwner::open(&path, &key).unwrap(); assert!( - owner - .apply_refresh( - &due[0].cookie_hash, - RefreshedSession { - expected_access_revision: 4, - access_revision: 6, - capabilities: vec!["app_access".into()], - access_expires_at: now + chrono::Duration::hours(1), - refresh_expires_at: now + chrono::Duration::days(7), - refresh_claim: "stale-refresh", - } - ) - .is_err() - ); - assert_eq!( - owner - .session_for_logout(&cookie) + reopened + .account_for_cookie(&cookie, Utc::now()) .unwrap() - .unwrap() - .refresh_claim, - "refresh-after" + .is_some() ); } + + #[test] + fn reopen_rejects_corrupt_inner_session_custody() { + let directory = tempfile::tempdir().unwrap(); + let key = directory.path().join("session.key"); + std::fs::write(&key, [23_u8; 32]).unwrap(); + let path = directory.path().join("app-sessions-v2.cc"); + let mut owner = AppSessionOwner::open(&path, &key).unwrap(); + owner + .create_session(session("private-refresh-claim")) + .unwrap(); + drop(owner); + + let store = OwnedRedbMessagePackBackingStore::new(&path).unwrap(); + let rows = store.pull_all().unwrap(); + let mut state: AppSessionState = rmp_serde::from_slice(&rows[0].payload).unwrap(); + state + .sessions + .values_mut() + .next() + .unwrap() + .encrypted_refresh_claim = "not-an-encrypted-claim".into(); + let corrupt = envelope(&state).unwrap(); + assert!(store.compare_and_swap_batch(&rows, &[corrupt]).unwrap()); + drop(store); + + assert!(AppSessionOwner::open(&path, &key).is_err()); + } } diff --git a/crates/ghostlight-dungeon/src/assessor.rs b/crates/ghostlight-dungeon/src/assessor.rs deleted file mode 100644 index 6e3b398..0000000 --- a/crates/ghostlight-dungeon/src/assessor.rs +++ /dev/null @@ -1,4430 +0,0 @@ -use crate::{ - domain::{ - ActionAssessment, ActionIntent, Campaign, ContextModifier, MAX_POSTURE_CHARS, - WorldEffectDelta, - }, - model::{ - ModelPort, ModelProviderAttemptReceipt, ModelStageReceipt, ModelStageRequest, - ModelTokenUsage, run_validated_stage, - }, - persistence::CampaignStore, - session_zero::{AggregatedBoundary, CampaignContract, ExtraordinaryPermission}, -}; -use anyhow::{Result, anyhow}; -use chrono::{Duration, Utc}; -use schemars::{JsonSchema, schema_for}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::{ - collections::{BTreeMap, BTreeSet}, - sync::Arc, -}; - -const ASSESSMENT_PROPOSAL_CACHE_KIND: &str = "assessment_proposal_cache.v1"; -const ASSESSMENT_PROPOSAL_CACHE_SCHEMA: &str = "ghostlight.private.assessment_proposal_cache.v6"; -const ASSESSMENT_SCOPE_CACHE_KIND: &str = "assessment_mutation_scope_cache.v1"; -const ASSESSMENT_SCOPE_CACHE_SCHEMA: &str = "ghostlight.private.assessment_mutation_scope_cache.v5"; -const ASSESSMENT_SEMANTICS_VERSION: &str = "ghostlight.action_assessment.v12"; - -const ASSESSMENT_SCOPE_INSTRUCTIONS: &str = "You own the compact admission and mutation-scope preflight for one fiction-first attempt. Decide 'deny' only when no d20 outcome can realize the exact intended effect from the supplied authority: the attempt lacks required capability, custody, access, spatial reach, extraordinary permission, an exact typed mutation path, or demands guaranteed control over another subject's independent future choices. A bounded attempt to influence a present subject's voluntary response is not guaranteed control: when the means can plausibly reach that subject, assess it and represent a successful voluntary promise, agreement, plan, goal, or obligation through actor_commitments. Difficulty, opposition, danger, or a costly but bounded effect are not reasons to deny; use 'assess' and let the full assessor set the DC and ceiling. For 'assess', select the smallest causally plausible typed mutation vocabulary. Availability is never relevance. Put every selected lane in lanes. Also put in required_success_lanes every lane whose non-empty mutation is necessary for strong and ordinary success to realize the intended effect; direct costs or incidental consequences are allowed lanes but are not required success lanes. actor_conditions changes bodily or situational conditions. actor_commitments adds or retires an exact present actor's goal or obligation; it records that actor's voluntary commitment and never grants custody of them or guarantees behavior beyond it. actor_knowledge_additions acquires or communicates an exact existing fact to an exact present actor allowed by the supplied lane. A subject receiving, recognizing, learning, remembering, or becoming able to act on information is a canonical knowledge transition even when narration is the only player-visible effect. If the intended recipient is an institution, population, place, remote actor, absent actor, unspecified office, or other subject for which no exact knowledge-recipient lane is structurally available, deny the intended effect and name the missing recipient/channel mutation path. Do not assess with empty information lanes while promising receipt or recognition in the stakes. actor_observations admits a new branch-local finding only when the acting actor's exact means directly perceives, measures, inspects, or tests something within current spatial reach; it cannot invent a remote event, hidden motive, unsupported identity, or conclusion beyond the intended effect and effect ceiling. Do not select either information lane for ordinary speech, promises, persuasion, trust, or scene texture. actor_relationship_updates changes durable trust, regard, leverage, or another exact relationship. actor_moves relocates the acting character along an admitted route. clock_advances and clock_reductions change an existing pressure. institution_postures changes an institution's durable policy or stance; posture is not a substitute for knowledge receipt. For 'deny', both lane sets must be empty and denial must state the exact missing permission or mutation path, the maximum effect declaration alone can have, one concise refusal stake, and one to four actionable bargains that could admit a narrower future assessment. For 'assess', denial must be null. Never infer a new lane, target, route, clock, institution, possession, or permission. New propositions are permitted only through actor_observations. Return only the typed JSON."; - -const ASSESSMENT_EFFECT_VERIFIER_INSTRUCTIONS: &str = "You are the private semantic verifier between the fiction-first action assessor and the world kernel. Structural authority, reach, knowledge access, and mutation shape were already checked. Judge the complete four-band typed effect bundle against the player's exact means and intended effect. Every non-empty mutation must be a direct realization of the intended effect or a concrete, previewed consequence of the attempted means in that exact outcome band. Every visible stake must also be backed by the typed mutations that would make its canonical claims true. A subject receiving, recognizing, learning, remembering, or becoming able to act on information is a knowledge transition. If a stake claims such a transition without an exact typed knowledge mutation for that exact recipient, return mismatch_kind 'effect_omission'; ordinary speech, narration, an institution posture change, or a sender's observation is not a substitute. Acquiring or communicating an existing fact requires a causally related information action. Admitting a new actor_observations finding requires exact local means that directly perceive, measure, inspect, or test it, and the statement must remain within the intended effect and effect ceiling. An actor_observations entry becomes canonical knowledge if its outcome is committed. It must therefore be a concrete, truth-apt proposition about what the inspection actually finds. Reject an entry that merely says the actor determines, establishes, learns, or discovers whether something is true; repeats the intended question; preserves an 'if one exists' placeholder; or otherwise reports completion of an inquiry without resolving it. A bounded concrete negative finding is valid. When supplied canon does not determine harmless local texture, the assessment may preview the smallest reversible branch-local detail consistent with the location and evidence; it must state that detail rather than leave a template for a later resolver. A plausible general reaction does not justify changing a commitment, relationship, condition, clock, posture, movement, or knowledge record that the attempted means and stakes do not cause. A target actor's new commitment must be a plausible voluntary response to the attempted influence, never disguised custody or guaranteed obedience. Failure and mixed effects may impose direct costs or complications, but not arbitrary available state changes. The effect ceiling and visible stakes must describe the same bounded consequences as the typed effects. Do not reassess admissibility, DC, or modifiers, and do not choose replacement effects. Return one JSON object. If every typed mutation is causally faithful and epistemically complete, use result 'match' with null mismatch_kind and null repair_guidance. Otherwise use result 'mismatch', one mismatch_kind, and one concrete repair sentence of at most 240 characters naming what must be removed or aligned. Shape: {\"result\":\"match\",\"mismatch_kind\":null,\"repair_guidance\":null}."; - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct AssessmentProposal { - normalized_intent: String, - admissible: bool, - missing_permission: Option, - dc: u8, - modifiers: Vec, - effect_ceiling: String, - success_stake: String, - mixed_stake: String, - failure_stake: String, - strong_effect: WorldEffectDelta, - success_effect: WorldEffectDelta, - mixed_effect: WorldEffectDelta, - failure_effect: WorldEffectDelta, - bargains: Vec, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum ConditionMutationOperation { - Add, - Remove, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct ActorConditionMutation { - actor_id: String, - operation: ConditionMutationOperation, - condition: String, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum ActorCommitmentMutationOperation { - AddGoal, - RetireGoal, - AddObligation, - RetireObligation, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct ActorCommitmentMutation { - actor_id: String, - operation: ActorCommitmentMutationOperation, - description: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct ActorKnowledgeMutation { - actor_id: String, - statement: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct ActorObservationMutation { - actor_id: String, - statement: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct ActorRelationshipMutation { - actor_id: String, - target_id: String, - relationship: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct ActorMoveMutation { - actor_id: String, - destination_id: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct ClockMutation { - clock_id: String, - amount: u8, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct InstitutionPostureMutation { - institution_id: String, - posture: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -struct AssessmentProposalCacheEntry { - schema: String, - basis_digest: String, - proposal: AssessmentProposal, - source_provider: String, - source_model: String, - source_scope_receipt_hash: String, - source_receipt_hash: String, - #[serde(default)] - source_effect_verifier_receipt_hash: Option, - created_at: chrono::DateTime, -} - -#[derive( - Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, -)] -#[serde(rename_all = "snake_case")] -enum AssessmentMutationLane { - ActorConditions, - ActorCommitments, - ActorKnowledgeAdditions, - ActorObservations, - ActorRelationshipUpdates, - ActorMoves, - ClockAdvances, - ClockReductions, - InstitutionPostures, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum AssessmentScopeDecision { - Assess, - Deny, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -struct AssessmentDenial { - normalized_intent: String, - missing_permission: String, - effect_ceiling: String, - refusal_stake: String, - bargains: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -struct AssessmentMutationScope { - decision: AssessmentScopeDecision, - lanes: BTreeSet, - required_success_lanes: BTreeSet, - denial: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -struct AssessmentMutationScopeCacheEntry { - schema: String, - basis_digest: String, - scope: AssessmentMutationScope, - source_provider: String, - source_model: String, - source_receipt_hash: String, - created_at: chrono::DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum AssessmentEffectMatchResult { - Match, - Mismatch, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum AssessmentEffectMismatchKind { - UnrelatedMutation, - EffectOmission, - EffectReversal, - TargetSubstitution, - InventedOutcome, - WrongEffectKind, - StakeMutationMismatch, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -struct AssessmentEffectVerification { - result: AssessmentEffectMatchResult, - mismatch_kind: Option, - repair_guidance: Option, -} - -pub struct ActionAssessor { - model: Arc, - verifier_model_id: String, - model_id: String, -} -impl ActionAssessor { - pub fn new(model: Arc, model_id: impl Into) -> Self { - let model_id = model_id.into(); - Self { - model, - verifier_model_id: model_id.clone(), - model_id, - } - } - - pub fn with_models( - model: Arc, - verifier_model_id: impl Into, - model_id: impl Into, - ) -> Self { - Self { - model, - verifier_model_id: verifier_model_id.into(), - model_id: model_id.into(), - } - } - pub async fn assess( - &self, - campaign: &Campaign, - intent: ActionIntent, - ) -> Result<(ActionAssessment, ModelStageReceipt)> { - self.assess_with_permissions(campaign, intent, &[]).await - } - - pub async fn assess_with_permissions( - &self, - campaign: &Campaign, - intent: ActionIntent, - extraordinary_permissions: &[ExtraordinaryPermission], - ) -> Result<(ActionAssessment, ModelStageReceipt)> { - self.assess_with_context(campaign, intent, extraordinary_permissions, None, &[]) - .await - } - - pub async fn assess_with_context( - &self, - campaign: &Campaign, - intent: ActionIntent, - extraordinary_permissions: &[ExtraordinaryPermission], - campaign_contract: Option<&CampaignContract>, - aggregate_boundaries: &[AggregatedBoundary], - ) -> Result<(ActionAssessment, ModelStageReceipt)> { - self.assess_with_context_inner( - None, - campaign, - intent, - extraordinary_permissions, - campaign_contract, - aggregate_boundaries, - ) - .await - } - - pub async fn assess_with_context_cached( - &self, - store: &CampaignStore, - campaign: &Campaign, - intent: ActionIntent, - extraordinary_permissions: &[ExtraordinaryPermission], - campaign_contract: Option<&CampaignContract>, - aggregate_boundaries: &[AggregatedBoundary], - ) -> Result<(ActionAssessment, ModelStageReceipt)> { - self.assess_with_context_inner( - Some(store), - campaign, - intent, - extraordinary_permissions, - campaign_contract, - aggregate_boundaries, - ) - .await - } - - async fn assess_with_context_inner( - &self, - store: Option<&CampaignStore>, - campaign: &Campaign, - intent: ActionIntent, - extraordinary_permissions: &[ExtraordinaryPermission], - campaign_contract: Option<&CampaignContract>, - aggregate_boundaries: &[AggregatedBoundary], - ) -> Result<(ActionAssessment, ModelStageReceipt)> { - let actor = campaign - .actors - .get(&intent.actor_id) - .ok_or_else(|| anyhow!("actor does not exist in this branch"))?; - let location = campaign - .locations - .get(&actor.location_id) - .ok_or_else(|| anyhow!("actor location is invalid"))?; - let visible_institutions: Vec<_> = campaign - .institutions - .values() - .map(|x| serde_json::json!({"id":x.id,"name":x.name,"posture":x.posture})) - .collect(); - let present_actors: Vec<_> = campaign - .actors - .values() - .filter(|candidate| candidate.location_id == actor.location_id) - .map(|candidate| { - serde_json::json!({ - "id": candidate.id, - "name": candidate.name, - "conditions": candidate.conditions, - "relationships": candidate.relationships, - }) - }) - .collect(); - let (mutation_scope, scope_receipt) = self - .select_mutation_scope( - store, - campaign, - &intent, - actor, - extraordinary_permissions, - campaign_contract, - aggregate_boundaries, - ) - .await?; - let information_facts = if mutation_scope - .lanes - .contains(&AssessmentMutationLane::ActorKnowledgeAdditions) - { - available_information_facts(campaign, actor) - } else { - Vec::new() - }; - let mut allowed_references = allowed_references(campaign, actor); - allowed_references.extend(present_actor_references(campaign, actor)); - allowed_references.extend( - extraordinary_permissions - .iter() - .map(|permission| format!("extraordinary_permission:{}", permission.id)), - ); - if matches!(mutation_scope.decision, AssessmentScopeDecision::Deny) { - let proposal = denied_assessment_proposal(&mutation_scope)?; - let proposal = validate_and_bind_proposal( - proposal, - campaign, - actor, - &allowed_references, - &mutation_scope, - )?; - return Ok((build_assessment(campaign, intent, proposal)?, scope_receipt)); - } - let source_scope_receipt_hash = scope_receipt.receipt_hash.clone(); - let agency_guidance = action_agency_guidance( - campaign - .agency_profiles - .get(&intent.actor_id) - .is_some_and(|profile| !profile.simulation_eligible) - || intent.actor_id == campaign.player_actor_id, - ); - let mut schema = serde_json::to_value(schema_for!(AssessmentProposal))?; - constrain_assessment_schema(&mut schema, &allowed_references, campaign, actor)?; - project_effect_schema_to_mutation_entries(&mut schema, campaign)?; - constrain_effect_schema_to_scope(&mut schema, &mutation_scope.lanes)?; - require_success_scope(&mut schema, &mutation_scope.required_success_lanes)?; - let base_prompt = format!( - "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nAssess an attempted effect, not whether words can be spoken. Impossible actions are inadmissible and receive bargains, not a roll. Choose DC only from 5,10,15,20,25,30. Every modifier reference must be copied exactly from ALLOWED REFERENCES. Modifier total is capped at +/-10. Never grant capability, custody, access, knowledge, or spatial reach absent from state. Accepted extraordinary permissions are binding: preserve their prerequisites, costs, limits, exposure, and effect ceiling exactly; they admit only effects within that scope. The campaign contract governs tone, pacing, focus, consequence style, and DM style. Obey every aggregate content boundary: line excludes the topic, veil keeps it off-screen, ask_first admits no new depiction without a current explicit acceptance. Never reveal attribution. State concrete success, mixed, and failure consequences and a bounded effect ceiling. The private scope projection has already removed mutation lanes that are not causally plausible for this exact attempt. The remaining lanes are an upper bound, not a request to use all of them. When admissible, every required_success_lane in MUTATION SCOPE must contain at least one mutation entry in both strong_effect and success_effect; a success stake may not claim an intended canonical change that its typed effect omits. Every non-empty mutation must be directly caused by the exact attempted means or realize the exact intended effect in that outcome band. A fact, relationship, clock, posture, or route being true, nearby, discoverable, or useful does not make changing it a consequence of an unrelated attempt. Do not append scene context as an observed finding unless the attempted means actually communicates it or the intended effect actually investigates or discloses it. Each supplied mutation lane is a bounded array of exact entries. Use an empty array when that lane does not change in an outcome; never add a duplicate or contradictory entry. Supplied entries may only name IDs copied exactly from PRESENT ACTORS and the enumerated schema, add or retire their exact goals or obligations, change their conditions or relationships, move only the acting actor along an existing route, advance or reduce existing clocks by a positive amount, or change existing institution posture. An actor_commitments entry records a present actor voluntarily adopting or retiring a bounded goal or obligation as an outcome; it does not make that actor a puppet, transfer authority, or guarantee unrelated future conduct. Strong and ordinary success share one visible stake, so give them identical commitment changes; the runtime binds each exact commitment into that stake. Use clock_advances when an outcome moves a pressure toward its consequence. Use clock_reductions when repair, relief, delay, or obstruction removes established progress. Never name the same clock in both arrays for one outcome. Existing informational outcomes may copy an exact statement from AVAILABLE INFORMATION FACTS through actor_knowledge_additions. A direct observation, measurement, inspection, or test may instead state one new bounded result through actor_observations. A subject receiving, recognizing, learning, remembering, or becoming able to act on information is a canonical knowledge transition and must have an exact actor_knowledge_additions entry for that exact present recipient. Never promise remote, institutional, population, place, office, or absent-actor receipt in a stake when no exact recipient knowledge lane exists; posture, narration, speech, and sender observation are not substitutes. Choose the fact that most directly answers the intended effect, preferring a relevant branch_local or provisional_local fact over generic canon background. A location-discoverable fact may be added only to the acting actor. A fact already known by the acting actor may instead be communicated to another present actor. Each actor_knowledge_additions or actor_observations entry contains the player-readable statement, never a fact ID, key, or label. An actor_observations statement is itself the canonical branch-local proposition committed on that outcome: state what is actually true. Do not say that the actor determines or establishes whether something is true, do not repeat the intended question, and do not leave 'if one exists' or another unresolved placeholder. A concrete negative result is valid. If canon is silent about harmless local texture needed to answer a direct inspection, improvise the smallest reversible detail consistent with the supplied location and evidence and preview it exactly; material geography, mechanics, institutions, or extraordinary capabilities remain outside this lane. actor_observations may target only the acting actor and must state only what the exact attempted means could establish at the current location; never use it for remote events, hidden motives, unsupported identities, or conclusions beyond the effect ceiling. Strong and ordinary success share one visible stake, so give them identical knowledge additions and observations. The runtime binds each exact finding into the player-visible stake; do not spend prose repeating it solely for formatting. If no supplied fact supports an intended disclosure, leave actor_knowledge_additions empty. If an intended local investigation can directly establish a bounded result, use actor_observations; otherwise make the limitation explicit in the stakes or mark the attempt inadmissible. Never invent remote events, hidden actors, unsupported proper nouns, or conclusions beyond the effect ceiling. Keep an effect empty only when the outcome truly has no canonical state change.\nMUTATION SCOPE:\n{}\nCAMPAIGN CONTRACT:\n{}\nAGGREGATE CONTENT BOUNDARIES:\n{}\nAGENCY BOUNDARY:\n{}\nLEGACY HOST ACTOR ID (not an authority):\n{}\nINTENT:\n{}\nACTOR:\n{}\nACCEPTED EXTRAORDINARY PERMISSIONS:\n{}\nLOCATION:\n{}\nPRESENT ACTORS:\n{}\nVISIBLE INSTITUTIONS:\n{}\nAVAILABLE INFORMATION FACTS:\n{}\nALLOWED REFERENCES:\n{}", - serde_json::to_string(&schema)?, - serde_json::to_string(&mutation_scope)?, - serde_json::to_string(&campaign_contract)?, - serde_json::to_string(aggregate_boundaries)?, - agency_guidance, - campaign.player_actor_id, - serde_json::to_string(&intent)?, - serde_json::to_string(actor)?, - serde_json::to_string(extraordinary_permissions)?, - serde_json::to_string(location)?, - serde_json::to_string(&present_actors)?, - serde_json::to_string(&visible_institutions)?, - serde_json::to_string(&information_facts)?, - serde_json::to_string(&allowed_references)? - ); - let snapshot_binding = format!("campaign:{}:revision:{}", campaign.id, campaign.revision); - let basis_digest = - assessment_basis_digest(&self.verifier_model_id, &self.model_id, &base_prompt); - if let Some(store) = store - && let Some((_, cached)) = store.load::( - ASSESSMENT_PROPOSAL_CACHE_KIND, - &basis_digest, - )? - { - if cached.schema != ASSESSMENT_PROPOSAL_CACHE_SCHEMA - || cached.basis_digest != basis_digest - { - return Err(anyhow!("assessment proposal cache identity mismatch")); - } - let proposal = validate_and_bind_proposal( - cached.proposal.clone(), - campaign, - actor, - &allowed_references, - &mutation_scope, - )?; - let assessment = build_assessment(campaign, intent, proposal.clone())?; - let receipt = cache_hit_receipt( - &cached, - &proposal, - &snapshot_binding, - &base_prompt, - &campaign.branch_origin.evidence_receipt_ids, - )?; - return Ok((assessment, receipt)); - } - let mut correction = String::new(); - let mut attempts = 0_u8; - let (proposal, out, effect_verifier_receipt) = loop { - attempts += 1; - let mut out = run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "action_assessment".into(), - model: self.model_id.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(2_800), - }, - ) - .await?; - let candidate = (|| -> Result { - let proposal = decode_assessment_proposal( - out.structured - .clone() - .ok_or_else(|| anyhow!("assessor returned no typed proposal"))?, - )?; - validate_and_bind_proposal( - proposal, - campaign, - actor, - &allowed_references, - &mutation_scope, - ) - })(); - match candidate { - Ok(proposal) => { - if !proposal.admissible { - if let Some(store) = store { - persist_private_stage_receipt(store, &out.receipt)?; - } - break (proposal, out, None); - } - let (verification, verifier_receipt) = verify_assessment_effects( - self.model.as_ref(), - &self.verifier_model_id, - campaign, - &intent, - &proposal, - &snapshot_binding, - attempts, - ) - .await?; - if matches!(verification.result, AssessmentEffectMatchResult::Mismatch) { - out.receipt.validation_result = "semantic_invalid".into(); - out.receipt.local_validation_error = verification - .repair_guidance - .as_deref() - .map(|guidance| guidance.chars().take(1_000).collect()); - } - if let Some(store) = store { - persist_private_stage_receipt(store, &out.receipt)?; - persist_private_stage_receipt(store, &verifier_receipt)?; - } - match verification.result { - AssessmentEffectMatchResult::Match => { - validate_effect_verification(&verification)?; - break (proposal, out, Some(verifier_receipt)); - } - AssessmentEffectMatchResult::Mismatch if attempts == 1 => { - validate_effect_verification(&verification)?; - let rejected = serde_json::to_string(&proposal)?; - let guidance = verification - .repair_guidance - .as_deref() - .expect("validated mismatch requires repair guidance"); - correction = format!( - "\n\nSEMANTIC EFFECT VERIFIER REJECTED THE PREVIOUS ASSESSMENT.\nREPAIR GUIDANCE: {guidance}\nPREVIOUS ASSESSMENT:\n{rejected}\nReturn one corrected complete assessment against the same snapshot. Preserve the exact means, intended effect, admissibility, and all causally faithful stakes and mutations. Remove or align the rejected mutation; do not replace it with another merely available fact or unrelated side effect." - ); - } - AssessmentEffectMatchResult::Mismatch => { - validate_effect_verification(&verification)?; - return Err(anyhow!( - "assessment failed semantic effect verification after one correction: {}", - verification - .repair_guidance - .as_deref() - .unwrap_or("effect mismatch") - )); - } - } - } - Err(error) if attempts == 1 => { - out.receipt.validation_result = "semantic_invalid".into(); - out.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - if let Some(store) = store { - persist_private_stage_receipt(store, &out.receipt)?; - } - let rejected = out - .structured - .as_ref() - .and_then(|value| serde_json::to_string(value).ok()) - .unwrap_or_else(|| "unavailable".into()); - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS ASSESSMENT: {error}\nPREVIOUS ASSESSMENT:\n{rejected}\nReturn a corrected complete assessment against the same snapshot. Copy every modifier reference from ALLOWED REFERENCES exactly; omit a modifier rather than paraphrasing or inventing its reference. Copy every actor and destination ID exactly from the supplied state. Every knowledge addition must copy one exact statement from AVAILABLE INFORMATION FACTS and obey its access mode; strong and ordinary success must use identical knowledge additions. Otherwise leave the corresponding mutation array empty." - ); - } - Err(error) => { - out.receipt.validation_result = "semantic_invalid".into(); - out.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - if let Some(store) = store { - persist_private_stage_receipt(store, &out.receipt)?; - } - return Err(anyhow!( - "assessor failed local validation after one correction: {error}" - )); - } - } - }; - let mut selected_proposal = proposal; - let mut selected_receipt = out.receipt; - if let Some(store) = store { - let entry = AssessmentProposalCacheEntry { - schema: ASSESSMENT_PROPOSAL_CACHE_SCHEMA.into(), - basis_digest: basis_digest.clone(), - proposal: selected_proposal.clone(), - source_provider: selected_receipt.provider.clone(), - source_model: selected_receipt.model.clone(), - source_scope_receipt_hash: source_scope_receipt_hash.clone(), - source_receipt_hash: selected_receipt.receipt_hash.clone(), - source_effect_verifier_receipt_hash: effect_verifier_receipt - .map(|receipt| receipt.receipt_hash), - created_at: Utc::now(), - }; - if let Err(insert_error) = store.insert( - ASSESSMENT_PROPOSAL_CACHE_KIND, - ASSESSMENT_PROPOSAL_CACHE_SCHEMA, - &basis_digest, - &entry, - ) { - let (_, winner) = store - .load::( - ASSESSMENT_PROPOSAL_CACHE_KIND, - &basis_digest, - )? - .ok_or_else(|| { - anyhow!( - "assessment proposal cache insert failed without an existing winner: {insert_error}" - ) - })?; - if winner.schema != ASSESSMENT_PROPOSAL_CACHE_SCHEMA - || winner.basis_digest != basis_digest - { - return Err(anyhow!( - "assessment proposal cache winner identity mismatch" - )); - } - selected_proposal = validate_and_bind_proposal( - winner.proposal.clone(), - campaign, - actor, - &allowed_references, - &mutation_scope, - )?; - selected_receipt = cache_hit_receipt( - &winner, - &selected_proposal, - &snapshot_binding, - &base_prompt, - &campaign.branch_origin.evidence_receipt_ids, - )?; - } - } - let assessment = build_assessment(campaign, intent, selected_proposal)?; - Ok((assessment, selected_receipt)) - } - - async fn select_mutation_scope( - &self, - store: Option<&CampaignStore>, - campaign: &Campaign, - intent: &ActionIntent, - actor: &crate::domain::ActorState, - extraordinary_permissions: &[ExtraordinaryPermission], - campaign_contract: Option<&CampaignContract>, - aggregate_boundaries: &[AggregatedBoundary], - ) -> Result<(AssessmentMutationScope, ModelStageReceipt)> { - let available_lanes = available_mutation_lanes(campaign, actor); - let mut schema = serde_json::to_value(schema_for!(AssessmentMutationScope))?; - constrain_mutation_scope_schema(&mut schema, &available_lanes)?; - let authority = assessment_admission_authority(campaign, actor); - let scope_prompt = format!( - "{ASSESSMENT_SCOPE_INSTRUCTIONS}\nOUTPUT JSON SCHEMA (follow exactly):\n{}\nEXACT ATTEMPT:\n{}\nEXACT CURRENT AUTHORITY:\n{}\nACCEPTED EXTRAORDINARY PERMISSIONS:\n{}\nCAMPAIGN CONTRACT:\n{}\nAGGREGATE CONTENT BOUNDARIES:\n{}\nSTRUCTURALLY AVAILABLE LANES:\n{}", - serde_json::to_string(&schema)?, - serde_json::to_string(intent)?, - serde_json::to_string(&authority)?, - serde_json::to_string(extraordinary_permissions)?, - serde_json::to_string(&campaign_contract)?, - serde_json::to_string(aggregate_boundaries)?, - serde_json::to_string(&available_lanes)?, - ); - let basis_digest = format!( - "sha256:{:x}", - Sha256::digest( - format!( - "{}|assessment_mutation_scope|{}|{}", - ASSESSMENT_SEMANTICS_VERSION, self.verifier_model_id, scope_prompt - ) - .as_bytes() - ) - ); - if let Some(store) = store - && let Some((_, cached)) = store.load::( - ASSESSMENT_SCOPE_CACHE_KIND, - &basis_digest, - )? - { - if cached.schema != ASSESSMENT_SCOPE_CACHE_SCHEMA || cached.basis_digest != basis_digest - { - return Err(anyhow!("assessment mutation scope cache identity mismatch")); - } - validate_mutation_scope(&cached.scope, &available_lanes)?; - let receipt = scope_cache_hit_receipt( - &cached, - &snapshot_binding_for_scope(campaign, &basis_digest), - &scope_prompt, - )?; - return Ok((cached.scope, receipt)); - } - let snapshot_binding = snapshot_binding_for_scope(campaign, &basis_digest); - let mut correction = String::new(); - let mut attempt = 0_u8; - let (scope, out) = loop { - attempt += 1; - let mut out = run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "assessment_mutation_scope".into(), - model: self.verifier_model_id.clone(), - snapshot_binding: snapshot_binding.clone(), - lived_stream: format!("{scope_prompt}{correction}"), - output_schema: Some(schema.clone()), - source_receipt_ids: Vec::new(), - temperature: Some(0.0), - max_output_tokens: Some(900), - }, - ) - .await?; - let candidate = (|| -> Result { - let scope = serde_json::from_value(out.structured.clone().ok_or_else(|| { - anyhow!("assessment mutation scope returned no typed output") - })?)?; - validate_mutation_scope(&scope, &available_lanes)?; - Ok(scope) - })(); - match candidate { - Ok(scope) => break (scope, out), - Err(error) if attempt == 1 => { - out.receipt.validation_result = "semantic_invalid".into(); - out.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - if let Some(store) = store { - persist_private_stage_receipt(store, &out.receipt)?; - } - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS ADMISSION SCOPE: {error}\nReturn one corrected complete object against the same snapshot. An assessable scope has no denial. A denied scope has a denial, one to four bargains, and no lanes." - ); - } - Err(error) => { - out.receipt.validation_result = "semantic_invalid".into(); - out.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - if let Some(store) = store { - persist_private_stage_receipt(store, &out.receipt)?; - } - return Err(anyhow!( - "assessment mutation scope failed local validation after one correction: {error}" - )); - } - } - }; - if let Some(store) = store { - persist_private_stage_receipt(store, &out.receipt)?; - let entry = AssessmentMutationScopeCacheEntry { - schema: ASSESSMENT_SCOPE_CACHE_SCHEMA.into(), - basis_digest: basis_digest.clone(), - scope: scope.clone(), - source_provider: out.receipt.provider.clone(), - source_model: out.receipt.model.clone(), - source_receipt_hash: out.receipt.receipt_hash.clone(), - created_at: Utc::now(), - }; - if let Err(insert_error) = store.insert( - ASSESSMENT_SCOPE_CACHE_KIND, - ASSESSMENT_SCOPE_CACHE_SCHEMA, - &basis_digest, - &entry, - ) { - let (_, winner) = store - .load::( - ASSESSMENT_SCOPE_CACHE_KIND, - &basis_digest, - )? - .ok_or_else(|| { - anyhow!( - "assessment mutation scope cache insert failed without an existing winner: {insert_error}" - ) - })?; - if winner.schema != ASSESSMENT_SCOPE_CACHE_SCHEMA - || winner.basis_digest != basis_digest - { - return Err(anyhow!( - "assessment mutation scope cache winner identity mismatch" - )); - } - validate_mutation_scope(&winner.scope, &available_lanes)?; - let receipt = scope_cache_hit_receipt(&winner, &snapshot_binding, &scope_prompt)?; - return Ok((winner.scope, receipt)); - } - } - Ok((scope, out.receipt)) - } -} - -fn decode_assessment_proposal(value: serde_json::Value) -> Result { - let mut wrapper = value - .as_object() - .cloned() - .ok_or_else(|| anyhow!("assessor output is not an object"))?; - if wrapper.len() != 1 || !wrapper.contains_key("proposal") { - return Err(anyhow!( - "assessor output must contain exactly one admission-bound proposal" - )); - } - let mut value = wrapper - .remove("proposal") - .ok_or_else(|| anyhow!("assessor output omitted proposal"))?; - let proposal = value - .as_object_mut() - .ok_or_else(|| anyhow!("assessor proposal is not an object"))?; - for field in [ - "strong_effect", - "success_effect", - "mixed_effect", - "failure_effect", - ] { - let effect = proposal - .get(field) - .ok_or_else(|| anyhow!("assessor output omitted {field}"))?; - proposal.insert( - field.into(), - serde_json::to_value(decode_effect_entries(effect)?)?, - ); - } - serde_json::from_value(value).map_err(Into::into) -} - -fn decode_effect_entries(value: &serde_json::Value) -> Result { - let fields = value - .as_object() - .ok_or_else(|| anyhow!("assessor effect is not an object"))?; - let allowed_fields = BTreeSet::from([ - "actor_conditions", - "actor_commitments", - "actor_knowledge_additions", - "actor_observations", - "actor_relationship_updates", - "actor_moves", - "clock_advances", - "clock_reductions", - "institution_postures", - ]); - if let Some(field) = fields - .keys() - .find(|field| !allowed_fields.contains(field.as_str())) - { - return Err(anyhow!( - "assessor effect contains unknown mutation lane {field}" - )); - } - - let mut effect = WorldEffectDelta::default(); - for entry in decode_mutation_entries::(fields, "actor_conditions")? { - let delta = effect - .actor_conditions - .entry(entry.actor_id.clone()) - .or_default(); - let (selected, opposite) = match entry.operation { - ConditionMutationOperation::Add => (&mut delta.add, &delta.remove), - ConditionMutationOperation::Remove => (&mut delta.remove, &delta.add), - }; - if opposite.contains(&entry.condition) { - return Err(anyhow!( - "condition mutation both adds and removes {:?} for {}", - entry.condition, - entry.actor_id - )); - } - if !selected.insert(entry.condition.clone()) { - return Err(anyhow!( - "duplicate condition mutation {:?} for {}", - entry.condition, - entry.actor_id - )); - } - } - for entry in decode_mutation_entries::(fields, "actor_commitments")? { - let delta = effect - .actor_commitments - .entry(entry.actor_id.clone()) - .or_default(); - let (selected, opposite) = match entry.operation { - ActorCommitmentMutationOperation::AddGoal => { - (&mut delta.goals_add, &delta.goals_retire) - } - ActorCommitmentMutationOperation::RetireGoal => { - (&mut delta.goals_retire, &delta.goals_add) - } - ActorCommitmentMutationOperation::AddObligation => { - (&mut delta.obligations_add, &delta.obligations_retire) - } - ActorCommitmentMutationOperation::RetireObligation => { - (&mut delta.obligations_retire, &delta.obligations_add) - } - }; - if opposite.contains(&entry.description) { - return Err(anyhow!( - "commitment mutation both adds and retires {:?} for {}", - entry.description, - entry.actor_id - )); - } - if !selected.insert(entry.description.clone()) { - return Err(anyhow!( - "duplicate commitment mutation {:?} for {}", - entry.description, - entry.actor_id - )); - } - } - for entry in - decode_mutation_entries::(fields, "actor_knowledge_additions")? - { - if !effect - .actor_knowledge_additions - .entry(entry.actor_id.clone()) - .or_default() - .insert(entry.statement.clone()) - { - return Err(anyhow!( - "duplicate knowledge mutation {:?} for {}", - entry.statement, - entry.actor_id - )); - } - } - for entry in decode_mutation_entries::(fields, "actor_observations")? - { - if !effect - .actor_observations - .entry(entry.actor_id.clone()) - .or_default() - .insert(entry.statement.clone()) - { - return Err(anyhow!( - "duplicate observation mutation {:?} for {}", - entry.statement, - entry.actor_id - )); - } - } - for entry in - decode_mutation_entries::(fields, "actor_relationship_updates")? - { - if effect - .actor_relationship_updates - .entry(entry.actor_id.clone()) - .or_default() - .insert(entry.target_id.clone(), entry.relationship) - .is_some() - { - return Err(anyhow!( - "duplicate relationship mutation from {} to {}", - entry.actor_id, - entry.target_id - )); - } - } - for entry in decode_mutation_entries::(fields, "actor_moves")? { - if effect - .actor_moves - .insert(entry.actor_id.clone(), entry.destination_id) - .is_some() - { - return Err(anyhow!( - "duplicate movement mutation for {}", - entry.actor_id - )); - } - } - for entry in decode_mutation_entries::(fields, "clock_advances")? { - if effect - .clock_advances - .insert(entry.clock_id.clone(), entry.amount) - .is_some() - { - return Err(anyhow!("duplicate clock advance for {}", entry.clock_id)); - } - } - for entry in decode_mutation_entries::(fields, "clock_reductions")? { - if effect - .clock_reductions - .insert(entry.clock_id.clone(), entry.amount) - .is_some() - { - return Err(anyhow!("duplicate clock reduction for {}", entry.clock_id)); - } - } - for entry in - decode_mutation_entries::(fields, "institution_postures")? - { - if effect - .institution_postures - .insert(entry.institution_id.clone(), entry.posture) - .is_some() - { - return Err(anyhow!( - "duplicate institution posture mutation for {}", - entry.institution_id - )); - } - } - Ok(effect) -} - -fn decode_mutation_entries( - fields: &serde_json::Map, - lane: &str, -) -> Result> -where - T: serde::de::DeserializeOwned, -{ - match fields.get(lane) { - None | Some(serde_json::Value::Null) => Ok(Vec::new()), - Some(value @ serde_json::Value::Array(_)) => { - serde_json::from_value(value.clone()).map_err(Into::into) - } - Some(_) => Err(anyhow!("assessor mutation lane {lane} is not an array")), - } -} - -fn validate_and_bind_proposal( - mut proposal: AssessmentProposal, - campaign: &Campaign, - actor: &crate::domain::ActorState, - allowed_references: &BTreeSet, - mutation_scope: &AssessmentMutationScope, -) -> Result { - bind_visible_effects(&mut proposal)?; - validate_proposal(&proposal, allowed_references)?; - for (effect, stake) in [ - (&proposal.strong_effect, &proposal.success_stake), - (&proposal.success_effect, &proposal.success_stake), - (&proposal.mixed_effect, &proposal.mixed_stake), - (&proposal.failure_effect, &proposal.failure_stake), - ] { - validate_effect(campaign, actor, effect, stake)?; - } - validate_required_success_lanes(&proposal, mutation_scope)?; - Ok(proposal) -} - -fn build_assessment( - campaign: &Campaign, - intent: ActionIntent, - proposal: AssessmentProposal, -) -> Result { - let modifier_total = - crate::d20::capped_modifier(proposal.modifiers.iter().map(|modifier| modifier.value)); - let mut assessment = ActionAssessment { - schema: "ghostlight.player_action_assessment.v1".into(), - campaign_id: campaign.id, - revision: campaign.revision, - intent, - admissible: proposal.admissible, - missing_permission: proposal.missing_permission, - dc: proposal.dc, - modifiers: proposal.modifiers, - modifier_total, - effect_ceiling: proposal.effect_ceiling, - success_stake: proposal.success_stake, - mixed_stake: proposal.mixed_stake, - failure_stake: proposal.failure_stake, - strong_effect: proposal.strong_effect, - success_effect: proposal.success_effect, - mixed_effect: proposal.mixed_effect, - failure_effect: proposal.failure_effect, - bargains: proposal.bargains, - expires_at: Utc::now() + Duration::minutes(10), - digest: String::new(), - }; - assessment.digest = assessment_digest(&assessment)?; - Ok(assessment) -} - -fn assessment_basis_digest(verifier_model_id: &str, model_id: &str, base_prompt: &str) -> String { - format!( - "sha256:{:x}", - Sha256::digest( - format!( - "{ASSESSMENT_SEMANTICS_VERSION}|{verifier_model_id}|{ASSESSMENT_EFFECT_VERIFIER_INSTRUCTIONS}|{model_id}|{base_prompt}" - ) - .as_bytes() - ) - ) -} - -async fn verify_assessment_effects( - model: &dyn ModelPort, - verifier_model_id: &str, - campaign: &Campaign, - intent: &ActionIntent, - proposal: &AssessmentProposal, - snapshot_binding: &str, - assessment_attempt: u8, -) -> Result<(AssessmentEffectVerification, ModelStageReceipt)> { - let referenced_state = assessment_effect_reference_context(campaign, proposal); - let context = serde_json::json!({ - "means":intent.description, - "intended_effect":intent.intended_effect, - "effect_ceiling":proposal.effect_ceiling, - "success_stake":proposal.success_stake, - "mixed_stake":proposal.mixed_stake, - "failure_stake":proposal.failure_stake, - "typed_effects":{ - "strong_success":proposal.strong_effect, - "success":proposal.success_effect, - "mixed":proposal.mixed_effect, - "failure":proposal.failure_effect, - }, - "referenced_state":referenced_state, - }); - let request = ModelStageRequest { - stage: "assessment_effect_verifier".into(), - model: verifier_model_id.into(), - snapshot_binding: format!( - "{}:assessment-attempt:{}:assessment-effect:{}", - snapshot_binding, - assessment_attempt, - format!("{:x}", Sha256::digest(serde_json::to_vec(&context)?)) - ), - lived_stream: format!( - "{ASSESSMENT_EFFECT_VERIFIER_INSTRUCTIONS}\n\nCANDIDATE:\n{}", - serde_json::to_string(&context)? - ), - output_schema: Some(serde_json::to_value(schema_for!( - AssessmentEffectVerification - ))?), - source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), - temperature: Some(0.0), - max_output_tokens: Some(192), - }; - let output = run_validated_stage(model, &request).await?; - let verification: AssessmentEffectVerification = serde_json::from_value( - output - .structured - .clone() - .ok_or_else(|| anyhow!("assessment effect verifier produced no typed verdict"))?, - )?; - validate_effect_verification(&verification)?; - let mut receipt = output.receipt; - if matches!(verification.result, AssessmentEffectMatchResult::Mismatch) { - receipt.validation_result = "semantic_invalid".into(); - receipt.local_validation_error = verification - .repair_guidance - .as_deref() - .map(|guidance| guidance.chars().take(1_000).collect()); - } - Ok((verification, receipt)) -} - -fn assessment_effect_reference_context( - campaign: &Campaign, - proposal: &AssessmentProposal, -) -> serde_json::Value { - let mut actor_ids = BTreeSet::new(); - let mut institution_ids = BTreeSet::new(); - let mut clock_ids = BTreeSet::new(); - let mut location_ids = BTreeSet::new(); - for effect in [ - &proposal.strong_effect, - &proposal.success_effect, - &proposal.mixed_effect, - &proposal.failure_effect, - ] { - actor_ids.extend(effect.actor_conditions.keys().cloned()); - actor_ids.extend(effect.actor_commitments.keys().cloned()); - actor_ids.extend(effect.actor_knowledge_additions.keys().cloned()); - actor_ids.extend(effect.actor_observations.keys().cloned()); - actor_ids.extend(effect.actor_relationship_updates.keys().cloned()); - actor_ids.extend(effect.actor_moves.keys().cloned()); - for target_id in effect - .actor_relationship_updates - .values() - .flat_map(|relationships| relationships.keys()) - { - if campaign.actors.contains_key(target_id) { - actor_ids.insert(target_id.clone()); - } else if campaign.institutions.contains_key(target_id) { - institution_ids.insert(target_id.clone()); - } - } - location_ids.extend(effect.actor_moves.values().cloned()); - clock_ids.extend(effect.clock_advances.keys().cloned()); - clock_ids.extend(effect.clock_reductions.keys().cloned()); - institution_ids.extend(effect.institution_postures.keys().cloned()); - } - let actors = actor_ids - .into_iter() - .filter_map(|id| { - campaign.actors.get(&id).map(|actor| { - ( - id, - serde_json::json!({ - "name":&actor.name, - "goals":&actor.goals, - "obligations":&actor.obligations, - "relationships":&actor.relationships, - }), - ) - }) - }) - .collect::>(); - let institutions = institution_ids - .into_iter() - .filter_map(|id| { - campaign - .institutions - .get(&id) - .map(|institution| (id, institution.name.clone())) - }) - .collect::>(); - let clocks = clock_ids - .into_iter() - .filter_map(|id| { - campaign - .clocks - .get(&id) - .map(|clock| (id, clock.label.clone())) - }) - .collect::>(); - let locations = location_ids - .into_iter() - .filter_map(|id| { - campaign - .locations - .get(&id) - .map(|location| (id, location.name.clone())) - }) - .collect::>(); - serde_json::json!({ - "actors":actors, - "institutions":institutions, - "clocks":clocks, - "locations":locations, - }) -} - -fn validate_effect_verification(verification: &AssessmentEffectVerification) -> Result<()> { - match ( - &verification.result, - &verification.mismatch_kind, - &verification.repair_guidance, - ) { - (AssessmentEffectMatchResult::Match, None, None) => Ok(()), - (AssessmentEffectMatchResult::Mismatch, Some(_), Some(guidance)) - if !guidance.trim().is_empty() && guidance.chars().count() <= 240 => - { - Ok(()) - } - _ => Err(anyhow!( - "assessment effect verifier returned an incoherent verdict" - )), - } -} - -fn persist_private_stage_receipt(store: &CampaignStore, receipt: &ModelStageReceipt) -> Result<()> { - match store.insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - receipt, - ) { - Ok(_) => Ok(()), - Err(_error) - if store - .load::("persona_stage_receipt.v1", receipt.storage_key())? - .is_some() => - { - Ok(()) - } - Err(error) => Err(error), - } -} - -fn snapshot_binding_for_scope(campaign: &Campaign, basis_digest: &str) -> String { - format!( - "campaign:{}:revision:{}:assessment-mutation-scope:{}", - campaign.id, campaign.revision, basis_digest - ) -} - -fn scope_cache_hit_receipt( - cached: &AssessmentMutationScopeCacheEntry, - snapshot_binding: &str, - scope_prompt: &str, -) -> Result { - let output = serde_json::to_string(&cached.scope)?; - let output_hash = format!("sha256:{:x}", Sha256::digest(output.as_bytes())); - let request_hash = format!( - "sha256:{:x}", - Sha256::digest( - format!( - "{}|{}|{}|{}", - cached.basis_digest, snapshot_binding, cached.source_model, scope_prompt - ) - .as_bytes() - ) - ); - let receipt_hash = format!( - "sha256:{:x}", - Sha256::digest( - format!( - "{}|{}|assessment_mutation_scope|{}|{}|{}|{}", - cached.source_provider, - cached.source_model, - snapshot_binding, - request_hash, - output_hash, - cached.source_receipt_hash - ) - .as_bytes() - ) - ); - Ok(ModelStageReceipt { - schema: "ghostlight.persona_stage_receipt.v1".into(), - receipt_hash, - provider: cached.source_provider.clone(), - model: cached.source_model.clone(), - stage: "assessment_mutation_scope".into(), - snapshot_binding: snapshot_binding.into(), - request_hash, - output_hash, - source_receipt_ids: Vec::new(), - latency_ms: 0, - validation_result: "valid_cache_hit".into(), - local_validation_error: None, - input_chars: scope_prompt.chars().count(), - output_chars: output.chars().count(), - provider_attempts: vec![ModelProviderAttemptReceipt { - provider_request_id: None, - system_fingerprint: None, - finish_reason: Some("cache_hit".into()), - latency_ms: 0, - token_usage: Some(ModelTokenUsage::default()), - transport_features: vec![ - "cultcache.output-cache".into(), - format!("source-receipt:{}", cached.source_receipt_hash), - ], - local_validation_result: "valid_cache_hit".into(), - local_validation_error: None, - }], - }) -} - -fn cache_hit_receipt( - cached: &AssessmentProposalCacheEntry, - proposal: &AssessmentProposal, - snapshot_binding: &str, - base_prompt: &str, - source_receipt_ids: &[String], -) -> Result { - let output = serde_json::to_string(proposal)?; - let output_hash = format!("sha256:{:x}", Sha256::digest(output.as_bytes())); - let request_hash = format!( - "sha256:{:x}", - Sha256::digest( - format!( - "{}|{}|{}|{}", - cached.basis_digest, - snapshot_binding, - cached.source_model, - source_receipt_ids.join("|") - ) - .as_bytes() - ) - ); - let receipt_hash = format!( - "sha256:{:x}", - Sha256::digest( - format!( - "{}|{}|action_assessment|{}|{}|{}|{}|{}", - cached.source_provider, - cached.source_model, - snapshot_binding, - request_hash, - output_hash, - cached.source_scope_receipt_hash, - cached.source_receipt_hash - ) - .as_bytes() - ) - ); - Ok(ModelStageReceipt { - schema: "ghostlight.persona_stage_receipt.v1".into(), - receipt_hash, - provider: cached.source_provider.clone(), - model: cached.source_model.clone(), - stage: "action_assessment".into(), - snapshot_binding: snapshot_binding.into(), - request_hash, - output_hash, - source_receipt_ids: source_receipt_ids.to_vec(), - latency_ms: 0, - validation_result: "valid_cache_hit".into(), - local_validation_error: None, - input_chars: base_prompt.chars().count(), - output_chars: output.chars().count(), - provider_attempts: vec![ModelProviderAttemptReceipt { - provider_request_id: None, - system_fingerprint: None, - finish_reason: Some("cache_hit".into()), - latency_ms: 0, - token_usage: Some(ModelTokenUsage::default()), - transport_features: { - let mut features = vec![ - "cultcache.output-cache".into(), - format!("source-mutation-scope:{}", cached.source_scope_receipt_hash), - format!("source-receipt:{}", cached.source_receipt_hash), - ]; - if let Some(hash) = &cached.source_effect_verifier_receipt_hash { - features.push(format!("source-effect-verifier:{hash}")); - } - features - }, - local_validation_result: "valid_cache_hit".into(), - local_validation_error: None, - }], - }) -} - -fn constrain_assessment_schema( - schema: &mut serde_json::Value, - allowed_references: &BTreeSet, - campaign: &Campaign, - acting_actor: &crate::domain::ActorState, -) -> Result<()> { - let properties = schema - .pointer_mut("/properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("assessment schema has no properties"))?; - properties.insert( - "dc".into(), - serde_json::json!({ - "type":"integer", - "enum":[5,10,15,20,25,30] - }), - ); - let modifier_properties = schema - .pointer_mut("/$defs/ContextModifier/properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("assessment schema has no context modifier properties"))?; - modifier_properties.insert( - "value".into(), - serde_json::json!({ - "type":"integer", - "minimum":-10, - "maximum":10 - }), - ); - modifier_properties.insert( - "references".into(), - serde_json::json!({ - "type":"array", - "items":{ - "type":"string", - "enum":allowed_references.iter().collect::>() - } - }), - ); - constrain_effect_schema(schema, campaign, acting_actor)?; - Ok(()) -} - -fn constrain_effect_schema( - schema: &mut serde_json::Value, - campaign: &Campaign, - acting_actor: &crate::domain::ActorState, -) -> Result<()> { - schema["$defs"]["WorldEffectDelta"]["additionalProperties"] = serde_json::json!(false); - let present_actor_ids = campaign - .actors - .values() - .filter(|candidate| candidate.location_id == acting_actor.location_id) - .map(|candidate| candidate.id.clone()) - .collect::>(); - let institution_ids = campaign - .institutions - .keys() - .cloned() - .collect::>(); - let relationship_target_ids = present_actor_ids - .iter() - .chain(institution_ids.iter()) - .cloned() - .collect::>(); - let destination_ids = campaign - .locations - .get(&acting_actor.location_id) - .ok_or_else(|| anyhow!("acting actor location vanished while binding effect schema"))? - .routes - .values() - .map(|route| route.destination_id.clone()) - .filter(|destination| campaign.locations.contains_key(destination)) - .collect::>(); - let clock_ids = campaign.clocks.keys().cloned().collect::>(); - for field in ["add", "remove"] { - schema["$defs"]["ConditionDelta"]["properties"][field]["items"] = - serde_json::json!({"type":"string","minLength":1}); - } - let effect_properties = schema - .pointer_mut("/$defs/WorldEffectDelta/properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("assessment schema has no world effect properties"))?; - - for field in [ - "actor_conditions", - "actor_commitments", - "actor_relationship_updates", - ] { - constrain_map_keys( - effect_properties - .get_mut(field) - .ok_or_else(|| anyhow!("assessment effect schema omitted {field}"))?, - &present_actor_ids, - )?; - } - let knowledge_available = constrain_knowledge_map( - effect_properties - .get_mut("actor_knowledge_additions") - .ok_or_else(|| anyhow!("assessment effect schema omitted actor_knowledge_additions"))?, - campaign, - acting_actor, - &present_actor_ids, - )?; - constrain_map_keys( - effect_properties - .get_mut("actor_observations") - .ok_or_else(|| anyhow!("assessment effect schema omitted actor_observations"))?, - &BTreeSet::from([acting_actor.id.clone()]), - )?; - effect_properties["actor_observations"]["additionalProperties"] = serde_json::json!({ - "type":"array", - "items":{"type":"string","minLength":1,"maxLength":500}, - "uniqueItems":true, - "minItems":1, - "maxItems":2 - }); - let relationship_targets = effect_properties - .get_mut("actor_relationship_updates") - .and_then(|value| value.get_mut("additionalProperties")) - .ok_or_else(|| anyhow!("assessment relationship schema has no target map"))?; - constrain_map_keys(relationship_targets, &relationship_target_ids)?; - relationship_targets["additionalProperties"] = - serde_json::json!({"type":"string","minLength":1}); - - let actor_moves = effect_properties - .get_mut("actor_moves") - .ok_or_else(|| anyhow!("assessment effect schema omitted actor_moves"))?; - constrain_map_keys(actor_moves, &BTreeSet::from([acting_actor.id.clone()]))?; - if destination_ids.is_empty() { - actor_moves["maxProperties"] = serde_json::json!(0); - } else { - actor_moves["additionalProperties"] = serde_json::json!({ - "type":"string", - "enum":destination_ids - }); - } - - let clock_advances = effect_properties - .get_mut("clock_advances") - .ok_or_else(|| anyhow!("assessment effect schema omitted clock_advances"))?; - constrain_map_keys(clock_advances, &clock_ids)?; - clock_advances["additionalProperties"] = - serde_json::json!({"type":"integer","minimum":1,"maximum":255}); - let clock_reductions = effect_properties - .get_mut("clock_reductions") - .ok_or_else(|| anyhow!("assessment effect schema omitted clock_reductions"))?; - constrain_map_keys(clock_reductions, &clock_ids)?; - clock_reductions["additionalProperties"] = - serde_json::json!({"type":"integer","minimum":1,"maximum":255}); - let institution_postures = effect_properties - .get_mut("institution_postures") - .ok_or_else(|| anyhow!("assessment effect schema omitted institution_postures"))?; - constrain_map_keys(institution_postures, &institution_ids)?; - institution_postures["additionalProperties"] = serde_json::json!({ - "type":"string", - "minLength":1, - "maxLength":MAX_POSTURE_CHARS - }); - let mut unavailable_lanes = Vec::new(); - if !knowledge_available { - unavailable_lanes.push("actor_knowledge_additions"); - } - if destination_ids.is_empty() { - unavailable_lanes.push("actor_moves"); - } - if clock_ids.is_empty() { - unavailable_lanes.extend(["clock_advances", "clock_reductions"]); - } - if institution_ids.is_empty() { - unavailable_lanes.push("institution_postures"); - } - for field in unavailable_lanes { - remove_effect_lane(schema, field)?; - } - Ok(()) -} - -fn project_effect_schema_to_mutation_entries( - schema: &mut serde_json::Value, - campaign: &Campaign, -) -> Result<()> { - let properties = schema - .pointer_mut("/$defs/WorldEffectDelta/properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("assessment schema has no world effect properties"))?; - - if let Some(map) = properties.get("actor_conditions").cloned() { - let actor_ids = constrained_map_keys(&map, "actor_conditions")?; - properties.insert( - "actor_conditions".into(), - mutation_entry_array( - serde_json::json!({ - "type":"object", - "properties":{ - "actor_id":typed_string_enum(&actor_ids), - "operation":{"type":"string","enum":["add","remove"]}, - "condition":{"type":"string","minLength":1} - }, - "required":["actor_id","operation","condition"], - "additionalProperties":false - }), - bounded_entry_count(actor_ids.len().saturating_mul(4)), - ), - ); - } - - if let Some(map) = properties.get("actor_commitments").cloned() { - let actor_ids = constrained_map_keys(&map, "actor_commitments")?; - let mut alternatives = Vec::new(); - for actor_id in &actor_ids { - let actor = campaign - .actors - .get(actor_id) - .ok_or_else(|| anyhow!("assessment commitment actor vanished"))?; - for operation in ["add_goal", "add_obligation"] { - alternatives.push(serde_json::json!({ - "type":"object", - "properties":{ - "actor_id":{"type":"string","enum":[actor_id]}, - "operation":{"type":"string","enum":[operation]}, - "description":{"type":"string","minLength":1,"maxLength":600} - }, - "required":["actor_id","operation","description"], - "additionalProperties":false - })); - } - if !actor.goals.is_empty() { - alternatives.push(serde_json::json!({ - "type":"object", - "properties":{ - "actor_id":{"type":"string","enum":[actor_id]}, - "operation":{"type":"string","enum":["retire_goal"]}, - "description":{"type":"string","enum":&actor.goals} - }, - "required":["actor_id","operation","description"], - "additionalProperties":false - })); - } - if !actor.obligations.is_empty() { - alternatives.push(serde_json::json!({ - "type":"object", - "properties":{ - "actor_id":{"type":"string","enum":[actor_id]}, - "operation":{"type":"string","enum":["retire_obligation"]}, - "description":{"type":"string","enum":&actor.obligations} - }, - "required":["actor_id","operation","description"], - "additionalProperties":false - })); - } - } - let items = if alternatives.len() == 1 { - alternatives.remove(0) - } else { - serde_json::json!({"anyOf":alternatives}) - }; - properties.insert( - "actor_commitments".into(), - mutation_entry_array( - items, - bounded_entry_count(actor_ids.len().saturating_mul(4)), - ), - ); - } - - if let Some(map) = properties.get("actor_knowledge_additions").cloned() { - let recipient_schemas = map - .get("properties") - .and_then(serde_json::Value::as_object) - .ok_or_else(|| anyhow!("assessment knowledge lane has no recipient properties"))?; - let mut alternatives = Vec::new(); - let mut maximum = 0_usize; - for (actor_id, statements) in recipient_schemas { - let statement_schema = statements - .get("items") - .cloned() - .ok_or_else(|| anyhow!("assessment knowledge recipient has no statement schema"))?; - maximum = maximum.saturating_add( - statements - .get("maxItems") - .and_then(serde_json::Value::as_u64) - .unwrap_or(1) as usize, - ); - alternatives.push(serde_json::json!({ - "type":"object", - "properties":{ - "actor_id":{"type":"string","enum":[actor_id]}, - "statement":statement_schema - }, - "required":["actor_id","statement"], - "additionalProperties":false - })); - } - if alternatives.is_empty() { - return Err(anyhow!( - "assessment knowledge lane survived without an authorized recipient" - )); - } - let items = if alternatives.len() == 1 { - alternatives.remove(0) - } else { - serde_json::json!({"anyOf":alternatives}) - }; - properties.insert( - "actor_knowledge_additions".into(), - mutation_entry_array(items, bounded_entry_count(maximum)), - ); - } - - if let Some(map) = properties.get("actor_relationship_updates").cloned() { - let actor_ids = constrained_map_keys(&map, "actor_relationship_updates")?; - let target_map = map - .get("additionalProperties") - .ok_or_else(|| anyhow!("assessment relationship lane has no target map"))?; - let target_ids = constrained_map_keys(target_map, "actor_relationship_updates targets")?; - properties.insert( - "actor_relationship_updates".into(), - mutation_entry_array( - serde_json::json!({ - "type":"object", - "properties":{ - "actor_id":typed_string_enum(&actor_ids), - "target_id":typed_string_enum(&target_ids), - "relationship":{"type":"string","minLength":1} - }, - "required":["actor_id","target_id","relationship"], - "additionalProperties":false - }), - bounded_entry_count(actor_ids.len().saturating_mul(target_ids.len())), - ), - ); - } - - if let Some(map) = properties.get("actor_observations").cloned() { - let actor_ids = constrained_map_keys(&map, "actor_observations")?; - properties.insert( - "actor_observations".into(), - mutation_entry_array( - serde_json::json!({ - "type":"object", - "properties":{ - "actor_id":typed_string_enum(&actor_ids), - "statement":{"type":"string","minLength":1,"maxLength":500} - }, - "required":["actor_id","statement"], - "additionalProperties":false - }), - 2, - ), - ); - } - - if let Some(map) = properties.get("actor_moves").cloned() { - let actor_ids = constrained_map_keys(&map, "actor_moves")?; - let destination_ids = constrained_value_enum(&map, "actor_moves destinations")?; - properties.insert( - "actor_moves".into(), - mutation_entry_array( - serde_json::json!({ - "type":"object", - "properties":{ - "actor_id":typed_string_enum(&actor_ids), - "destination_id":typed_string_enum(&destination_ids) - }, - "required":["actor_id","destination_id"], - "additionalProperties":false - }), - bounded_entry_count(actor_ids.len()), - ), - ); - } - - for field in ["clock_advances", "clock_reductions"] { - if let Some(map) = properties.get(field).cloned() { - let clock_ids = constrained_map_keys(&map, field)?; - properties.insert( - field.into(), - mutation_entry_array( - serde_json::json!({ - "type":"object", - "properties":{ - "clock_id":typed_string_enum(&clock_ids), - "amount":{"type":"integer","minimum":1,"maximum":255} - }, - "required":["clock_id","amount"], - "additionalProperties":false - }), - bounded_entry_count(clock_ids.len()), - ), - ); - } - } - - if let Some(map) = properties.get("institution_postures").cloned() { - let institution_ids = constrained_map_keys(&map, "institution_postures")?; - properties.insert( - "institution_postures".into(), - mutation_entry_array( - serde_json::json!({ - "type":"object", - "properties":{ - "institution_id":typed_string_enum(&institution_ids), - "posture":{"type":"string","minLength":1,"maxLength":MAX_POSTURE_CHARS} - }, - "required":["institution_id","posture"], - "additionalProperties":false - }), - bounded_entry_count(institution_ids.len()), - ), - ); - } - Ok(()) -} - -fn bounded_entry_count(available: usize) -> usize { - available.clamp(1, 16) -} - -fn mutation_entry_array(items: serde_json::Value, max_items: usize) -> serde_json::Value { - serde_json::json!({ - "type":"array", - "items":items, - "maxItems":max_items - }) -} - -fn constrained_map_keys(schema: &serde_json::Value, lane: &str) -> Result> { - schema - .pointer("/propertyNames/enum") - .and_then(serde_json::Value::as_array) - .ok_or_else(|| anyhow!("assessment {lane} lane has no authorized keys"))? - .iter() - .map(|value| { - value - .as_str() - .map(ToOwned::to_owned) - .ok_or_else(|| anyhow!("assessment {lane} lane has a non-string key")) - }) - .collect() -} - -fn constrained_value_enum(schema: &serde_json::Value, lane: &str) -> Result> { - schema - .pointer("/additionalProperties/enum") - .and_then(serde_json::Value::as_array) - .ok_or_else(|| anyhow!("assessment {lane} lane has no authorized values"))? - .iter() - .map(|value| { - value - .as_str() - .map(ToOwned::to_owned) - .ok_or_else(|| anyhow!("assessment {lane} lane has a non-string value")) - }) - .collect() -} - -fn typed_string_enum(values: &[String]) -> serde_json::Value { - serde_json::json!({"type":"string","enum":values}) -} - -fn assessment_admission_authority( - campaign: &Campaign, - acting_actor: &crate::domain::ActorState, -) -> serde_json::Value { - let location = campaign.locations.get(&acting_actor.location_id); - let routes = location - .into_iter() - .flat_map(|location| { - location.routes.iter().map(|(route_id, route)| { - serde_json::json!({ - "route_id":route_id, - "destination_id":route.destination_id, - "destination_name":campaign.locations.get(&route.destination_id).map(|value| value.name.as_str()), - "distance":route.distance, - "travel_minutes":route.travel_minutes, - }) - }) - }) - .collect::>(); - let present_actors = campaign - .actors - .values() - .filter(|candidate| candidate.location_id == acting_actor.location_id) - .map(|candidate| { - serde_json::json!({ - "id":candidate.id, - "name":candidate.name, - "conditions":candidate.conditions, - "relationship_to_actor":candidate.relationships.get(&acting_actor.id), - }) - }) - .collect::>(); - let institutions = campaign - .institutions - .values() - .map(|institution| { - let profile = campaign.agency_profiles.get(&institution.id); - serde_json::json!({ - "id":institution.id, - "name":institution.name, - "posture":institution.posture, - "location_ids":profile.map(|value| &value.location_ids), - "collective_authority_id":profile.and_then(|value| value.collective_authority_id.as_deref()), - "information_channels":profile.map(|value| &value.information_channels), - }) - }) - .collect::>(); - let clocks = campaign - .clocks - .values() - .map(|clock| { - serde_json::json!({ - "id":clock.id, - "label":clock.label, - "progress":clock.progress, - "threshold":clock.threshold, - "consequence":clock.consequence, - }) - }) - .collect::>(); - serde_json::json!({ - "actor":{ - "id":acting_actor.id, - "location_id":acting_actor.location_id, - "capabilities":acting_actor.capabilities, - "knowledge":acting_actor.knowledge, - "equipment":acting_actor.equipment, - "conditions":acting_actor.conditions, - "obligations":acting_actor.obligations, - "relationships":acting_actor.relationships, - }, - "location":location.map(|value| serde_json::json!({ - "id":value.id, - "name":value.name, - "persistent_features":value.persistent_features, - })), - "routes":routes, - "present_actors":present_actors, - "institutions":institutions, - "clocks":clocks, - "accessible_information_facts":available_information_facts(campaign, acting_actor), - }) -} - -fn denied_assessment_proposal(scope: &AssessmentMutationScope) -> Result { - let denial = scope - .denial - .as_ref() - .ok_or_else(|| anyhow!("denied assessment scope omitted its denial"))?; - Ok(AssessmentProposal { - normalized_intent: denial.normalized_intent.clone(), - admissible: false, - missing_permission: Some(denial.missing_permission.clone()), - dc: 30, - modifiers: Vec::new(), - effect_ceiling: denial.effect_ceiling.clone(), - success_stake: denial.refusal_stake.clone(), - mixed_stake: denial.refusal_stake.clone(), - failure_stake: denial.refusal_stake.clone(), - strong_effect: WorldEffectDelta::default(), - success_effect: WorldEffectDelta::default(), - mixed_effect: WorldEffectDelta::default(), - failure_effect: WorldEffectDelta::default(), - bargains: denial.bargains.clone(), - }) -} - -fn available_mutation_lanes( - campaign: &Campaign, - acting_actor: &crate::domain::ActorState, -) -> BTreeSet { - let mut lanes = BTreeSet::from([ - AssessmentMutationLane::ActorConditions, - AssessmentMutationLane::ActorCommitments, - AssessmentMutationLane::ActorObservations, - AssessmentMutationLane::ActorRelationshipUpdates, - ]); - let has_knowledge_target = campaign.actors.values().any(|target| { - target.location_id == acting_actor.location_id - && campaign.facts.values().any(|fact| { - let accessible = if target.id == acting_actor.id { - fact.discoverable_at_location_ids - .contains(&acting_actor.location_id) - } else { - acting_actor.knowledge.contains(&fact.statement) - }; - accessible && !target.knowledge.contains(&fact.statement) - }) - }); - if has_knowledge_target { - lanes.insert(AssessmentMutationLane::ActorKnowledgeAdditions); - } - let has_destination = campaign - .locations - .get(&acting_actor.location_id) - .is_some_and(|location| { - location - .routes - .values() - .any(|route| campaign.locations.contains_key(&route.destination_id)) - }); - if has_destination { - lanes.insert(AssessmentMutationLane::ActorMoves); - } - if !campaign.clocks.is_empty() { - lanes.insert(AssessmentMutationLane::ClockAdvances); - lanes.insert(AssessmentMutationLane::ClockReductions); - } - if !campaign.institutions.is_empty() { - lanes.insert(AssessmentMutationLane::InstitutionPostures); - } - lanes -} - -fn constrain_mutation_scope_schema( - schema: &mut serde_json::Value, - available_lanes: &BTreeSet, -) -> Result<()> { - for field in ["lanes", "required_success_lanes"] { - let lane_items = schema - .pointer_mut(&format!("/properties/{field}/items")) - .ok_or_else(|| anyhow!("assessment mutation scope schema has no {field} items"))?; - *lane_items = serde_json::json!({ - "type":"string", - "enum":available_lanes, - }); - } - Ok(()) -} - -fn validate_mutation_scope( - scope: &AssessmentMutationScope, - available_lanes: &BTreeSet, -) -> Result<()> { - if !scope.lanes.is_subset(available_lanes) { - return Err(anyhow!( - "assessment mutation scope selected a structurally unavailable lane" - )); - } - if !scope.required_success_lanes.is_subset(&scope.lanes) { - return Err(anyhow!( - "assessment mutation scope required a success lane it did not select" - )); - } - match (&scope.decision, &scope.denial) { - (AssessmentScopeDecision::Assess, None) => {} - (AssessmentScopeDecision::Deny, Some(denial)) => { - if !scope.lanes.is_empty() || !scope.required_success_lanes.is_empty() { - return Err(anyhow!("denied assessment scope selected a mutation lane")); - } - for (field, value) in [ - ("normalized_intent", denial.normalized_intent.as_str()), - ("missing_permission", denial.missing_permission.as_str()), - ("effect_ceiling", denial.effect_ceiling.as_str()), - ("refusal_stake", denial.refusal_stake.as_str()), - ] { - let count = value.trim().chars().count(); - if count == 0 || count > 600 { - return Err(anyhow!( - "assessment denial {field} must contain 1 to 600 characters" - )); - } - } - if denial.bargains.is_empty() - || denial.bargains.len() > 4 - || denial - .bargains - .iter() - .any(|value| value.trim().is_empty() || value.chars().count() > 600) - { - return Err(anyhow!( - "assessment denial must contain one to four bounded bargains" - )); - } - } - (AssessmentScopeDecision::Assess, Some(_)) => { - return Err(anyhow!("assessable mutation scope included a denial")); - } - (AssessmentScopeDecision::Deny, None) => { - return Err(anyhow!("denied assessment scope omitted its denial")); - } - } - Ok(()) -} - -fn constrain_effect_schema_to_scope( - schema: &mut serde_json::Value, - selected_lanes: &BTreeSet, -) -> Result<()> { - for (lane, field) in [ - (AssessmentMutationLane::ActorConditions, "actor_conditions"), - ( - AssessmentMutationLane::ActorCommitments, - "actor_commitments", - ), - ( - AssessmentMutationLane::ActorKnowledgeAdditions, - "actor_knowledge_additions", - ), - ( - AssessmentMutationLane::ActorObservations, - "actor_observations", - ), - ( - AssessmentMutationLane::ActorRelationshipUpdates, - "actor_relationship_updates", - ), - (AssessmentMutationLane::ActorMoves, "actor_moves"), - (AssessmentMutationLane::ClockAdvances, "clock_advances"), - (AssessmentMutationLane::ClockReductions, "clock_reductions"), - ( - AssessmentMutationLane::InstitutionPostures, - "institution_postures", - ), - ] { - if !selected_lanes.contains(&lane) { - remove_effect_lane(schema, field)?; - } - } - Ok(()) -} - -fn require_success_scope( - schema: &mut serde_json::Value, - required_lanes: &BTreeSet, -) -> Result<()> { - let base_effect = schema - .pointer("/$defs/WorldEffectDelta") - .cloned() - .ok_or_else(|| anyhow!("assessment schema has no scoped world effect definition"))?; - let mut required_success_effect = base_effect.clone(); - let required_properties = required_success_effect - .get_mut("properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("scoped success effect has no properties"))?; - for lane in required_lanes { - let field = mutation_lane_field(*lane); - let property = required_properties.get_mut(field).ok_or_else(|| { - anyhow!("required success lane {field} was removed from the scoped schema") - })?; - if property.get("type").and_then(serde_json::Value::as_str) != Some("array") { - return Err(anyhow!( - "required success lane {field} is not a model mutation-entry array" - )); - } - property["minItems"] = serde_json::json!(1); - } - - let mut no_mutation_effect = base_effect; - let no_mutation_properties = no_mutation_effect - .get_mut("properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("scoped no-mutation effect has no properties"))?; - for property in no_mutation_properties.values_mut() { - if property.get("type").and_then(serde_json::Value::as_str) != Some("array") { - return Err(anyhow!( - "scoped no-mutation effect contains a non-array mutation lane" - )); - } - property["maxItems"] = serde_json::json!(0); - } - - let defs = schema - .get_mut("$defs") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("assessment schema has no definitions"))?; - defs.insert( - "RequiredSuccessWorldEffectDelta".into(), - required_success_effect, - ); - defs.insert("NoMutationWorldEffectDelta".into(), no_mutation_effect); - - let proposal_properties = schema - .get("properties") - .and_then(serde_json::Value::as_object) - .cloned() - .ok_or_else(|| anyhow!("assessment schema has no proposal properties"))?; - let required = proposal_properties - .keys() - .cloned() - .map(serde_json::Value::String) - .collect::>(); - let mut admitted_properties = proposal_properties.clone(); - admitted_properties.insert( - "admissible".into(), - serde_json::json!({"type":"boolean","enum":[true]}), - ); - admitted_properties.insert( - "missing_permission".into(), - serde_json::json!({"type":"null"}), - ); - for field in ["strong_effect", "success_effect"] { - admitted_properties.insert( - field.into(), - serde_json::json!({"$ref":"#/$defs/RequiredSuccessWorldEffectDelta"}), - ); - } - let admitted = serde_json::json!({ - "type":"object", - "properties":admitted_properties, - "required":required.clone(), - "additionalProperties":false - }); - - let mut denied_properties = proposal_properties; - denied_properties.insert( - "admissible".into(), - serde_json::json!({"type":"boolean","enum":[false]}), - ); - denied_properties.insert( - "missing_permission".into(), - serde_json::json!({"type":"string","minLength":1}), - ); - for field in [ - "strong_effect", - "success_effect", - "mixed_effect", - "failure_effect", - ] { - denied_properties.insert( - field.into(), - serde_json::json!({"$ref":"#/$defs/NoMutationWorldEffectDelta"}), - ); - } - let denied = serde_json::json!({ - "type":"object", - "properties":denied_properties, - "required":required, - "additionalProperties":false - }); - - let defs = schema - .get("$defs") - .cloned() - .ok_or_else(|| anyhow!("assessment schema lost its definitions"))?; - *schema = serde_json::json!({ - "type":"object", - "properties":{ - "proposal":{"anyOf":[admitted,denied]} - }, - "required":["proposal"], - "additionalProperties":false, - "$defs":defs - }); - Ok(()) -} - -fn validate_required_success_lanes( - proposal: &AssessmentProposal, - scope: &AssessmentMutationScope, -) -> Result<()> { - if !proposal.admissible { - return Ok(()); - } - for lane in &scope.required_success_lanes { - if !effect_uses_lane(&proposal.strong_effect, *lane) - || !effect_uses_lane(&proposal.success_effect, *lane) - { - return Err(anyhow!( - "admissible assessment omitted required success mutation lane {}", - mutation_lane_field(*lane) - )); - } - } - Ok(()) -} - -fn mutation_lane_field(lane: AssessmentMutationLane) -> &'static str { - match lane { - AssessmentMutationLane::ActorConditions => "actor_conditions", - AssessmentMutationLane::ActorCommitments => "actor_commitments", - AssessmentMutationLane::ActorKnowledgeAdditions => "actor_knowledge_additions", - AssessmentMutationLane::ActorObservations => "actor_observations", - AssessmentMutationLane::ActorRelationshipUpdates => "actor_relationship_updates", - AssessmentMutationLane::ActorMoves => "actor_moves", - AssessmentMutationLane::ClockAdvances => "clock_advances", - AssessmentMutationLane::ClockReductions => "clock_reductions", - AssessmentMutationLane::InstitutionPostures => "institution_postures", - } -} - -fn effect_uses_lane(effect: &WorldEffectDelta, lane: AssessmentMutationLane) -> bool { - match lane { - AssessmentMutationLane::ActorConditions => effect - .actor_conditions - .values() - .any(|delta| !delta.add.is_empty() || !delta.remove.is_empty()), - AssessmentMutationLane::ActorCommitments => { - effect.actor_commitments.values().any(|delta| { - !delta.goals_add.is_empty() - || !delta.goals_retire.is_empty() - || !delta.obligations_add.is_empty() - || !delta.obligations_retire.is_empty() - }) - } - AssessmentMutationLane::ActorKnowledgeAdditions => effect - .actor_knowledge_additions - .values() - .any(|additions| !additions.is_empty()), - AssessmentMutationLane::ActorObservations => effect - .actor_observations - .values() - .any(|observations| !observations.is_empty()), - AssessmentMutationLane::ActorRelationshipUpdates => effect - .actor_relationship_updates - .values() - .any(|updates| !updates.is_empty()), - AssessmentMutationLane::ActorMoves => !effect.actor_moves.is_empty(), - AssessmentMutationLane::ClockAdvances => !effect.clock_advances.is_empty(), - AssessmentMutationLane::ClockReductions => !effect.clock_reductions.is_empty(), - AssessmentMutationLane::InstitutionPostures => !effect.institution_postures.is_empty(), - } -} - -fn constrain_knowledge_map( - schema: &mut serde_json::Value, - campaign: &Campaign, - acting_actor: &crate::domain::ActorState, - present_actor_ids: &BTreeSet, -) -> Result { - let mut properties = serde_json::Map::new(); - for actor_id in present_actor_ids { - let target = campaign - .actors - .get(actor_id) - .ok_or_else(|| anyhow!("present actor vanished while binding knowledge schema"))?; - let allowed = campaign - .facts - .values() - .filter(|fact| { - let accessible = if actor_id == &acting_actor.id { - fact.discoverable_at_location_ids - .contains(&acting_actor.location_id) - } else { - acting_actor.knowledge.contains(&fact.statement) - }; - accessible && !target.knowledge.contains(&fact.statement) - }) - .map(|fact| fact.statement.clone()) - .collect::>(); - if allowed.is_empty() { - continue; - } - let max_items = usize::min(4, allowed.len()); - properties.insert( - actor_id.clone(), - serde_json::json!({ - "type":"array", - "items":{"type":"string","enum":allowed}, - "uniqueItems":true, - "minItems":1, - "maxItems":max_items - }), - ); - } - let max_properties = properties.len(); - *schema = serde_json::json!({ - "type":"object", - "properties":properties, - "additionalProperties":false, - "maxProperties":max_properties - }); - Ok(max_properties > 0) -} - -fn remove_effect_lane(schema: &mut serde_json::Value, field: &str) -> Result<()> { - let definition = schema - .pointer_mut("/$defs/WorldEffectDelta") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("assessment schema has no world effect definition"))?; - definition - .get_mut("properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("assessment schema has no world effect properties"))? - .remove(field); - if let Some(required) = definition - .get_mut("required") - .and_then(serde_json::Value::as_array_mut) - { - required.retain(|value| value.as_str() != Some(field)); - } - Ok(()) -} - -fn constrain_map_keys(schema: &mut serde_json::Value, allowed: &BTreeSet) -> Result<()> { - let object = schema - .as_object_mut() - .ok_or_else(|| anyhow!("assessment effect map schema is not an object"))?; - if allowed.is_empty() { - object.insert("maxProperties".into(), serde_json::json!(0)); - object.remove("propertyNames"); - } else { - object.insert("propertyNames".into(), serde_json::json!({"enum":allowed})); - } - Ok(()) -} - -fn action_agency_guidance(human_controlled: bool) -> &'static str { - if human_controlled { - "The acting actor is player-controlled; assess the player's attempted effect without upgrading it into a completed fact." - } else { - "The acting actor is an NPC. The player retains authority over the player's own speech, choices, consent, beliefs, disclosures, feelings, and voluntary actions. An NPC may create pressure, make an offer or threat, reveal information, oppose the player, or change independently owned world state, but no outcome stake may assert that the player answered, chose, consented, believed, disclosed, felt, or obeyed. If the intended effect is only to obtain such a player response, mark it inadmissible because the response remains the player's next decision." - } -} - -fn bind_visible_effects(proposal: &mut AssessmentProposal) -> Result<()> { - if proposal.strong_effect.actor_knowledge_additions - != proposal.success_effect.actor_knowledge_additions - { - return Err(anyhow!( - "strong and ordinary success must expose identical knowledge because they share one visible stake" - )); - } - if proposal.strong_effect.actor_observations != proposal.success_effect.actor_observations { - return Err(anyhow!( - "strong and ordinary success must expose identical observations because they share one visible stake" - )); - } - if proposal.strong_effect.actor_commitments != proposal.success_effect.actor_commitments { - return Err(anyhow!( - "strong and ordinary success must expose identical commitments because they share one visible stake" - )); - } - append_visible_commitments(&mut proposal.success_stake, &proposal.success_effect); - append_visible_commitments(&mut proposal.mixed_stake, &proposal.mixed_effect); - append_visible_commitments(&mut proposal.failure_stake, &proposal.failure_effect); - append_visible_findings(&mut proposal.success_stake, &proposal.success_effect); - append_visible_findings(&mut proposal.mixed_stake, &proposal.mixed_effect); - append_visible_findings(&mut proposal.failure_stake, &proposal.failure_effect); - Ok(()) -} - -fn append_visible_commitments(stake: &mut String, effect: &WorldEffectDelta) { - for delta in effect.actor_commitments.values() { - for (label, values) in [ - ("Goal adopted", &delta.goals_add), - ("Goal retired", &delta.goals_retire), - ("Obligation adopted", &delta.obligations_add), - ("Obligation retired", &delta.obligations_retire), - ] { - for value in values { - if !stake.contains(value) { - if !stake.trim_end().is_empty() { - stake.push(' '); - } - stake.push_str(label); - stake.push_str(": "); - stake.push_str(value); - } - } - } - } -} - -fn append_visible_findings(stake: &mut String, effect: &WorldEffectDelta) { - for finding in effect - .actor_knowledge_additions - .values() - .chain(effect.actor_observations.values()) - .flat_map(|findings| findings.iter()) - { - if !stake.contains(finding) { - if !stake.trim_end().is_empty() { - stake.push(' '); - } - stake.push_str("Observed finding: "); - stake.push_str(finding); - } - } -} - -fn allowed_references(campaign: &Campaign, actor: &crate::domain::ActorState) -> BTreeSet { - let mut refs = BTreeSet::from([ - format!("actor:{}", actor.id), - format!("location:{}", actor.location_id), - ]); - for value in actor - .capabilities - .iter() - .map(|x| format!("capability:{x}")) - .chain(actor.knowledge.iter().map(|x| format!("knowledge:{x}"))) - .chain(actor.equipment.iter().map(|x| format!("equipment:{x}"))) - .chain(actor.conditions.iter().map(|x| format!("condition:{x}"))) - .chain(actor.obligations.iter().map(|x| format!("obligation:{x}"))) - { - refs.insert(value); - } - for id in campaign.institutions.keys() { - refs.insert(format!("institution:{id}")); - } - for fact in available_information_facts(campaign, actor) { - if let Some(id) = fact.get("id").and_then(serde_json::Value::as_str) { - refs.insert(format!("fact:{id}")); - } - } - for id in &campaign.branch_origin.evidence_receipt_ids { - refs.insert(id.clone()); - } - refs -} - -fn present_actor_references( - campaign: &Campaign, - actor: &crate::domain::ActorState, -) -> BTreeSet { - campaign - .actors - .values() - .filter(|candidate| candidate.location_id == actor.location_id) - .map(|candidate| format!("actor:{}", candidate.id)) - .collect() -} - -fn available_information_facts( - campaign: &Campaign, - actor: &crate::domain::ActorState, -) -> Vec { - campaign - .facts - .values() - .filter_map(|fact| { - let access = if actor.knowledge.contains(&fact.statement) { - "known_by_actor" - } else if fact - .discoverable_at_location_ids - .contains(&actor.location_id) - { - "discoverable_here" - } else { - return None; - }; - Some(serde_json::json!({ - "id": fact.id, - "statement": fact.statement, - "scope": fact.scope, - "access": access, - })) - }) - .collect() -} -fn validate_proposal(p: &AssessmentProposal, allowed: &BTreeSet) -> Result<()> { - if ![5, 10, 15, 20, 25, 30].contains(&p.dc) { - return Err(anyhow!("assessor chose invalid DC")); - } - let invalid_values = p - .modifiers - .iter() - .filter(|modifier| modifier.value < -10 || modifier.value > 10) - .map(|modifier| format!("{}={}", modifier.label, modifier.value)) - .collect::>(); - let invalid_references = p - .modifiers - .iter() - .flat_map(|modifier| modifier.references.iter()) - .filter(|reference| !allowed.contains(*reference)) - .cloned() - .collect::>(); - if !invalid_values.is_empty() || !invalid_references.is_empty() { - return Err(anyhow!( - "assessor modifier validation failed; out-of-range values [{}]; references absent from ALLOWED REFERENCES [{}]", - invalid_values.join(", "), - invalid_references - .into_iter() - .collect::>() - .join(", ") - )); - } - if p.admissible && p.missing_permission.is_some() { - return Err(anyhow!("admissible assessment claims missing permission")); - } - if !p.admissible && p.missing_permission.is_none() { - return Err(anyhow!( - "inadmissible assessment omitted missing permission" - )); - } - if !p.admissible - && [ - &p.strong_effect, - &p.success_effect, - &p.mixed_effect, - &p.failure_effect, - ] - .into_iter() - .any(|effect| effect != &WorldEffectDelta::default()) - { - return Err(anyhow!("inadmissible assessment proposed a world mutation")); - } - Ok(()) -} - -pub(crate) fn validate_effect( - campaign: &Campaign, - acting_actor: &crate::domain::ActorState, - effect: &WorldEffectDelta, - stake: &str, -) -> Result<()> { - let affected = effect - .actor_conditions - .keys() - .chain(effect.actor_commitments.keys()) - .chain(effect.actor_knowledge_additions.keys()) - .chain(effect.actor_observations.keys()) - .chain(effect.actor_relationship_updates.keys()); - for id in affected { - let target = campaign - .actors - .get(id) - .ok_or_else(|| anyhow!("outcome delta invented an actor"))?; - if target.location_id != acting_actor.location_id { - return Err(anyhow!("outcome delta exceeds spatial reach")); - } - } - for delta in effect.actor_conditions.values() { - if delta.add.iter().any(|value| value.trim().is_empty()) - || delta.remove.iter().any(|value| value.trim().is_empty()) - || !delta.add.is_disjoint(&delta.remove) - { - return Err(anyhow!("outcome condition delta is contradictory")); - } - } - for (actor_id, delta) in &effect.actor_commitments { - let target = campaign - .actors - .get(actor_id) - .ok_or_else(|| anyhow!("outcome commitment actor vanished"))?; - let additions = delta - .goals_add - .iter() - .chain(delta.obligations_add.iter()) - .collect::>(); - let retirements = delta - .goals_retire - .iter() - .chain(delta.obligations_retire.iter()) - .collect::>(); - if additions.len().saturating_add(retirements.len()) > 4 - || additions.iter().chain(retirements.iter()).any(|value| { - value.trim().is_empty() - || value.chars().count() > 600 - || !stake.contains(value.as_str()) - }) - || !delta.goals_add.is_disjoint(&delta.goals_retire) - || !delta.obligations_add.is_disjoint(&delta.obligations_retire) - || delta - .goals_add - .iter() - .any(|value| target.goals.contains(value)) - || delta - .obligations_add - .iter() - .any(|value| target.obligations.contains(value)) - || delta - .goals_retire - .iter() - .any(|value| !target.goals.contains(value)) - || delta - .obligations_retire - .iter() - .any(|value| !target.obligations.contains(value)) - { - return Err(anyhow!( - "outcome commitment delta must add a new or retire an exact existing goal or obligation for a present actor and expose the exact commitment in its stake" - )); - } - } - for (actor_id, additions) in &effect.actor_knowledge_additions { - let target = campaign - .actors - .get(actor_id) - .ok_or_else(|| anyhow!("outcome knowledge target vanished"))?; - let invalid_finding = additions.iter().find(|finding| { - let Some(fact) = campaign - .facts - .values() - .find(|fact| fact.statement == finding.as_str()) - else { - return true; - }; - let accessible = if actor_id == &acting_actor.id { - fact.discoverable_at_location_ids - .contains(&acting_actor.location_id) - } else { - acting_actor.knowledge.contains(*finding) - }; - !accessible || target.knowledge.contains(*finding) - }); - if additions.is_empty() - || additions.len() > 4 - || additions.iter().any(|finding| { - finding.trim().is_empty() - || finding.chars().count() > 500 - || looks_like_identifier(finding) - || !stake.contains(finding) - }) - || invalid_finding.is_some() - { - return Err(anyhow!( - "outcome knowledge must copy an existing accessible WorldFact statement: a location-discoverable fact may go only to the acting actor, while another present actor may receive only a fact already known by the acting actor; every finding must be new to its recipient and visible verbatim in its stake" - )); - } - } - for (actor_id, observations) in &effect.actor_observations { - if actor_id != &acting_actor.id - || observations.is_empty() - || observations.len() > 2 - || observations.iter().any(|observation| { - observation.trim().is_empty() - || observation.chars().count() > 500 - || looks_like_identifier(observation) - || !stake.contains(observation) - || acting_actor.knowledge.contains(observation) - || campaign - .facts - .values() - .any(|fact| fact.statement == observation.as_str()) - || effect - .actor_knowledge_additions - .values() - .any(|additions| additions.contains(observation)) - }) - { - return Err(anyhow!( - "outcome observations must contain one or two new player-readable branch-local findings for only the acting actor, visible verbatim in the stake and distinct from existing propositions" - )); - } - } - for relationships in effect.actor_relationship_updates.values() { - if relationships.iter().any(|(id, value)| { - (!campaign - .actors - .get(id) - .is_some_and(|target| target.location_id == acting_actor.location_id) - && !campaign.institutions.contains_key(id)) - || value.trim().is_empty() - }) { - return Err(anyhow!( - "outcome relationship delta cited an unavailable target" - )); - } - } - for (actor_id, destination) in &effect.actor_moves { - if actor_id != &acting_actor.id - || !campaign.locations.contains_key(destination) - || !campaign.locations[&acting_actor.location_id] - .routes - .values() - .any(|route| &route.destination_id == destination) - { - return Err(anyhow!("outcome movement exceeds spatial reach")); - } - } - if let Some((id, amount)) = effect - .clock_advances - .iter() - .find(|(id, amount)| **amount == 0 || !campaign.clocks.contains_key(*id)) - { - return Err(anyhow!( - "outcome clock advance must name an existing clock and advance it by at least one: {id}={amount}" - )); - } - if let Some((id, amount)) = effect - .clock_reductions - .iter() - .find(|(id, amount)| **amount == 0 || !campaign.clocks.contains_key(*id)) - { - return Err(anyhow!( - "outcome clock reduction must name an existing clock and reduce it by at least one: {id}={amount}" - )); - } - if let Some(id) = effect - .clock_advances - .keys() - .find(|id| effect.clock_reductions.contains_key(*id)) - { - return Err(anyhow!( - "one outcome cannot both advance and reduce the same clock: {id}" - )); - } - if let Some((id, posture)) = effect.institution_postures.iter().find(|(id, posture)| { - !campaign.institutions.contains_key(*id) - || posture.trim().is_empty() - || posture.chars().count() > MAX_POSTURE_CHARS - }) { - return Err(anyhow!( - "outcome institution posture must name an existing institution and contain one to {MAX_POSTURE_CHARS} characters: {id}={posture:?}" - )); - } - Ok(()) -} - -fn looks_like_identifier(value: &str) -> bool { - let value = value.trim(); - !value.chars().any(char::is_whitespace) - && (value.contains('_') - || value.contains("::") - || value.starts_with("fact:") - || value.starts_with("fact-")) -} -pub fn assessment_digest(assessment: &ActionAssessment) -> Result { - let mut value = assessment.clone(); - value.digest.clear(); - Ok(format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(&value)?) - )) -} - -#[cfg(test)] -mod tests { - use super::*; - use async_trait::async_trait; - use std::sync::atomic::{AtomicUsize, Ordering}; - - struct DriftingAssessmentModel { - calls: AtomicUsize, - } - - struct DenyingScopeModel { - calls: AtomicUsize, - } - - struct DenyingUnsupportedRecipientModel { - calls: AtomicUsize, - } - - #[async_trait] - impl ModelPort for DenyingScopeModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.calls.fetch_add(1, Ordering::SeqCst); - assert_eq!(request.stage, "assessment_mutation_scope"); - assert!(request.lived_stream.contains("EXACT CURRENT AUTHORITY")); - assert!(request.lived_stream.contains("present_actors")); - Ok(serde_json::json!({ - "decision":"deny", - "lanes":[], - "required_success_lanes":[], - "denial":{ - "normalized_intent":"Take permanent command of an independent institution by declaration.", - "missing_permission":"The actor has no authority, leverage, custody, or extraordinary permission that can compel the institution's surrender.", - "effect_ceiling":"The actor may make the demand; the declaration cannot transfer institutional authority or custody.", - "refusal_stake":"No roll occurs and no institutional authority, custody, or obedience changes.", - "bargains":[ - "Seek a specific local concession from a present official.", - "Acquire leverage or recognized authority that the institution must answer." - ] - } - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "denying-scope-fixture" - } - } - - #[async_trait] - impl ModelPort for DenyingUnsupportedRecipientModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.calls.fetch_add(1, Ordering::SeqCst); - assert_eq!(request.stage, "assessment_mutation_scope"); - assert!(request.lived_stream.contains( - "A subject receiving, recognizing, learning, remembering, or becoming able to act on information is a canonical knowledge transition" - )); - assert!(request.lived_stream.contains("Harrow Station office")); - Ok(serde_json::json!({ - "decision":"deny", - "lanes":[], - "required_success_lanes":[], - "denial":{ - "normalized_intent":"Deliver Vesa Orn's exact message to the Harrow Station office and establish its receipt.", - "missing_permission":"No exact foreground knowledge-recipient and channel mutation path is available for the remote Harrow Station office.", - "effect_ceiling":"Asha may speak into or deposit the message in the apparatus, but cannot establish institutional receipt or recognition.", - "refusal_stake":"No roll occurs and no remote or institutional subject acquires the message.", - "bargains":[ - "Reach an exact present Harrow representative who can receive the message.", - "Establish an admitted bidirectional channel bound to an exact recipient." - ] - } - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "unsupported-recipient-scope-fixture" - } - } - - #[tokio::test] - async fn impossible_overreach_terminates_after_one_compact_admission_stage() { - let model = Arc::new(DenyingScopeModel { - calls: AtomicUsize::new(0), - }); - let assessor = ActionAssessor::with_models(model.clone(), "fast", "capable"); - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let mut campaign = crate::resolution::tests::campaign(0, 1); - let intent = ActionIntent { - actor_id: "player".into(), - description: "I declare myself the ruler of every institution.".into(), - intended_effect: "Every institution surrenders its authority and obeys forever.".into(), - }; - - let (first, first_receipt) = assessor - .assess_with_context_cached(&store, &campaign, intent.clone(), &[], None, &[]) - .await - .unwrap(); - assert!(!first.admissible); - assert!(first.missing_permission.is_some()); - assert_eq!(first.bargains.len(), 2); - assert_eq!(first.strong_effect, WorldEffectDelta::default()); - assert_eq!(first.success_effect, WorldEffectDelta::default()); - assert_eq!(first_receipt.stage, "assessment_mutation_scope"); - assert_eq!(model.calls.load(Ordering::SeqCst), 1); - assert!( - store - .keys(ASSESSMENT_PROPOSAL_CACHE_KIND) - .unwrap() - .is_empty() - ); - assert_eq!(store.keys(ASSESSMENT_SCOPE_CACHE_KIND).unwrap().len(), 1); - let stages = store - .load_all::("persona_stage_receipt.v1") - .unwrap() - .into_iter() - .map(|receipt| receipt.stage) - .collect::>(); - assert_eq!(stages, BTreeSet::from(["assessment_mutation_scope".into()])); - - campaign.revision += 1; - let (second, second_receipt) = assessor - .assess_with_context_cached(&store, &campaign, intent, &[], None, &[]) - .await - .unwrap(); - assert_eq!(model.calls.load(Ordering::SeqCst), 1); - assert!(!second.admissible); - assert_eq!(second.revision, 1); - assert_ne!(first.digest, second.digest); - assert_eq!(second_receipt.validation_result, "valid_cache_hit"); - } - - #[tokio::test] - async fn unsupported_remote_or_institution_recipient_is_denied_before_resolution() { - let model = Arc::new(DenyingUnsupportedRecipientModel { - calls: AtomicUsize::new(0), - }); - let assessor = ActionAssessor::with_models(model.clone(), "fast", "capable"); - let mut campaign = crate::resolution::tests::campaign(0, 1); - campaign.institutions.insert( - "harrow-station-office".into(), - crate::domain::InstitutionState { - id: "harrow-station-office".into(), - name: "Harrow Station office".into(), - resources: vec![], - goals: vec!["maintain the station's message service".into()], - posture: "unverified".into(), - }, - ); - let intent = ActionIntent { - actor_id: "player".into(), - description: - "Use the marked message tube to recite Vesa Orn's exact message unchanged.".into(), - intended_effect: - "The Harrow Station office receives and recognizes Vesa Orn's exact words.".into(), - }; - - let (assessment, receipt) = assessor - .assess_with_context(&campaign, intent, &[], None, &[]) - .await - .unwrap(); - - assert!(!assessment.admissible); - assert!( - assessment - .missing_permission - .as_deref() - .is_some_and(|value| value.contains("knowledge-recipient")) - ); - assert_eq!(assessment.strong_effect, WorldEffectDelta::default()); - assert_eq!(assessment.success_effect, WorldEffectDelta::default()); - assert_eq!(receipt.stage, "assessment_mutation_scope"); - assert_eq!(model.calls.load(Ordering::SeqCst), 1); - } - - fn proposal_value_for_request( - request: &ModelStageRequest, - proposal: AssessmentProposal, - ) -> Result { - let mut value = serde_json::to_value(proposal)?; - let allowed_effect_fields = request - .output_schema - .as_ref() - .and_then(|schema| schema.pointer("/$defs/WorldEffectDelta/properties")) - .and_then(serde_json::Value::as_object) - .map(|properties| properties.keys().cloned().collect::>()) - .unwrap_or_default(); - for field in [ - "strong_effect", - "success_effect", - "mixed_effect", - "failure_effect", - ] { - let canonical: WorldEffectDelta = serde_json::from_value(value[field].clone())?; - value[field] = encode_effect_entries(&canonical, &allowed_effect_fields); - } - Ok(serde_json::json!({"proposal":value})) - } - - fn encode_effect_entries( - effect: &WorldEffectDelta, - allowed_fields: &BTreeSet, - ) -> serde_json::Value { - let mut fields = serde_json::Map::new(); - if allowed_fields.contains("actor_conditions") { - let mut entries = Vec::new(); - for (actor_id, delta) in &effect.actor_conditions { - entries.extend(delta.add.iter().map(|condition| { - serde_json::json!({ - "actor_id":actor_id, - "operation":"add", - "condition":condition - }) - })); - entries.extend(delta.remove.iter().map(|condition| { - serde_json::json!({ - "actor_id":actor_id, - "operation":"remove", - "condition":condition - }) - })); - } - fields.insert("actor_conditions".into(), serde_json::Value::Array(entries)); - } - if allowed_fields.contains("actor_commitments") { - let mut entries = Vec::new(); - for (actor_id, delta) in &effect.actor_commitments { - entries.extend(delta.goals_add.iter().map(|description| { - serde_json::json!({ - "actor_id":actor_id, - "operation":"add_goal", - "description":description - }) - })); - entries.extend(delta.goals_retire.iter().map(|description| { - serde_json::json!({ - "actor_id":actor_id, - "operation":"retire_goal", - "description":description - }) - })); - entries.extend(delta.obligations_add.iter().map(|description| { - serde_json::json!({ - "actor_id":actor_id, - "operation":"add_obligation", - "description":description - }) - })); - entries.extend(delta.obligations_retire.iter().map(|description| { - serde_json::json!({ - "actor_id":actor_id, - "operation":"retire_obligation", - "description":description - }) - })); - } - fields.insert( - "actor_commitments".into(), - serde_json::Value::Array(entries), - ); - } - if allowed_fields.contains("actor_knowledge_additions") { - let entries = effect - .actor_knowledge_additions - .iter() - .flat_map(|(actor_id, statements)| { - statements.iter().map(move - |statement| serde_json::json!({"actor_id":actor_id,"statement":statement}), - ) - }) - .collect(); - fields.insert( - "actor_knowledge_additions".into(), - serde_json::Value::Array(entries), - ); - } - if allowed_fields.contains("actor_observations") { - let entries = effect - .actor_observations - .iter() - .flat_map(|(actor_id, statements)| { - statements.iter().map(move |statement| { - serde_json::json!({"actor_id":actor_id,"statement":statement}) - }) - }) - .collect(); - fields.insert( - "actor_observations".into(), - serde_json::Value::Array(entries), - ); - } - if allowed_fields.contains("actor_relationship_updates") { - let entries = effect - .actor_relationship_updates - .iter() - .flat_map(|(actor_id, targets)| { - targets.iter().map(move |(target_id, relationship)| { - serde_json::json!({ - "actor_id":actor_id, - "target_id":target_id, - "relationship":relationship - }) - }) - }) - .collect(); - fields.insert( - "actor_relationship_updates".into(), - serde_json::Value::Array(entries), - ); - } - if allowed_fields.contains("actor_moves") { - let entries = effect - .actor_moves - .iter() - .map(|(actor_id, destination_id)| { - serde_json::json!({"actor_id":actor_id,"destination_id":destination_id}) - }) - .collect(); - fields.insert("actor_moves".into(), serde_json::Value::Array(entries)); - } - for (field, clocks) in [ - ("clock_advances", &effect.clock_advances), - ("clock_reductions", &effect.clock_reductions), - ] { - if allowed_fields.contains(field) { - let entries = clocks - .iter() - .map(|(clock_id, amount)| { - serde_json::json!({"clock_id":clock_id,"amount":amount}) - }) - .collect(); - fields.insert(field.into(), serde_json::Value::Array(entries)); - } - } - if allowed_fields.contains("institution_postures") { - let entries = effect - .institution_postures - .iter() - .map(|(institution_id, posture)| { - serde_json::json!({"institution_id":institution_id,"posture":posture}) - }) - .collect(); - fields.insert( - "institution_postures".into(), - serde_json::Value::Array(entries), - ); - } - serde_json::Value::Object(fields) - } - - #[async_trait] - impl ModelPort for DriftingAssessmentModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - if request.stage == "assessment_mutation_scope" { - return Ok( - r#"{"decision":"assess","lanes":[],"required_success_lanes":[],"denial":null}"# - .into(), - ); - } - if request.stage == "assessment_effect_verifier" { - return Ok( - r#"{"result":"match","mismatch_kind":null,"repair_guidance":null}"#.into(), - ); - } - assert!( - request - .lived_stream - .contains("remaining lanes are an upper bound") - ); - let call = self.calls.fetch_add(1, Ordering::SeqCst); - let mut value = proposal_value_for_request(request, proposal("actor:player"))?; - value["proposal"]["modifiers"][0]["value"] = - serde_json::json!(if call == 0 { 2 } else { 6 }); - Ok(serde_json::to_string(&value)?) - } - - fn provider(&self) -> &'static str { - "drifting-fixture" - } - } - - fn proposal(reference: &str) -> AssessmentProposal { - AssessmentProposal { - normalized_intent: "open the gate".into(), - admissible: true, - missing_permission: None, - dc: 15, - modifiers: vec![ContextModifier { - label: "tool".into(), - value: 2, - references: vec![reference.into()], - }], - effect_ceiling: "open this gate".into(), - success_stake: "gate opens".into(), - mixed_stake: "gate opens noisily".into(), - failure_stake: "lock jams".into(), - strong_effect: WorldEffectDelta::default(), - success_effect: WorldEffectDelta::default(), - mixed_effect: WorldEffectDelta::default(), - failure_effect: WorldEffectDelta::default(), - bargains: vec![], - } - } - - #[tokio::test] - async fn unchanged_semantic_packet_reuses_exact_validated_assessment_proposal() { - let model = Arc::new(DriftingAssessmentModel { - calls: AtomicUsize::new(0), - }); - let assessor = ActionAssessor::new(model.clone(), "fixture-model"); - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let mut campaign = crate::resolution::tests::campaign(0, 1); - let intent = ActionIntent { - actor_id: "player".into(), - description: "inspect the gate".into(), - intended_effect: "learn whether it is open".into(), - }; - - let (first, first_receipt) = assessor - .assess_with_context_cached(&store, &campaign, intent.clone(), &[], None, &[]) - .await - .unwrap(); - campaign.revision += 1; - let (second, second_receipt) = assessor - .assess_with_context_cached(&store, &campaign, intent, &[], None, &[]) - .await - .unwrap(); - - assert_eq!(model.calls.load(Ordering::SeqCst), 1); - assert_eq!(first.modifiers, second.modifiers); - assert_eq!(first.modifier_total, 2); - assert_eq!(second.modifier_total, 2); - assert_eq!(first.revision, 0); - assert_eq!(second.revision, 1); - assert_ne!(first.digest, second.digest); - assert_eq!(first_receipt.validation_result, "valid"); - assert_eq!(second_receipt.validation_result, "valid_cache_hit"); - assert!( - second_receipt.provider_attempts[0] - .transport_features - .contains(&"cultcache.output-cache".to_string()) - ); - assert!( - second_receipt.provider_attempts[0] - .transport_features - .iter() - .any(|feature| feature.starts_with("source-mutation-scope:sha256:")) - ); - assert!( - second_receipt.provider_attempts[0] - .transport_features - .iter() - .any(|feature| feature.starts_with("source-effect-verifier:sha256:")) - ); - assert_eq!(store.keys(ASSESSMENT_PROPOSAL_CACHE_KIND).unwrap().len(), 1); - assert_eq!(store.keys(ASSESSMENT_SCOPE_CACHE_KIND).unwrap().len(), 1); - assert_eq!(store.keys("persona_stage_receipt.v1").unwrap().len(), 3); - } - - struct ConcretizingObservationModel { - assessment_calls: AtomicUsize, - verifier_calls: AtomicUsize, - } - - struct OmittedRecipientEffectModel { - assessment_calls: AtomicUsize, - verifier_calls: AtomicUsize, - } - - #[async_trait] - impl ModelPort for OmittedRecipientEffectModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - match request.stage.as_str() { - "assessment_mutation_scope" => Ok(serde_json::json!({ - "decision":"assess", - "lanes":[], - "required_success_lanes":[], - "denial":null - }) - .to_string()), - "action_assessment" => { - self.assessment_calls.fetch_add(1, Ordering::SeqCst); - assert!(request.lived_stream.contains( - "Never promise remote, institutional, population, place, office, or absent-actor receipt" - )); - let mut value = proposal_value_for_request(request, proposal("actor:player"))?; - value["proposal"]["normalized_intent"] = - serde_json::json!("send Vesa Orn's exact message to Harrow Station"); - value["proposal"]["effect_ceiling"] = serde_json::json!( - "The station office may receive and recognize the exact message." - ); - value["proposal"]["success_stake"] = serde_json::json!( - "The Harrow Station office receives and recognizes Vesa Orn's exact words." - ); - value["proposal"]["mixed_stake"] = serde_json::json!( - "The office receives only part of the message and cannot authenticate it." - ); - value["proposal"]["failure_stake"] = - serde_json::json!("The message does not reach the office."); - Ok(serde_json::to_string(&value)?) - } - "assessment_effect_verifier" => { - self.verifier_calls.fetch_add(1, Ordering::SeqCst); - assert!(request.lived_stream.contains( - "If a stake claims such a transition without an exact typed knowledge mutation for that exact recipient" - )); - Ok(serde_json::json!({ - "result":"mismatch", - "mismatch_kind":"effect_omission", - "repair_guidance":"The stake claims Harrow Station learned the message without an exact recipient knowledge mutation; deny the intended delivery rather than narrating receipt." - }) - .to_string()) - } - stage => Err(anyhow!("unexpected fixture stage {stage}")), - } - } - - fn provider(&self) -> &'static str { - "omitted-recipient-effect-fixture" - } - } - - #[async_trait] - impl ModelPort for ConcretizingObservationModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - match request.stage.as_str() { - "assessment_mutation_scope" => Ok(serde_json::json!({ - "decision":"assess", - "lanes":["actor_observations"], - "required_success_lanes":["actor_observations"], - "denial":null - }) - .to_string()), - "action_assessment" => { - self.assessment_calls.fetch_add(1, Ordering::SeqCst); - assert!(request.lived_stream.contains( - "An actor_observations statement is itself the canonical branch-local proposition" - )); - let correction = request - .lived_stream - .contains("SEMANTIC EFFECT VERIFIER REJECTED"); - if correction { - assert!( - request.lived_stream.contains( - "Replace the inquiry-status observation with one concrete" - ) - ); - } - let statement = if correction { - "The station is visibly unoccupied, but a weatherproof platform dispatch box is powered and accepts written messages for the Harrow watch." - } else { - "The inspection establishes whether the station is occupied and identifies a usable message channel if one exists." - }; - let mut value = proposal_value_for_request(request, proposal("actor:player"))?; - value["proposal"]["normalized_intent"] = - serde_json::json!("inspect the station for a message channel"); - value["proposal"]["effect_ceiling"] = serde_json::json!( - "Direct local evidence may establish station occupancy and one usable message channel." - ); - value["proposal"]["success_stake"] = - serde_json::json!("The inspection answers the bounded local question."); - value["proposal"]["mixed_stake"] = - serde_json::json!("Only part of the station can be assessed."); - value["proposal"]["failure_stake"] = - serde_json::json!("The station remains unreadable from the platform."); - for effect in ["strong_effect", "success_effect"] { - value["proposal"][effect]["actor_observations"] = serde_json::json!([{ - "actor_id":"player", - "statement":statement - }]); - } - Ok(serde_json::to_string(&value)?) - } - "assessment_effect_verifier" => { - self.verifier_calls.fetch_add(1, Ordering::SeqCst); - assert!( - request - .lived_stream - .contains("must therefore be a concrete, truth-apt proposition") - ); - let unresolved = request - .lived_stream - .contains("identifies a usable message channel if one exists"); - Ok(if unresolved { - serde_json::json!({ - "result":"mismatch", - "mismatch_kind":"invented_outcome", - "repair_guidance":"Replace the inquiry-status observation with one concrete, truth-apt local finding that resolves occupancy or the message channel within the previewed ceiling." - }) - } else { - serde_json::json!({ - "result":"match", - "mismatch_kind":null, - "repair_guidance":null - }) - } - .to_string()) - } - stage => Err(anyhow!("unexpected fixture stage {stage}")), - } - } - - fn provider(&self) -> &'static str { - "concretizing-observation-fixture" - } - } - - #[tokio::test] - async fn semantic_verifier_rejects_inquiry_status_as_canonical_observation() { - let model = Arc::new(ConcretizingObservationModel { - assessment_calls: AtomicUsize::new(0), - verifier_calls: AtomicUsize::new(0), - }); - let assessor = ActionAssessor::with_models(model.clone(), "flash", "capable"); - let campaign = crate::resolution::tests::campaign(0, 1); - let intent = ActionIntent { - actor_id: "player".into(), - description: "inspect the station platform and signal equipment".into(), - intended_effect: "learn whether anyone is present and find a message channel".into(), - }; - - let (assessment, _) = assessor - .assess_with_context(&campaign, intent, &[], None, &[]) - .await - .unwrap(); - - assert_eq!(model.assessment_calls.load(Ordering::SeqCst), 2); - assert_eq!(model.verifier_calls.load(Ordering::SeqCst), 2); - assert_eq!( - assessment.success_effect.actor_observations["player"], - BTreeSet::from(["The station is visibly unoccupied, but a weatherproof platform dispatch box is powered and accepts written messages for the Harrow watch.".into()]) - ); - assert!(!assessment.success_stake.contains("if one exists")); - } - - #[tokio::test] - async fn semantic_verifier_aborts_narrated_receipt_without_a_recipient_mutation() { - let model = Arc::new(OmittedRecipientEffectModel { - assessment_calls: AtomicUsize::new(0), - verifier_calls: AtomicUsize::new(0), - }); - let assessor = ActionAssessor::with_models(model.clone(), "flash", "capable"); - let campaign = crate::resolution::tests::campaign(0, 1); - let intent = ActionIntent { - actor_id: "player".into(), - description: "Recite Vesa Orn's exact message into the station tube.".into(), - intended_effect: "The Harrow Station office receives and recognizes it.".into(), - }; - - let error = assessor - .assess_with_context(&campaign, intent, &[], None, &[]) - .await - .unwrap_err() - .to_string(); - - assert!(error.contains("failed semantic effect verification after one correction")); - assert!(error.contains("without an exact recipient knowledge mutation")); - assert_eq!(model.assessment_calls.load(Ordering::SeqCst), 2); - assert_eq!(model.verifier_calls.load(Ordering::SeqCst), 2); - } - - struct CorrectingEffectModel { - assessment_calls: AtomicUsize, - verifier_calls: AtomicUsize, - corrects: bool, - } - - #[async_trait] - impl ModelPort for CorrectingEffectModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - match request.stage.as_str() { - "assessment_mutation_scope" => Ok(serde_json::json!({ - "decision":"assess", - "lanes":["actor_knowledge_additions","actor_relationship_updates"], - "required_success_lanes":["actor_relationship_updates"], - "denial":null - }) - .to_string()), - "action_assessment" => { - self.assessment_calls.fetch_add(1, Ordering::SeqCst); - let correction = request - .lived_stream - .contains("SEMANTIC EFFECT VERIFIER REJECTED"); - if correction { - assert!( - request - .lived_stream - .contains("Remove the ration knowledge transfer") - ); - } - let mut value = proposal_value_for_request(request, proposal("actor:target"))?; - value["proposal"]["normalized_intent"] = - serde_json::json!("honor the target's consent boundary"); - value["proposal"]["effect_ceiling"] = serde_json::json!( - "The target may trust the player more while retaining control of their identity." - ); - value["proposal"]["success_stake"] = - serde_json::json!("The target's trust deepens."); - value["proposal"]["mixed_stake"] = - serde_json::json!("The target remains cautious."); - value["proposal"]["failure_stake"] = - serde_json::json!("The promise sounds hollow."); - for effect in ["strong_effect", "success_effect"] { - value["proposal"][effect]["actor_relationship_updates"] = serde_json::json!([{ - "actor_id":"target", - "target_id":"player", - "relationship":"trusts the player to respect their consent boundary" - }]); - } - if !correction || !self.corrects { - for effect in ["strong_effect", "success_effect"] { - value["proposal"][effect]["actor_knowledge_additions"] = serde_json::json!([{ - "actor_id":"target", - "statement":"Rations are restricted." - }]); - } - } - Ok(serde_json::to_string(&value)?) - } - "assessment_effect_verifier" => { - assert!(request.lived_stream.contains("\"name\":\"Target\"")); - self.verifier_calls.fetch_add(1, Ordering::SeqCst); - let mismatch = request.lived_stream.contains("Rations are restricted."); - Ok(if mismatch { - serde_json::json!({ - "result":"mismatch", - "mismatch_kind":"unrelated_mutation", - "repair_guidance":"Remove the ration knowledge transfer; the trust promise does not communicate ration policy." - }) - } else { - serde_json::json!({ - "result":"match", - "mismatch_kind":null, - "repair_guidance":null - }) - } - .to_string()) - } - stage => Err(anyhow!("unexpected fixture stage {stage}")), - } - } - - fn provider(&self) -> &'static str { - "correcting-effect-fixture" - } - } - - #[tokio::test] - async fn semantic_verifier_removes_a_legal_but_unrelated_effect_before_caching() { - let model = Arc::new(CorrectingEffectModel { - assessment_calls: AtomicUsize::new(0), - verifier_calls: AtomicUsize::new(0), - corrects: true, - }); - let assessor = ActionAssessor::with_models(model.clone(), "flash", "capable"); - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let mut campaign = crate::resolution::tests::campaign(0, 1); - let acting = campaign.actors["player"].clone(); - campaign - .actors - .get_mut("player") - .unwrap() - .knowledge - .insert("Rations are restricted.".into()); - let mut target = acting.clone(); - target.id = "target".into(); - target.name = "Target".into(); - target.knowledge.clear(); - campaign.actors.insert(target.id.clone(), target); - campaign.facts.insert( - "ration-policy".into(), - crate::domain::WorldFact { - id: "ration-policy".into(), - statement: "Rations are restricted.".into(), - scope: crate::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::new(), - }, - ); - - let (assessment, _) = - assessor - .assess_with_context_cached( - &store, - &campaign, - ActionIntent { - actor_id: "player".into(), - description: - "Promise not to record the target's route role without consent.".into(), - intended_effect: - "The target trusts the player more while retaining identity control." - .into(), - }, - &[], - None, - &[], - ) - .await - .unwrap(); - - assert_eq!(model.assessment_calls.load(Ordering::SeqCst), 2); - assert_eq!(model.verifier_calls.load(Ordering::SeqCst), 2); - assert!( - assessment - .success_effect - .actor_knowledge_additions - .is_empty() - ); - assert_eq!( - assessment.success_effect.actor_relationship_updates["target"]["player"], - "trusts the player to respect their consent boundary" - ); - let stage_receipts = store - .load_all::("persona_stage_receipt.v1") - .unwrap(); - assert_eq!(stage_receipts.len(), 5); - assert_eq!( - stage_receipts - .iter() - .filter(|receipt| receipt.validation_result == "semantic_invalid") - .count(), - 2 - ); - assert_eq!( - stage_receipts - .iter() - .filter(|receipt| receipt.validation_result == "valid") - .count(), - 3 - ); - assert_eq!( - stage_receipts - .iter() - .filter(|receipt| receipt.stage == "assessment_mutation_scope") - .count(), - 1 - ); - assert_eq!( - stage_receipts - .iter() - .filter(|receipt| receipt.stage == "action_assessment") - .count(), - 2 - ); - assert_eq!( - stage_receipts - .iter() - .filter(|receipt| receipt.stage == "assessment_effect_verifier") - .count(), - 2 - ); - assert_eq!(store.keys(ASSESSMENT_PROPOSAL_CACHE_KIND).unwrap().len(), 1); - assert_eq!(store.keys(ASSESSMENT_SCOPE_CACHE_KIND).unwrap().len(), 1); - } - - #[tokio::test] - async fn repeated_semantic_mismatch_aborts_without_a_cache_entry() { - let model = Arc::new(CorrectingEffectModel { - assessment_calls: AtomicUsize::new(0), - verifier_calls: AtomicUsize::new(0), - corrects: false, - }); - let assessor = ActionAssessor::with_models(model.clone(), "flash", "capable"); - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let mut campaign = crate::resolution::tests::campaign(0, 1); - let acting = campaign.actors["player"].clone(); - campaign - .actors - .get_mut("player") - .unwrap() - .knowledge - .insert("Rations are restricted.".into()); - let mut target = acting; - target.id = "target".into(); - target.name = "Target".into(); - target.knowledge.clear(); - campaign.actors.insert(target.id.clone(), target); - campaign.facts.insert( - "ration-policy".into(), - crate::domain::WorldFact { - id: "ration-policy".into(), - statement: "Rations are restricted.".into(), - scope: crate::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::new(), - }, - ); - - let error = assessor - .assess_with_context_cached( - &store, - &campaign, - ActionIntent { - actor_id: "player".into(), - description: "Promise not to record the target without consent.".into(), - intended_effect: "The target trusts the player more.".into(), - }, - &[], - None, - &[], - ) - .await - .unwrap_err() - .to_string(); - - assert!(error.contains("failed semantic effect verification after one correction")); - assert_eq!(model.assessment_calls.load(Ordering::SeqCst), 2); - assert_eq!(model.verifier_calls.load(Ordering::SeqCst), 2); - assert!( - store - .keys(ASSESSMENT_PROPOSAL_CACHE_KIND) - .unwrap() - .is_empty() - ); - let receipts = store - .load_all::("persona_stage_receipt.v1") - .unwrap(); - assert_eq!(receipts.len(), 5); - assert_eq!( - receipts - .iter() - .filter(|receipt| receipt.validation_result == "semantic_invalid") - .count(), - 4 - ); - assert_eq!( - receipts - .iter() - .filter(|receipt| receipt.stage == "assessment_mutation_scope") - .count(), - 1 - ); - } - - #[test] - fn assessment_rejects_unearned_state_reference() { - let allowed = BTreeSet::from(["equipment:key".into()]); - let error = validate_proposal(&proposal("capability:telepathy"), &allowed) - .unwrap_err() - .to_string(); - assert!(error.contains("capability:telepathy")); - assert!(error.contains("ALLOWED REFERENCES")); - assert!(validate_proposal(&proposal("equipment:key"), &allowed).is_ok()); - } - - #[test] - fn assessment_reference_schema_enumerates_exact_allowed_values() { - let campaign = crate::resolution::tests::campaign(0, 1); - let acting = &campaign.actors["player"]; - let allowed = BTreeSet::from([ - "actor:player".into(), - "actor:clinic-director".into(), - "equipment:audit-seal".into(), - ]); - let mut schema = serde_json::to_value(schema_for!(AssessmentProposal)).unwrap(); - constrain_assessment_schema(&mut schema, &allowed, &campaign, acting).unwrap(); - let values = schema - .pointer("/$defs/ContextModifier/properties/references/items/enum") - .and_then(serde_json::Value::as_array) - .unwrap() - .iter() - .filter_map(serde_json::Value::as_str) - .collect::>(); - assert_eq!( - values, - BTreeSet::from([ - "actor:player", - "actor:clinic-director", - "equipment:audit-seal" - ]) - ); - } - - #[test] - fn mutation_scope_removes_every_causally_unselected_effect_lane() { - let campaign = crate::resolution::tests::campaign(0, 1); - let acting = &campaign.actors["player"]; - let mut schema = serde_json::to_value(schema_for!(AssessmentProposal)).unwrap(); - constrain_assessment_schema( - &mut schema, - &BTreeSet::from(["actor:player".into()]), - &campaign, - acting, - ) - .unwrap(); - project_effect_schema_to_mutation_entries(&mut schema, &campaign).unwrap(); - constrain_effect_schema_to_scope( - &mut schema, - &BTreeSet::from([AssessmentMutationLane::ActorRelationshipUpdates]), - ) - .unwrap(); - - let fields = schema - .pointer("/$defs/WorldEffectDelta/properties") - .and_then(serde_json::Value::as_object) - .unwrap() - .keys() - .map(String::as_str) - .collect::>(); - assert_eq!(fields, BTreeSet::from(["actor_relationship_updates"])); - } - - #[test] - fn mutation_scope_schema_inlines_the_provider_enum_without_ref_siblings() { - let mut schema = serde_json::to_value(schema_for!(AssessmentMutationScope)).unwrap(); - constrain_mutation_scope_schema( - &mut schema, - &BTreeSet::from([ - AssessmentMutationLane::ActorConditions, - AssessmentMutationLane::ActorRelationshipUpdates, - ]), - ) - .unwrap(); - - for field in ["lanes", "required_success_lanes"] { - let items = schema - .pointer(&format!("/properties/{field}/items")) - .unwrap(); - assert_eq!(items["type"], "string"); - assert!(items.get("$ref").is_none()); - assert_eq!( - items["enum"], - serde_json::json!(["actor_conditions", "actor_relationship_updates"]) - ); - } - } - - #[test] - fn required_success_lane_is_structural_and_locally_rechecked() { - let campaign = crate::resolution::tests::campaign(0, 1); - let acting = &campaign.actors["player"]; - let required = BTreeSet::from([AssessmentMutationLane::ActorRelationshipUpdates]); - let mut schema = serde_json::to_value(schema_for!(AssessmentProposal)).unwrap(); - constrain_assessment_schema( - &mut schema, - &BTreeSet::from(["actor:player".into()]), - &campaign, - acting, - ) - .unwrap(); - project_effect_schema_to_mutation_entries(&mut schema, &campaign).unwrap(); - constrain_effect_schema_to_scope(&mut schema, &required).unwrap(); - require_success_scope(&mut schema, &required).unwrap(); - assert!(schema.get("anyOf").is_none()); - assert_eq!( - schema["properties"]["proposal"]["anyOf"][0]["properties"]["success_effect"]["$ref"], - "#/$defs/RequiredSuccessWorldEffectDelta" - ); - assert_eq!( - schema["properties"]["proposal"]["anyOf"][0]["properties"]["admissible"]["enum"], - serde_json::json!([true]) - ); - assert_eq!( - schema["properties"]["proposal"]["anyOf"][1]["properties"]["admissible"]["enum"], - serde_json::json!([false]) - ); - assert_eq!( - schema["$defs"]["RequiredSuccessWorldEffectDelta"]["properties"]["actor_relationship_updates"] - ["minItems"], - 1 - ); - assert_eq!( - schema["$defs"]["NoMutationWorldEffectDelta"]["properties"]["actor_relationship_updates"] - ["maxItems"], - 0 - ); - - let scope = AssessmentMutationScope { - decision: AssessmentScopeDecision::Assess, - lanes: required.clone(), - required_success_lanes: required, - denial: None, - }; - let mut candidate = proposal("actor:player"); - let error = validate_required_success_lanes(&candidate, &scope) - .unwrap_err() - .to_string(); - assert!(error.contains("actor_relationship_updates")); - for effect in [&mut candidate.strong_effect, &mut candidate.success_effect] { - effect.actor_relationship_updates.insert( - "player".into(), - BTreeMap::from([("player".into(), "trust deepens".into())]), - ); - } - validate_required_success_lanes(&candidate, &scope).unwrap(); - } - - #[test] - fn assessment_effect_schema_binds_exact_visible_and_spatial_scope() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - let acting = campaign.actors["player"].clone(); - campaign.clocks.insert( - "clinic-failure".into(), - crate::domain::WorldClock { - id: "clinic-failure".into(), - label: "Clinic failure".into(), - progress: 1, - threshold: 4, - consequence: "The clinic fails.".into(), - consequence_scope: Default::default(), - }, - ); - campaign.institutions.insert( - "clinic".into(), - crate::domain::InstitutionState { - id: "clinic".into(), - name: "Clinic".into(), - resources: vec![], - goals: vec!["remain operational".into()], - posture: "strained".into(), - }, - ); - let mut nearby = acting.clone(); - nearby.id = "clinic-director".into(); - nearby.name = "Clinic Director".into(); - campaign.actors.insert(nearby.id.clone(), nearby); - campaign.locations.insert( - "adjacent".into(), - crate::domain::Location { - id: "adjacent".into(), - name: "Adjacent".into(), - container_id: None, - routes: Default::default(), - persistent_features: vec![], - }, - ); - campaign - .locations - .get_mut(&acting.location_id) - .unwrap() - .routes - .insert( - "adjacent".into(), - crate::domain::Route { - destination_id: "adjacent".into(), - distance: "5 km".into(), - travel_minutes: 20, - }, - ); - campaign.locations.insert( - "remote".into(), - crate::domain::Location { - id: "remote".into(), - name: "Remote".into(), - container_id: None, - routes: Default::default(), - persistent_features: vec![], - }, - ); - let mut remote = acting.clone(); - remote.id = "remote-commander".into(); - remote.name = "Remote Commander".into(); - remote.location_id = "remote".into(); - campaign.actors.insert(remote.id.clone(), remote); - - let mut schema = serde_json::to_value(schema_for!(AssessmentProposal)).unwrap(); - constrain_assessment_schema(&mut schema, &BTreeSet::new(), &campaign, &acting).unwrap(); - project_effect_schema_to_mutation_entries(&mut schema, &campaign).unwrap(); - let effect = schema - .pointer("/$defs/WorldEffectDelta/properties") - .unwrap(); - let actor_targets = effect["actor_conditions"]["items"]["properties"]["actor_id"]["enum"] - .as_array() - .unwrap() - .iter() - .filter_map(serde_json::Value::as_str) - .collect::>(); - assert_eq!(actor_targets, BTreeSet::from(["clinic-director", "player"])); - assert_eq!( - effect["actor_observations"]["items"]["properties"]["actor_id"]["enum"], - serde_json::json!(["player"]) - ); - let observation_validator = - jsonschema::validator_for(&effect["actor_observations"]).unwrap(); - assert!(observation_validator.is_valid(&serde_json::json!([{ - "actor_id":"player", - "statement":"The left coupling carries the highest current thermal stress." - }]))); - assert!(!observation_validator.is_valid(&serde_json::json!([{ - "actor_id":"clinic-director", - "statement":"The left coupling carries the highest current thermal stress." - }]))); - let commitments = &effect["actor_commitments"]; - let commitment_validator = jsonschema::validator_for(commitments).unwrap(); - assert!(commitment_validator.is_valid(&serde_json::json!([{ - "actor_id":"clinic-director", - "operation":"add_obligation", - "description":"state concrete supervised-inspection terms" - }]))); - assert!(!commitment_validator.is_valid(&serde_json::json!([{ - "actor_id":"remote-commander", - "operation":"add_obligation", - "description":"state concrete supervised-inspection terms" - }]))); - let relationship_targets = - effect["actor_relationship_updates"]["items"]["properties"]["target_id"]["enum"] - .as_array() - .unwrap() - .iter() - .filter_map(serde_json::Value::as_str) - .collect::>(); - assert!(relationship_targets.contains("clinic-director")); - assert!(relationship_targets.contains("player")); - assert!(!relationship_targets.contains("remote-commander")); - assert_eq!( - effect["actor_moves"]["items"]["properties"]["actor_id"]["enum"], - serde_json::json!(["player"]) - ); - assert_eq!( - effect["actor_moves"]["items"]["properties"]["destination_id"]["enum"], - serde_json::json!(["adjacent"]) - ); - assert_eq!( - effect["clock_advances"]["items"]["properties"]["amount"]["minimum"], - 1 - ); - assert_eq!( - effect["clock_reductions"]["items"]["properties"]["amount"]["minimum"], - 1 - ); - assert_eq!( - effect["institution_postures"]["items"]["properties"]["posture"]["minLength"], - 1 - ); - assert_eq!( - effect["institution_postures"]["items"]["properties"]["posture"]["maxLength"], - MAX_POSTURE_CHARS - ); - assert_eq!( - effect["actor_relationship_updates"]["items"]["properties"]["relationship"]["minLength"], - 1 - ); - assert_eq!( - effect["actor_conditions"]["items"]["properties"]["condition"]["minLength"], - 1 - ); - let effect_text = serde_json::to_string(effect).unwrap(); - for erased_dynamic_map_keyword in ["propertyNames", "minProperties", "maxProperties"] { - assert!(!effect_text.contains(erased_dynamic_map_keyword)); - } - } - - #[test] - fn assessment_effect_schema_omits_unavailable_mutation_lanes() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - campaign.clocks.clear(); - campaign.institutions.clear(); - campaign.facts.clear(); - let actor_id = campaign.player_actor_id.clone(); - let location_id = campaign.actors[&actor_id].location_id.clone(); - campaign - .locations - .get_mut(&location_id) - .unwrap() - .routes - .clear(); - campaign - .actors - .get_mut(&actor_id) - .unwrap() - .knowledge - .clear(); - let acting = campaign.actors[&actor_id].clone(); - - let mut schema = serde_json::to_value(schema_for!(AssessmentProposal)).unwrap(); - constrain_assessment_schema(&mut schema, &BTreeSet::new(), &campaign, &acting).unwrap(); - project_effect_schema_to_mutation_entries(&mut schema, &campaign).unwrap(); - let effect = schema.pointer("/$defs/WorldEffectDelta").unwrap(); - let properties = effect["properties"].as_object().unwrap(); - - assert!(properties.contains_key("actor_conditions")); - assert!(properties.contains_key("actor_commitments")); - assert!(properties.contains_key("actor_observations")); - assert!(properties.contains_key("actor_relationship_updates")); - for unavailable in [ - "actor_knowledge_additions", - "actor_moves", - "clock_advances", - "clock_reductions", - "institution_postures", - ] { - assert!(!properties.contains_key(unavailable)); - assert!( - effect["required"] - .as_array() - .is_none_or(|required| required.iter().all(|value| value != unavailable)) - ); - } - let effect_contract = serde_json::json!({ - "$ref":"#/$defs/WorldEffectDelta", - "$defs":schema["$defs"].clone(), - }); - let validator = jsonschema::validator_for(&effect_contract).unwrap(); - assert!(validator.is_valid(&serde_json::json!({}))); - assert!(!validator.is_valid(&serde_json::json!({ - "actor_knowledge_additions":null - }))); - let decoded: WorldEffectDelta = serde_json::from_value(serde_json::json!({})).unwrap(); - assert_eq!(decoded, WorldEffectDelta::default()); - } - - #[test] - fn actor_commitment_entries_are_typed_and_contradictions_fail_closed() { - let decoded = decode_effect_entries(&serde_json::json!({ - "actor_commitments":[ - { - "actor_id":"target", - "operation":"add_obligation", - "description":"state concrete supervised-inspection terms" - }, - { - "actor_id":"target", - "operation":"add_goal", - "description":"review the seizure ledger" - } - ] - })) - .unwrap(); - assert!( - decoded.actor_commitments["target"] - .obligations_add - .contains("state concrete supervised-inspection terms") - ); - assert!( - decoded.actor_commitments["target"] - .goals_add - .contains("review the seizure ledger") - ); - - let error = decode_effect_entries(&serde_json::json!({ - "actor_commitments":[ - { - "actor_id":"target", - "operation":"add_obligation", - "description":"state concrete supervised-inspection terms" - }, - { - "actor_id":"target", - "operation":"retire_obligation", - "description":"state concrete supervised-inspection terms" - } - ] - })) - .unwrap_err() - .to_string(); - assert!(error.contains("both adds and retires")); - } - - #[test] - fn assessment_knowledge_schema_binds_exact_facts_per_recipient() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - campaign - .actors - .get_mut("player") - .unwrap() - .knowledge - .insert("The clinic director already knows the convoy is delayed.".into()); - let acting = campaign.actors["player"].clone(); - let mut nearby = acting.clone(); - nearby.id = "clinic-director".into(); - nearby.name = "Clinic Director".into(); - nearby.knowledge.clear(); - campaign.actors.insert(nearby.id.clone(), nearby); - campaign.facts.insert( - "cache".into(), - crate::domain::WorldFact { - id: "cache".into(), - statement: "The emergency cache is behind the north clinic wall.".into(), - scope: crate::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from([acting.location_id.clone()]), - }, - ); - campaign.facts.insert( - "delay".into(), - crate::domain::WorldFact { - id: "delay".into(), - statement: "The clinic director already knows the convoy is delayed.".into(), - scope: crate::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::new(), - }, - ); - - let mut schema = serde_json::to_value(schema_for!(AssessmentProposal)).unwrap(); - constrain_assessment_schema(&mut schema, &BTreeSet::new(), &campaign, &acting).unwrap(); - project_effect_schema_to_mutation_entries(&mut schema, &campaign).unwrap(); - let knowledge = schema - .pointer("/$defs/WorldEffectDelta/properties/actor_knowledge_additions") - .unwrap(); - let validator = jsonschema::validator_for(knowledge).unwrap(); - - assert!(validator.is_valid(&serde_json::json!([{ - "actor_id":"player", - "statement":"The emergency cache is behind the north clinic wall." - }]))); - assert!(validator.is_valid(&serde_json::json!([{ - "actor_id":"clinic-director", - "statement":"The clinic director already knows the convoy is delayed." - }]))); - assert!(!validator.is_valid(&serde_json::json!([{ - "actor_id":"clinic-director", - "statement":"The emergency cache is behind the north clinic wall." - }]))); - assert!(!validator.is_valid(&serde_json::json!([{ - "actor_id":"player", - "statement":"The clinic director already knows the convoy is delayed." - }]))); - } - - #[test] - fn bounded_observation_must_be_new_actor_local_and_visible() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - let acting = campaign.actors["player"].clone(); - let statement = "The regulator's left coupling carries the highest current thermal stress."; - let stake = format!("Observed finding: {statement}"); - let effect = decode_effect_entries(&serde_json::json!({ - "actor_observations":[{ - "actor_id":acting.id, - "statement":statement - }] - })) - .unwrap(); - - validate_effect(&campaign, &acting, &effect, &stake).unwrap(); - - campaign.facts.insert( - "already-known".into(), - crate::domain::WorldFact { - id: "already-known".into(), - statement: statement.into(), - scope: crate::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from([acting.location_id.clone()]), - }, - ); - assert!( - validate_effect(&campaign, &acting, &effect, &stake) - .unwrap_err() - .to_string() - .contains("branch-local findings") - ); - } - - #[test] - fn assessment_references_include_present_actors_but_not_remote_actors() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - let acting = campaign.actors["player"].clone(); - let mut nearby = acting.clone(); - nearby.id = "clinic-director".into(); - nearby.name = "Clinic Director".into(); - campaign.actors.insert(nearby.id.clone(), nearby); - campaign.locations.insert( - "remote".into(), - crate::domain::Location { - id: "remote".into(), - name: "Remote".into(), - container_id: None, - routes: Default::default(), - persistent_features: vec![], - }, - ); - let mut remote = acting.clone(); - remote.id = "remote-commander".into(); - remote.name = "Remote Commander".into(); - remote.location_id = "remote".into(); - campaign.actors.insert(remote.id.clone(), remote); - - let references = present_actor_references(&campaign, &acting); - assert!(references.contains("actor:player")); - assert!(references.contains("actor:clinic-director")); - assert!(!references.contains("actor:remote-commander")); - } - - #[test] - fn assessment_effect_rejects_a_relationship_to_an_unseen_remote_actor() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - let acting = campaign.actors["player"].clone(); - campaign.locations.insert( - "remote".into(), - crate::domain::Location { - id: "remote".into(), - name: "Remote".into(), - container_id: None, - routes: Default::default(), - persistent_features: vec![], - }, - ); - let mut remote = acting.clone(); - remote.id = "remote-commander".into(); - remote.name = "Remote Commander".into(); - remote.location_id = "remote".into(); - campaign.actors.insert(remote.id.clone(), remote); - let effect = WorldEffectDelta { - actor_relationship_updates: std::collections::BTreeMap::from([( - acting.id.clone(), - std::collections::BTreeMap::from([( - "remote-commander".into(), - "unexpected trust".into(), - )]), - )]), - ..WorldEffectDelta::default() - }; - - let error = validate_effect(&campaign, &acting, &effect, "nothing changes") - .unwrap_err() - .to_string(); - assert!(error.contains("unavailable target")); - } - - #[test] - fn assessment_effect_names_an_invalid_zero_clock_advance() { - let campaign = crate::resolution::tests::campaign(0, 1); - let acting = campaign.actors["player"].clone(); - let effect = WorldEffectDelta { - clock_advances: std::collections::BTreeMap::from([("missing-clock".into(), 0)]), - ..WorldEffectDelta::default() - }; - - let error = validate_effect(&campaign, &acting, &effect, "nothing changes") - .unwrap_err() - .to_string(); - assert!(error.contains("missing-clock=0")); - assert!(error.contains("at least one")); - } - - #[test] - fn assessment_effect_rejects_an_oversized_posture() { - let campaign = crate::resolution::tests::campaign(2, 1); - let acting = campaign.actors["player"].clone(); - let institution_id = campaign.institutions.keys().next().unwrap().clone(); - let effect = WorldEffectDelta { - institution_postures: std::collections::BTreeMap::from([( - institution_id, - "x".repeat(MAX_POSTURE_CHARS + 1), - )]), - ..WorldEffectDelta::default() - }; - - let error = validate_effect(&campaign, &acting, &effect, "nothing changes").unwrap_err(); - assert!(error.to_string().contains("one to 460 characters")); - } - - #[test] - fn assessment_effect_rejects_invalid_or_conflicting_clock_reduction() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - campaign.clocks.insert( - "clinic-failure".into(), - crate::domain::WorldClock { - id: "clinic-failure".into(), - label: "Clinic failure".into(), - progress: 3, - threshold: 4, - consequence: "The regulator fails.".into(), - consequence_scope: Default::default(), - }, - ); - let acting = campaign.actors["player"].clone(); - let invalid = WorldEffectDelta { - clock_reductions: std::collections::BTreeMap::from([("missing-clock".into(), 0)]), - ..WorldEffectDelta::default() - }; - let error = validate_effect(&campaign, &acting, &invalid, "nothing changes") - .unwrap_err() - .to_string(); - assert!(error.contains("missing-clock=0")); - assert!(error.contains("at least one")); - - let conflicting = WorldEffectDelta { - clock_advances: std::collections::BTreeMap::from([("clinic-failure".into(), 1)]), - clock_reductions: std::collections::BTreeMap::from([("clinic-failure".into(), 1)]), - ..WorldEffectDelta::default() - }; - let error = validate_effect(&campaign, &acting, &conflicting, "ambiguous change") - .unwrap_err() - .to_string(); - assert!(error.contains("both advance and reduce")); - assert!(error.contains("clinic-failure")); - } - - #[test] - fn assessment_rejects_noncanonical_dc() { - let mut value = proposal("equipment:key"); - value.dc = 17; - assert!(validate_proposal(&value, &BTreeSet::from(["equipment:key".into()])).is_err()); - } - - #[test] - fn inadmissible_assessment_cannot_smuggle_a_world_mutation() { - let mut value = proposal("equipment:key"); - value.admissible = false; - value.missing_permission = Some("No admitted route reaches that destination.".into()); - value - .success_effect - .actor_moves - .insert("player".into(), "elsewhere".into()); - - let error = validate_proposal(&value, &BTreeSet::from(["equipment:key".into()])) - .unwrap_err() - .to_string(); - assert!(error.contains("inadmissible assessment proposed a world mutation")); - } - - #[test] - fn npc_assessment_guidance_preserves_player_decision_authority() { - let guidance = action_agency_guidance(false); - assert!(guidance.contains("player retains authority")); - assert!(guidance.contains("response remains the player's next decision")); - assert!(!action_agency_guidance(true).contains("acting actor is an NPC")); - } - - #[test] - fn exact_knowledge_is_bound_into_visible_stakes_without_model_duplication() { - let finding = "The relay's backup cell is depleted.".to_string(); - let mut value = proposal("equipment:key"); - let additions = std::collections::BTreeMap::from([( - "player".into(), - BTreeSet::from([finding.clone()]), - )]); - value.strong_effect.actor_knowledge_additions = additions.clone(); - value.success_effect.actor_knowledge_additions = additions; - - bind_visible_effects(&mut value).unwrap(); - - assert!(value.success_stake.contains(&finding)); - assert_eq!(value.success_stake.matches(&finding).count(), 1); - } - - #[test] - fn fact_identifier_cannot_masquerade_as_character_knowledge() { - assert!(looks_like_identifier("fact_distress_relay_antenna_damaged")); - assert!(!looks_like_identifier( - "The distress relay's antenna array is damaged." - )); - } -} diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-agency-corpus.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-agency-corpus.rs deleted file mode 100644 index 46cc0ab..0000000 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-agency-corpus.rs +++ /dev/null @@ -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(()) -} diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-campaign-inspect.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-campaign-inspect.rs deleted file mode 100644 index 394e223..0000000 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-campaign-inspect.rs +++ /dev/null @@ -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 ")?; - 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.v1", &campaign_key)? - .context("campaign.v1 row disappeared during inspection")?; - let mut ticks = store.load_all::("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::("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::("cell_appraisal.v1")? - .into_iter() - .filter(|appraisal| { - appraisal.world_revision == revision && appraisal.resolution_epoch == epoch - }) - .collect::>(), - _ => 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::("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::("rejected_proposal_receipt.v1")?; - rejected.sort_by_key(|receipt| (receipt.revision, receipt.rejected_at)); - let rejected = rejected - .into_iter() - .rev() - .take(16) - .collect::>() - .into_iter() - .rev() - .collect::>(); - let mut presence = - store.load_all::("gestalt_materialization_receipt.v1")?; - presence.sort_by_key(|receipt| receipt.revision); - let presence = presence.into_iter().rev().take(16).collect::>(); - - 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::("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::>(), - })); - } - } - let recent_revision_bindings = (campaign.revision.saturating_sub(3)..=campaign.revision) - .map(|revision| format!("campaign:{}:revision:{revision}", campaign.id)) - .collect::>(); - let mut recent_model_receipts = store - .load_all::("persona_stage_receipt.v1")? - .into_iter() - .filter(|receipt| { - recent_revision_bindings - .iter() - .any(|binding| receipt.snapshot_binding.contains(binding)) - }) - .collect::>(); - recent_model_receipts.sort_by(|left, right| left.storage_key().cmp(right.storage_key())); - let mut newspaper_model_receipts = store - .load_all::("persona_stage_receipt.v1")? - .into_iter() - .filter(|receipt| receipt.stage.starts_with("newspaper_")) - .collect::>(); - newspaper_model_receipts.sort_by(|left, right| left.storage_key().cmp(right.storage_key())); - let assessment_mutation_scopes = - store.load_all::("assessment_mutation_scope_cache.v1")?; - let mut roll_receipts = store.load_all::("roll_receipt.v1")?; - roll_receipts.reverse(); - roll_receipts.truncate(16); - let mut commit_receipts = store.load_all::("world_commit_receipt.v1")?; - commit_receipts.sort_by_key(|receipt| receipt.revision); - let commit_receipts = commit_receipts - .into_iter() - .rev() - .take(16) - .collect::>(); - - 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::>()) - .unwrap_or_default(); - let events = campaign - .events - .iter() - .filter(|event| event_ids.contains(&event.id)) - .collect::>(); - let news = campaign - .news - .iter() - .filter(|issue| issue.event_ids.iter().any(|id| event_ids.contains(id))) - .collect::>(); - - 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::>(), - "recentWorldEvents": campaign.events.iter().rev().take(24).collect::>(), - "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::>(), - }))? - ); - Ok(()) -} diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-mesh-inspect.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-mesh-inspect.rs deleted file mode 100644 index 4500a36..0000000 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-mesh-inspect.rs +++ /dev/null @@ -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 ")?; - let campaign_id = args - .next() - .context("usage: ghostlight-mesh-inspect ")? - .parse::() - .context("campaign-id must be a UUID")?; - if args.next().is_some() { - anyhow::bail!("usage: ghostlight-mesh-inspect "); - } - - 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(()) -} diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-native-client.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-native-client.rs deleted file mode 100644 index dc23322..0000000 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-native-client.rs +++ /dev/null @@ -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, - session_token: Option, - refresh_expires_at: Option, - 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, - refresh_expires_at: Option, -} - -struct ClientStore { - store: CampaignStore, - row: Option, - state: NativeClientState, - path: PathBuf, -} - -impl ClientStore { - fn open(path: impl AsRef) -> Result { - 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::("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 "); - } - let session = state - .state - .session_token - .as_deref() - .context("Native Ghostlight client is not authenticated")?; - let source_version = rest[2].parse::()?; - 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)> { - let mut args = std::env::args().skip(1).collect::>(); - 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 is required")?; - let command = args.first().cloned().context( - "usage: ghostlight-native-client --state [--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 { - 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( - endpoint: SocketAddr, - operation: &str, - payload_schema: &str, - payload: &impl Serialize, -) -> Result { - 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); - } -} diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-provider-health-identity.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-provider-health-identity.rs deleted file mode 100644 index 9ffcf10..0000000 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-provider-health-identity.rs +++ /dev/null @@ -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 "); - } - let path = path.expect("validated above"); - let signer = if action == "enroll" { - enroll_service_identity_at::(&path)? - } else { - open_service_identity_at::(&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 -} diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-session-zero-inspect.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-session-zero-inspect.rs deleted file mode 100644 index 973dd55..0000000 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-session-zero-inspect.rs +++ /dev/null @@ -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 [receipt-limit]")?; - let limit = arguments - .next() - .map(|value| value.parse::()) - .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::("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::>(); - 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::>(), - }) - }) - .collect::>(); - - 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(()) -} diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-world-explore.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-world-explore.rs deleted file mode 100644 index 5f32956..0000000 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-world-explore.rs +++ /dev/null @@ -1,1033 +0,0 @@ -use anyhow::{Context, Result, bail}; -use ghostlight_dungeon::{domain::Campaign, persistence::CampaignStore}; -use serde_json::{Value, json}; -use std::collections::{BTreeMap, BTreeSet}; - -fn main() -> Result<()> { - let mut args = std::env::args().skip(1); - let store_path = args.next().context( - "usage: ghostlight-world-explore [query]", - )?; - let command = args.next().unwrap_or_else(|| "overview".into()); - let operand = args.next(); - if args.next().is_some() { - bail!("too many arguments"); - } - - let campaign = load_campaign(&store_path)?; - let output = match command.as_str() { - "overview" => overview(&campaign), - "quality" => quality(&campaign), - "search" => search( - &campaign, - operand - .as_deref() - .context("search requires one case-insensitive query")?, - ), - "region" => region( - &campaign, - operand - .as_deref() - .context("region requires one exact location ID")?, - )?, - "subject" => subject( - &campaign, - operand - .as_deref() - .context("subject requires one exact subject ID")?, - )?, - other => bail!( - "unknown command {other:?}; expected overview, quality, search, region, or subject" - ), - }; - println!("{}", serde_json::to_string_pretty(&output)?); - Ok(()) -} - -fn normalized_text(value: &str) -> String { - value - .chars() - .filter(|character| character.is_alphanumeric()) - .flat_map(char::to_lowercase) - .collect() -} - -fn terminal_name_token(value: &str) -> String { - value - .split(|character: char| !character.is_alphanumeric()) - .filter(|token| !token.is_empty()) - .last() - .map(normalized_text) - .unwrap_or_default() -} - -fn duplicate_groups(entries: impl IntoIterator) -> Value { - let mut groups: BTreeMap> = BTreeMap::new(); - for (key, id) in entries { - if !key.is_empty() { - groups.entry(key).or_default().push(id); - } - } - let mut groups = groups - .into_iter() - .filter(|(_, ids)| ids.len() > 1) - .map(|(key, mut ids)| { - ids.sort(); - let count = ids.len(); - ids.truncate(20); - json!({"key":key,"count":count,"subjectIdSample":ids}) - }) - .collect::>(); - groups.sort_by(|left, right| { - right["count"] - .as_u64() - .cmp(&left["count"].as_u64()) - .then_with(|| left["key"].as_str().cmp(&right["key"].as_str())) - }); - let group_count = groups.len(); - let occurrence_count = groups - .iter() - .filter_map(|group| group["count"].as_u64()) - .sum::(); - let member_sample_truncated = groups.iter().any(|group| { - group["count"].as_u64().unwrap_or(0) - > group["subjectIdSample"] - .as_array() - .map_or(0, |sample| sample.len()) as u64 - }); - groups.truncate(20); - json!({ - "groupCount":group_count, - "occurrenceCount":occurrence_count, - "groupsSample":groups, - "truncated":group_count > 20 || member_sample_truncated, - "groupSampleLimit":20, - "subjectIdSampleLimitPerGroup":20, - }) -} - -fn gestalt_semantic_key(gestalt: &ghostlight_dungeon::domain::GestaltPersonaState) -> String { - serde_json::to_string(&( - &gestalt.shared_capabilities, - &gestalt.shared_knowledge, - &gestalt.goals, - &gestalt.pressures, - )) - .unwrap_or_default() -} - -fn lineage_depth(campaign: &Campaign, subject_id: &str) -> usize { - let mut depth = 0; - let mut current = subject_id; - let mut visited = BTreeSet::new(); - while visited.insert(current.to_owned()) { - let Some(parent) = campaign - .agency_profiles - .get(current) - .and_then(|profile| profile.parent_subject_id.as_deref()) - else { - break; - }; - depth += 1; - current = parent; - } - depth -} - -fn repeated_texts<'a>(values: impl IntoIterator) -> Value { - duplicate_groups( - values - .into_iter() - .map(|(id, value)| (normalized_text(value), id.to_owned())), - ) -} - -fn has_structurally_complete_named_person_shape( - has_goal: bool, - has_memory: bool, - has_detail_state: bool, -) -> bool { - has_goal && has_memory && has_detail_state -} - -fn quality(campaign: &Campaign) -> Value { - let residual_ids = campaign - .gestalt_lineages - .values() - .map(|lineage| lineage.residual_child_id.clone()) - .collect::>(); - let raw_actionable_ids = campaign - .agency_profiles - .values() - .filter(|profile| profile.active_leaf && profile.simulation_eligible) - .map(|profile| profile.subject_id.clone()) - .collect::>(); - let qualified_ids = ghostlight_dungeon::elaboration::canonical_actionable_subject_ids(campaign); - let qualified_count = - ghostlight_dungeon::elaboration::canonical_actionable_subject_count(campaign); - let twenty_percent_target = u32::from(campaign.resolution_policy.active_cell_budget) * 5; - let qualified_target_delta = i64::from(twenty_percent_target) - i64::from(qualified_count); - - let materialized_member_actor_ids = campaign - .gestalt_members - .values() - .flat_map(|member| { - member - .materialized_actor_id - .iter() - .cloned() - .chain(std::iter::once(format!("member:{}", member.id))) - }) - .collect::>(); - let person_name_records = campaign - .actors - .values() - .filter(|actor| { - actor.id != campaign.player_actor_id - && !materialized_member_actor_ids.contains(&actor.id) - }) - .map(|actor| (actor.name.clone(), format!("actor:{}", actor.id))) - .chain( - campaign - .gestalt_members - .values() - .map(|member| (member.name.clone(), format!("member:{}", member.id))), - ) - .collect::>(); - let population_name_records = campaign - .gestalts - .values() - .filter(|gestalt| qualified_ids.contains(&gestalt.id)) - .map(|gestalt| (gestalt.name.clone(), gestalt.id.clone())) - .collect::>(); - let invalid_person_identity_ids = person_name_records - .iter() - .filter(|(name, _)| normalized_text(name).is_empty()) - .map(|(_, id)| id.clone()) - .collect::>(); - let invalid_population_identity_ids = population_name_records - .iter() - .filter(|(name, _)| normalized_text(name).is_empty()) - .map(|(_, id)| id.clone()) - .collect::>(); - let duplicate_person_names = duplicate_groups( - person_name_records - .iter() - .map(|(name, id)| (normalized_text(name), id.clone())), - ); - let duplicate_population_names = duplicate_groups( - population_name_records - .iter() - .map(|(name, id)| (normalized_text(name), id.clone())), - ); - let repeated_person_terminal_tokens = duplicate_groups( - person_name_records - .iter() - .map(|(name, id)| (terminal_name_token(name), id.clone())), - ); - let repeated_population_terminal_tokens = duplicate_groups( - population_name_records - .iter() - .map(|(name, id)| (terminal_name_token(name), id.clone())), - ); - - // This is a structural record-shape count, not a judgment of semantic quality. - // A counted standalone actor has at least one goal, at least one memory, and at - // least one capability, knowledge item, equipment item, condition, obligation, - // or relationship. The player and actor projections of gestalt members are - // excluded. A counted gestalt member has at least one goal, at least one memory, - // and at least one capability addition, knowledge addition, equipment item, - // condition, obligation, or relationship. Naming validity is measured separately. - let structurally_complete_actor_count = campaign - .actors - .values() - .filter(|actor| { - actor.id != campaign.player_actor_id - && !materialized_member_actor_ids.contains(&actor.id) - }) - .filter(|actor| { - has_structurally_complete_named_person_shape( - !actor.goals.is_empty(), - !actor.memories.is_empty(), - !actor.capabilities.is_empty() - || !actor.knowledge.is_empty() - || !actor.equipment.is_empty() - || !actor.conditions.is_empty() - || !actor.obligations.is_empty() - || !actor.relationships.is_empty(), - ) - }) - .count(); - let structurally_complete_member_count = campaign - .gestalt_members - .values() - .filter(|member| { - has_structurally_complete_named_person_shape( - !member.goals.is_empty(), - !member.memories.is_empty(), - !member.capability_additions.is_empty() - || !member.knowledge_additions.is_empty() - || !member.equipment.is_empty() - || !member.conditions.is_empty() - || !member.obligations.is_empty() - || !member.relationships.is_empty(), - ) - }) - .count(); - let actor_person_count = campaign - .actors - .values() - .filter(|actor| { - actor.id != campaign.player_actor_id - && !materialized_member_actor_ids.contains(&actor.id) - }) - .count(); - let named_person_count = actor_person_count + campaign.gestalt_members.len(); - - let qualified_gestalts = campaign - .gestalts - .values() - .filter(|gestalt| qualified_ids.contains(&gestalt.id)) - .collect::>(); - let semantic_clone_groups = duplicate_groups( - qualified_gestalts - .iter() - .map(|gestalt| (gestalt_semantic_key(gestalt), gestalt.id.clone())), - ); - let repeated_goals = repeated_texts(qualified_gestalts.iter().flat_map(|gestalt| { - gestalt - .goals - .iter() - .map(|value| (gestalt.id.as_str(), value)) - })); - let repeated_pressures = repeated_texts(qualified_gestalts.iter().flat_map(|gestalt| { - gestalt - .pressures - .iter() - .map(|value| (gestalt.id.as_str(), value)) - })); - let direct_fission_deltas = qualified_gestalts - .iter() - .filter_map(|gestalt| { - let parent_id = campaign - .agency_profiles - .get(&gestalt.id)? - .parent_subject_id - .as_ref()?; - let parent = campaign.gestalts.get(parent_id)?; - Some(( - gestalt.id.as_str(), - gestalt - .shared_capabilities - .difference(&parent.shared_capabilities) - .cloned() - .collect::>(), - gestalt - .shared_knowledge - .difference(&parent.shared_knowledge) - .cloned() - .collect::>(), - gestalt - .goals - .iter() - .filter(|goal| !parent.goals.contains(goal)) - .cloned() - .collect::>(), - gestalt - .pressures - .iter() - .filter(|pressure| !parent.pressures.contains(pressure)) - .cloned() - .collect::>(), - )) - }) - .collect::>(); - let repeated_direct_added_goals = repeated_texts( - direct_fission_deltas - .iter() - .flat_map(|(id, _, _, goals, _)| goals.iter().map(|value| (*id, value))), - ); - let repeated_direct_added_pressures = repeated_texts( - direct_fission_deltas - .iter() - .flat_map(|(id, _, _, _, pressures)| pressures.iter().map(|value| (*id, value))), - ); - let exact_direct_delta_clone_groups = duplicate_groups(direct_fission_deltas.iter().map( - |(id, capabilities, knowledge, goals, pressures)| { - ( - serde_json::to_string(&(capabilities, knowledge, goals, pressures)) - .unwrap_or_default(), - (*id).to_owned(), - ) - }, - )); - - let mut raw_relation_degrees = qualified_ids - .iter() - .map(|id| (id.clone(), 0usize)) - .collect::>(); - let mut non_inherited_relation_degrees = raw_relation_degrees.clone(); - let mut raw_relation_kind_counts = BTreeMap::::new(); - let mut non_inherited_relation_kind_counts = BTreeMap::::new(); - let mut mechanically_inherited_relation_count = 0usize; - for relation in campaign - .agency_relations - .values() - .filter(|relation| relation.active) - { - if let Some(degree) = raw_relation_degrees.get_mut(&relation.from_subject_id) { - *degree += 1; - } - if let Some(degree) = raw_relation_degrees.get_mut(&relation.to_subject_id) { - *degree += 1; - } - let kind = format!("{:?}", relation.kind).to_lowercase(); - *raw_relation_kind_counts.entry(kind.clone()).or_default() += 1; - if relation.id.contains(":fission:") { - mechanically_inherited_relation_count += 1; - continue; - } - if let Some(degree) = non_inherited_relation_degrees.get_mut(&relation.from_subject_id) { - *degree += 1; - } - if let Some(degree) = non_inherited_relation_degrees.get_mut(&relation.to_subject_id) { - *degree += 1; - } - *non_inherited_relation_kind_counts.entry(kind).or_default() += 1; - } - let mut individual_relationship_entries = 0usize; - let mut record_individual_relationship = |from_subject_id: &str, to_subject_id: &str| { - individual_relationship_entries += 1; - if let Some(degree) = raw_relation_degrees.get_mut(from_subject_id) { - *degree += 1; - } - if let Some(degree) = raw_relation_degrees.get_mut(to_subject_id) { - *degree += 1; - } - if let Some(degree) = non_inherited_relation_degrees.get_mut(from_subject_id) { - *degree += 1; - } - if let Some(degree) = non_inherited_relation_degrees.get_mut(to_subject_id) { - *degree += 1; - } - *raw_relation_kind_counts - .entry("individual_relationship".into()) - .or_default() += 1; - *non_inherited_relation_kind_counts - .entry("individual_relationship".into()) - .or_default() += 1; - }; - for actor in campaign.actors.values() { - for other_subject_id in actor.relationships.keys() { - record_individual_relationship(&actor.id, other_subject_id); - } - } - for member in campaign.gestalt_members.values() { - let default_actor_id = ghostlight_dungeon::domain::gestalt_member_subject_id(&member.id); - let projected_actor_exists = campaign.actors.contains_key(&default_actor_id) - || member - .materialized_actor_id - .as_ref() - .is_some_and(|actor_id| campaign.actors.contains_key(actor_id)); - if projected_actor_exists { - continue; - } - for other_subject_id in member.relationships.keys() { - record_individual_relationship(&default_actor_id, other_subject_id); - } - } - let raw_isolated_subject_ids = raw_relation_degrees - .iter() - .filter(|(_, degree)| **degree == 0) - .map(|(id, _)| id.clone()) - .collect::>(); - let non_inherited_isolated_subject_ids = non_inherited_relation_degrees - .iter() - .filter(|(_, degree)| **degree == 0) - .map(|(id, _)| id.clone()) - .collect::>(); - let raw_degree_sum = raw_relation_degrees.values().sum::(); - let non_inherited_degree_sum = non_inherited_relation_degrees.values().sum::(); - - let civic_signatures = duplicate_groups(campaign.civic_systems.values().map(|civic| { - let institutions = civic - .governing_institution_ids - .iter() - .filter_map(|id| campaign.institutions.get(id)) - .map(|institution| { - ( - normalized_text(&institution.posture), - institution - .goals - .iter() - .map(|value| normalized_text(value)) - .collect::>(), - institution - .resources - .iter() - .map(|value| normalized_text(value)) - .collect::>(), - ) - }) - .collect::>(); - let residents = civic - .resident_population_ids - .iter() - .filter_map(|id| campaign.gestalts.get(id)) - .map(gestalt_semantic_key) - .collect::>(); - ( - serde_json::to_string(&(institutions, residents)).unwrap_or_default(), - civic.jurisdiction_location_id.clone(), - ) - })); - - let event_kind_counts = - campaign - .events - .iter() - .fold(BTreeMap::::new(), |mut counts, event| { - *counts.entry(event.kind.clone()).or_default() += 1; - counts - }); - let repeated_event_summaries = duplicate_groups( - campaign - .events - .iter() - .map(|event| (normalized_text(&event.summary), event.id.clone())), - ); - let distribution_by_root = campaign - .locations - .values() - .filter(|location| location.container_id.is_none()) - .map(|location| { - let places = descendant_location_ids(campaign, &location.id); - let count = qualified_ids - .iter() - .filter(|id| { - campaign - .agency_profiles - .get(*id) - .is_some_and(|profile| !profile.location_ids.is_disjoint(&places)) - }) - .count(); - (location.id.clone(), count) - }) - .collect::>(); - let spread_by_jurisdiction = campaign - .civic_systems - .keys() - .filter(|location_id| campaign.locations.contains_key(*location_id)) - .map(|location_id| { - let places = descendant_location_ids(campaign, location_id); - let location_counts = places - .iter() - .map(|place_id| { - let count = qualified_ids - .iter() - .filter(|id| { - campaign - .agency_profiles - .get(*id) - .is_some_and(|profile| profile.location_ids.contains(place_id)) - }) - .count(); - (place_id.clone(), count) - }) - .collect::>(); - let occupied_location_count = location_counts - .values() - .filter(|count| **count > 0) - .count(); - let location_assignment_count = location_counts.values().sum::(); - let largest_location_count = location_counts.values().copied().max().unwrap_or(0); - ( - location_id.clone(), - json!({ - "qualifiedSubjects":qualified_ids.iter().filter(|id|campaign.agency_profiles.get(*id).is_some_and(|profile|!profile.location_ids.is_disjoint(&places))).count(), - "occupiedLocationCount":occupied_location_count, - "locationAssignmentCount":location_assignment_count, - "largestLocationShareBasisPoints":if location_assignment_count == 0 { None } else { Some(largest_location_count * 10_000 / location_assignment_count) }, - "qualifiedSubjectCountsByLocation":location_counts, - }), - ) - }) - .collect::>(); - let occupied_location_count = campaign - .locations - .keys() - .filter(|location_id| { - qualified_ids.iter().any(|id| { - campaign - .agency_profiles - .get(id) - .is_some_and(|profile| profile.location_ids.contains(*location_id)) - }) - }) - .count(); - - json!({ - "schema":"ghostlight.world_quality.v1", - "campaign":{"id":campaign.id,"revision":campaign.revision,"strategicTickCount":campaign.strategic_tick_count}, - "scale":{ - "rawActionableSubjects":raw_actionable_ids.len(), - "qualifiedActionableSubjects":qualified_count, - "residualActionableSubjects":raw_actionable_ids.intersection(&residual_ids).count(), - "twentyPercentTarget":twenty_percent_target, - "qualifiedTargetDelta":qualified_target_delta, - "qualifiedCoverBasisPoints":if qualified_count == 0 { None } else { Some(u32::from(campaign.resolution_policy.active_cell_budget) * 10_000 / qualified_count) }, - "rawCoverBasisPoints":if raw_actionable_ids.is_empty() { None } else { Some(usize::from(campaign.resolution_policy.active_cell_budget) * 10_000 / raw_actionable_ids.len()) }, - "maximumQualifiedLineageDepth":qualified_ids.iter().map(|id|lineage_depth(campaign,id)).max().unwrap_or(0), - "qualifiedDistributionByRootLocation":distribution_by_root, - "occupiedLocationCount":occupied_location_count, - "qualifiedSpreadByJurisdiction":spread_by_jurisdiction, - "geographyFissionCount":campaign.gestalt_lineages.values().filter(|lineage|lineage.partition_axis == ghostlight_dungeon::domain::AgencyAxis::Geography).count(), - }, - "identity":{ - "namedPersons":named_person_count, - "structurallyCompleteNamedPersons":structurally_complete_actor_count + structurally_complete_member_count, - "invalidPublicPersonIdentityIds":invalid_person_identity_ids, - "invalidQualifiedPopulationIdentityIds":invalid_population_identity_ids, - "duplicatePersonNames":duplicate_person_names, - "duplicateQualifiedPopulationNames":duplicate_population_names, - "repeatedPersonTerminalNameTokens":repeated_person_terminal_tokens, - "repeatedQualifiedPopulationTerminalNameTokens":repeated_population_terminal_tokens, - "lexicalDiagnosticsOnly":true, - }, - "causality":{ - "qualifiedGestalts":qualified_gestalts.len(), - "qualifiedGestaltsWithoutGoals":qualified_gestalts.iter().filter(|gestalt|gestalt.goals.is_empty()).count(), - "qualifiedGestaltsWithoutPressures":qualified_gestalts.iter().filter(|gestalt|gestalt.pressures.is_empty()).count(), - "qualifiedGestaltsWithoutCapabilities":qualified_gestalts.iter().filter(|gestalt|gestalt.shared_capabilities.is_empty()).count(), - "qualifiedGestaltsWithoutKnowledge":qualified_gestalts.iter().filter(|gestalt|gestalt.shared_knowledge.is_empty()).count(), - "inheritanceInclusiveExactSemanticCloneGroups":semantic_clone_groups, - "inheritanceInclusiveRepeatedGoals":repeated_goals, - "inheritanceInclusiveRepeatedPressures":repeated_pressures, - "exactDirectFissionDeltaCloneGroups":exact_direct_delta_clone_groups, - "repeatedDirectAddedGoals":repeated_direct_added_goals, - "repeatedDirectAddedPressures":repeated_direct_added_pressures, - }, - "relationships":{ - "collectiveAgencyActiveRelations":campaign.agency_relations.values().filter(|relation|relation.active).count(), - "individualRelationshipEntries":individual_relationship_entries, - "rawActiveRelationshipEntries":campaign.agency_relations.values().filter(|relation|relation.active).count() + individual_relationship_entries, - "estimatedMechanicallyInheritedFissionRelationsByIdConvention":mechanically_inherited_relation_count, - "nonInheritedActiveRelationshipEntries":campaign.agency_relations.values().filter(|relation|relation.active && !relation.id.contains(":fission:")).count() + individual_relationship_entries, - "rawRelationKindCounts":raw_relation_kind_counts, - "nonInheritedRelationKindCounts":non_inherited_relation_kind_counts, - "rawIsolatedQualifiedSubjects":raw_isolated_subject_ids.len(), - "rawIsolatedQualifiedSubjectSample":raw_isolated_subject_ids.into_iter().take(50).collect::>(), - "nonInheritedIsolatedQualifiedSubjects":non_inherited_isolated_subject_ids.len(), - "nonInheritedIsolatedQualifiedSubjectSample":non_inherited_isolated_subject_ids.into_iter().take(50).collect::>(), - "rawMeanQualifiedDegree":if raw_relation_degrees.is_empty() { 0.0 } else { raw_degree_sum as f64 / raw_relation_degrees.len() as f64 }, - "nonInheritedMeanQualifiedDegree":if non_inherited_relation_degrees.is_empty() { 0.0 } else { non_inherited_degree_sum as f64 / non_inherited_relation_degrees.len() as f64 }, - "inheritanceClassification":"estimate based on the current :fission: relation-ID convention; authored IDs can confound it", - }, - "politics":{ - "civicJurisdictions":campaign.civic_systems.len(), - "exactCivicSignatureCloneGroups":civic_signatures, - "exactSignatureDiagnosticsDoNotMeasureSemanticPoliticalDiversity":true, - }, - "behavior":{ - "eventKindCounts":event_kind_counts, - "exactRepeatedEventSummaryGroups":repeated_event_summaries, - "newsIssues":campaign.news.len(), - "exactSummaryDiagnosticsDoNotMeasureSemanticDramaticDiversity":true, - }, - }) -} - -fn load_campaign(path: &str) -> Result { - let store = CampaignStore::open(path)?; - let key = store - .keys("campaign.v1")? - .into_iter() - .next() - .context("store contains no campaign.v1 state")?; - store - .load::("campaign.v1", &key)? - .map(|(_, campaign)| campaign) - .context("campaign.v1 row disappeared during inspection") -} - -fn overview(campaign: &Campaign) -> Value { - let roots = campaign - .locations - .values() - .filter(|location| location.container_id.is_none()) - .map(|location| location_summary(campaign, &location.id)) - .collect::>(); - let civic_jurisdictions = campaign - .civic_systems - .values() - .map(|civic| { - json!({ - "locationId": civic.jurisdiction_location_id, - "locationName": location_name(campaign, &civic.jurisdiction_location_id), - "governingInstitutions": civic.governing_institution_ids.iter().map(|id| json!({ - "id": id, - "name": campaign.institutions.get(id).map(|institution| institution.name.as_str()), - })).collect::>(), - "residentPopulationCount": civic.resident_population_ids.len(), - }) - }) - .collect::>(); - json!({ - "schema": "ghostlight.world_exploration.v1", - "campaign": { - "id": campaign.id, - "name": campaign.name, - "revision": campaign.revision, - "worldTime": campaign.world_time, - "resolutionEpoch": campaign.resolution_policy.resolution_epoch, - "activeCellBudget": campaign.resolution_policy.active_cell_budget, - }, - "counts": { - "locations": campaign.locations.len(), - "actors": campaign.actors.len(), - "institutions": campaign.institutions.len(), - "gestalts": campaign.gestalts.len(), - "gestaltMembers": campaign.gestalt_members.len(), - "facts": campaign.facts.len(), - "clocks": campaign.clocks.len(), - "agencyRelations": campaign.agency_relations.len(), - "civicSystems": campaign.civic_systems.len(), - }, - "rootLocations": roots, - "civicJurisdictions": civic_jurisdictions, - "clocks": campaign.clocks, - }) -} - -fn location_summary(campaign: &Campaign, location_id: &str) -> Value { - let location = &campaign.locations[location_id]; - let descendants = descendant_location_ids(campaign, location_id); - let subject_counts = subject_counts_in_locations(campaign, &descendants); - json!({ - "id": location.id, - "name": location.name, - "containerId": location.container_id, - "persistentFeatures": location.persistent_features, - "directChildren": campaign.locations.values().filter(|candidate| candidate.container_id.as_deref() == Some(location_id)).map(|candidate| json!({"id":candidate.id,"name":candidate.name})).collect::>(), - "descendantLocationCount": descendants.len().saturating_sub(1), - "subjectCounts": subject_counts, - }) -} - -fn search(campaign: &Campaign, query: &str) -> Value { - let needle = query.to_lowercase(); - let mut matches = Vec::new(); - for location in campaign.locations.values() { - push_match( - &mut matches, - &needle, - "location", - &location.id, - &location.name, - json!(location), - ); - } - for actor in campaign.actors.values() { - push_match( - &mut matches, - &needle, - "actor", - &actor.id, - &actor.name, - json!(actor), - ); - } - for institution in campaign.institutions.values() { - push_match( - &mut matches, - &needle, - "institution", - &institution.id, - &institution.name, - json!(institution), - ); - } - for gestalt in campaign.gestalts.values() { - push_match( - &mut matches, - &needle, - "gestalt", - &gestalt.id, - &gestalt.name, - json!(gestalt), - ); - } - for member in campaign.gestalt_members.values() { - push_match( - &mut matches, - &needle, - "gestalt_member", - &member.id, - &member.name, - json!(member), - ); - } - for fact in campaign.facts.values() { - push_match( - &mut matches, - &needle, - "fact", - &fact.id, - &fact.statement, - json!(fact), - ); - } - for clock in campaign.clocks.values() { - push_match( - &mut matches, - &needle, - "clock", - &clock.id, - &clock.label, - json!(clock), - ); - } - let total_match_count = matches.len(); - matches.truncate(200); - json!({ - "schema": "ghostlight.world_search.v1", - "query": query, - "totalMatchCount": total_match_count, - "returnedMatchCount": matches.len(), - "truncated": total_match_count > matches.len(), - "matches": matches, - }) -} - -fn push_match( - matches: &mut Vec, - needle: &str, - kind: &str, - id: &str, - label: &str, - value: Value, -) { - let haystack = value.to_string().to_lowercase(); - if haystack.contains(needle) { - matches.push(json!({"kind": kind, "id": id, "label": label, "value": value})); - } -} - -fn region(campaign: &Campaign, location_id: &str) -> Result { - if !campaign.locations.contains_key(location_id) { - bail!("unknown location ID {location_id:?}"); - } - let location_ids = descendant_location_ids(campaign, location_id); - let subject_ids = subject_ids_in_locations(campaign, &location_ids); - let locations = location_ids - .iter() - .map(|id| (id.clone(), json!(&campaign.locations[id]))) - .collect::>(); - let subjects = subject_ids - .iter() - .filter_map(|id| subject_value(campaign, id).map(|value| (id.clone(), value))) - .collect::>(); - let relations = campaign - .agency_relations - .values() - .filter(|relation| { - subject_ids.contains(&relation.from_subject_id) - || subject_ids.contains(&relation.to_subject_id) - }) - .collect::>(); - let civic_systems = campaign - .civic_systems - .values() - .filter(|civic| location_ids.contains(&civic.jurisdiction_location_id)) - .collect::>(); - let facts = campaign - .facts - .values() - .filter(|fact| { - let serialized = serde_json::to_string(fact).unwrap_or_default(); - location_ids.iter().any(|id| serialized.contains(id)) - || subject_ids.iter().any(|id| serialized.contains(id)) - }) - .collect::>(); - Ok(json!({ - "schema": "ghostlight.world_region.v1", - "root": location_summary(campaign, location_id), - "locations": locations, - "subjects": subjects, - "relations": relations, - "civicSystems": civic_systems, - "facts": facts, - })) -} - -fn subject(campaign: &Campaign, subject_id: &str) -> Result { - let value = subject_value(campaign, subject_id) - .with_context(|| format!("unknown subject ID {subject_id:?}"))?; - let relations = campaign - .agency_relations - .values() - .filter(|relation| { - relation.from_subject_id == subject_id || relation.to_subject_id == subject_id - }) - .collect::>(); - Ok(json!({ - "schema": "ghostlight.world_subject.v1", - "subject": value, - "relations": relations, - })) -} - -fn subject_value(campaign: &Campaign, subject_id: &str) -> Option { - if let Some(actor) = campaign.actors.get(subject_id) { - return Some( - json!({"kind":"actor", "state":actor, "agency":campaign.agency_profiles.get(subject_id)}), - ); - } - if let Some(institution) = campaign.institutions.get(subject_id) { - return Some( - json!({"kind":"institution", "state":institution, "agency":campaign.agency_profiles.get(subject_id)}), - ); - } - if let Some(gestalt) = campaign.gestalts.get(subject_id) { - return Some( - json!({"kind":"gestalt", "state":gestalt, "agency":campaign.agency_profiles.get(subject_id), "lineage":campaign.gestalt_lineages.get(subject_id)}), - ); - } - let member_id = subject_id.strip_prefix("member:").unwrap_or(subject_id); - campaign.gestalt_members.get(member_id).map(|member| { - json!({"kind":"gestalt_member", "state":member, "parent":campaign.gestalts.get(&member.gestalt_id)}) - }) -} - -fn descendant_location_ids(campaign: &Campaign, root_id: &str) -> BTreeSet { - let mut ids = BTreeSet::from([root_id.to_owned()]); - loop { - let before = ids.len(); - for location in campaign.locations.values() { - if location - .container_id - .as_ref() - .is_some_and(|container| ids.contains(container)) - { - ids.insert(location.id.clone()); - } - } - if ids.len() == before { - return ids; - } - } -} - -fn subject_ids_in_locations( - campaign: &Campaign, - location_ids: &BTreeSet, -) -> BTreeSet { - let mut ids = BTreeSet::new(); - for actor in campaign.actors.values() { - if location_ids.contains(&actor.location_id) { - ids.insert(actor.id.clone()); - } - } - for gestalt in campaign.gestalts.values() { - if location_ids.contains(&gestalt.home_location_id) { - ids.insert(gestalt.id.clone()); - } - } - for (id, profile) in &campaign.agency_profiles { - if !profile.location_ids.is_disjoint(location_ids) { - ids.insert(id.clone()); - } - } - for member in campaign.gestalt_members.values() { - if ids.contains(&member.gestalt_id) - || member - .last_location_id - .as_ref() - .is_some_and(|id| location_ids.contains(id)) - { - ids.insert(format!("member:{}", member.id)); - } - } - ids -} - -fn subject_counts_in_locations( - campaign: &Campaign, - location_ids: &BTreeSet, -) -> BTreeMap<&'static str, usize> { - let ids = subject_ids_in_locations(campaign, location_ids); - let mut counts = BTreeMap::from([ - ("actors", 0), - ("institutions", 0), - ("gestalts", 0), - ("gestaltMembers", 0), - ]); - for id in ids { - if id.starts_with("member:") { - counts - .entry("gestaltMembers") - .and_modify(|count| *count += 1); - } else if campaign.actors.contains_key(&id) { - counts.entry("actors").and_modify(|count| *count += 1); - } else if campaign.institutions.contains_key(&id) { - counts.entry("institutions").and_modify(|count| *count += 1); - } else if campaign.gestalts.contains_key(&id) { - counts.entry("gestalts").and_modify(|count| *count += 1); - } - } - counts -} - -fn location_name<'a>(campaign: &'a Campaign, id: &str) -> Option<&'a str> { - campaign - .locations - .get(id) - .map(|location| location.name.as_str()) -} - -#[cfg(test)] -mod tests { - use super::{duplicate_groups, has_structurally_complete_named_person_shape}; - - #[test] - fn named_person_structural_completeness_requires_goal_memory_and_detail_state() { - assert!(has_structurally_complete_named_person_shape( - true, true, true - )); - assert!(!has_structurally_complete_named_person_shape( - false, true, true - )); - assert!(!has_structurally_complete_named_person_shape( - true, false, true - )); - assert!(!has_structurally_complete_named_person_shape( - true, true, false - )); - } - - #[test] - fn duplicate_report_preserves_complete_prevalence_while_sampling_large_results() { - let mut entries = (0..25) - .map(|index| ("shared".to_owned(), format!("shared-{index:02}"))) - .collect::>(); - for group in 0..21 { - entries.push((format!("group-{group:02}"), format!("group-{group:02}-a"))); - entries.push((format!("group-{group:02}"), format!("group-{group:02}-b"))); - } - - let report = duplicate_groups(entries); - - assert_eq!(report["groupCount"], 22); - assert_eq!(report["occurrenceCount"], 67); - assert_eq!(report["groupsSample"].as_array().unwrap().len(), 20); - assert_eq!(report["groupsSample"][0]["count"], 25); - assert_eq!( - report["groupsSample"][0]["subjectIdSample"] - .as_array() - .unwrap() - .len(), - 20 - ); - assert_eq!(report["truncated"], true); - } -} diff --git a/crates/ghostlight-dungeon/src/clock.rs b/crates/ghostlight-dungeon/src/clock.rs deleted file mode 100644 index 543b41b..0000000 --- a/crates/ghostlight-dungeon/src/clock.rs +++ /dev/null @@ -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, - 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, - pub model_receipt_ids: Vec, - pub accepted_model_receipt_id: String, - pub emitted_event_ids: Vec, - pub emitted_news_ids: Vec, - pub news_count_before: usize, - pub next_wave_index: usize, - pub committed_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(deny_unknown_fields)] -struct ClockConsequenceBindingAction { - bindings: Vec, -} - -#[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 { - Ok(self.schema.clone()) - } - - async fn invoke( - &mut self, - action: Self::Action, - context: &ModelAgentToolContext, - ) -> ModelAgentToolOutcome { - 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 { - crate::legacy_transition::digest_serializable(&serde_json::json!({ - "campaign_id":campaign.id, - "revision":campaign.revision, - "clocks":campaign.clocks, - "actor_ids":campaign.actors.keys().collect::>(), - "institution_ids":campaign.institutions.keys().collect::>(), - "gestalt_ids":campaign.gestalts.keys().collect::>(), - "locations":campaign.locations.iter().map(|(id, location)| serde_json::json!({ - "id":id, - "name":location.name, - })).collect::>(), - "public_channels":admitted_public_channels(campaign), - })) -} - -pub async fn propose_clock_consequence_bindings( - model: &dyn ModelPort, - campaign: &Campaign, -) -> std::result::Result< - crate::agent::ModelAgentRun, - crate::agent::ModelAgentFailure, -> { - let unbound = campaign - .clocks - .values() - .filter(|clock| clock.consequence_scope.is_unbound()) - .collect::>(); - 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::>(), - "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::>(), - "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::>(), - "locations":campaign.locations.values().map(|location| serde_json::json!({ - "id":location.id, - "name":location.name, - })).collect::>(), - "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 { - 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::>(); - let supplied = bindings - .iter() - .map(|binding| binding.clock_id.as_str()) - .collect::>(); - 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::>().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> { - 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> { - 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::>(); - for event in events { - crate::domain::append_event_with_publications(campaign, event); - } - Ok(emitted) -} - -fn admitted_public_channels(campaign: &Campaign) -> BTreeSet { - 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, - ) -> (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") - ); - } -} diff --git a/crates/ghostlight-dungeon/src/compiler.rs b/crates/ghostlight-dungeon/src/compiler.rs deleted file mode 100644 index 8737595..0000000 --- a/crates/ghostlight-dungeon/src/compiler.rs +++ /dev/null @@ -1,12395 +0,0 @@ -use crate::{ - agent::{ - ModelAgentSpec, ModelAgentTool, ModelAgentToolContext, ModelAgentToolOutcome, - run_model_agent, - }, - domain::{ - ActorState, AgencyAxis, AgencyProfile, AgencyRelation, AgencyRelationKind, - AgencySubjectKind, BranchOrigin, Campaign, CivicSystemManifest, - DestinationCompilationPreview, EvidenceCoverage, EvidenceUseLane, FactScope, - GestaltMemberDelta, GestaltPersonaState, InstitutionState, LocalityElaboration, - LocalityElaborationPreview, Location, MAX_POSTURE_CHARS, Route, VaultEvidenceReceipt, - WorldClock, WorldCompilePreview, WorldFact, - }, - model::{ - MODEL_BALANCED, ModelPort, ModelStageReceipt, ModelStageRequest, - mark_model_receipt_semantic_invalid as mark_semantic_invalid, run_validated_stage, - }, - session_zero::{ - ApprovedCampaignBrief, CampaignContract, MAX_SESSION_ZERO_MEMBERS, actor_from_character, - }, - vault::{DEFAULT_VAULT_ID, VaultProvider, VaultQuery, canonical_vault_id}, -}; -use anyhow::{Result, anyhow}; -use async_trait::async_trait; -use chrono::{DateTime, Utc}; -use schemars::{JsonSchema, schema_for}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::{ - cmp::Reverse, - collections::{BTreeMap, BTreeSet, BinaryHeap}, - sync::Arc, -}; -use uuid::Uuid; - -const MAX_PARTY_IDENTITY_CHARS: usize = MAX_SESSION_ZERO_MEMBERS * 1_000; - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct OpeningRequest { - pub setting: String, - pub constraints: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct OpeningSuggestion { - pub id: String, - pub title: String, - pub era: String, - pub place: String, - pub pressure: String, - pub player_hook: String, - pub evidence_receipt_ids: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct RoleSuggestion { - pub id: String, - pub name: String, - pub premise: String, - pub capabilities: Vec, - pub obligations: Vec, - pub evidence_receipt_ids: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct CustomStart { - pub campaign_name: String, - pub who: String, - pub where_: String, - pub when: String, - pub goal: String, -} - -#[derive(Clone, Debug, Serialize, PartialEq)] -struct RequiredRelationshipActor { - id: String, - name: String, - approved_relationship_descriptions: Vec, -} - -#[derive(Clone, Debug, PartialEq)] -struct ApprovedRelationshipPlan { - anchors: Vec, - targets: BTreeMap<(String, String), String>, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct SelectedStart { - pub campaign_name: String, - pub opening: OpeningSuggestion, - pub role: RoleSuggestion, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct GestaltFissionRequest { - pub parent_gestalt_id: String, - pub partition_axis: AgencyAxis, - pub requested_partition_values: Vec, - pub reason: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct SuggestedOpenings { - pub openings: Vec, - pub evidence_receipts: Vec, - pub model_receipts: Vec, - pub retrieval_receipt: ModelStageReceipt, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct SuggestedRoles { - pub roles: Vec, - pub evidence_receipts: Vec, - pub model_receipts: Vec, - pub retrieval_receipt: ModelStageReceipt, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct DestinationCompilationFailure { - pub message: String, - pub model_receipts: Vec, -} - -impl std::fmt::Display for DestinationCompilationFailure { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter.write_str(&self.message) - } -} - -impl std::error::Error for DestinationCompilationFailure {} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct CivicElaborationVerificationFailure { - pub message: String, - #[serde(default)] - pub semantic_diagnostic: Option, - pub model_receipts: Vec, -} - -impl std::fmt::Display for CivicElaborationVerificationFailure { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter.write_str(&self.message) - } -} - -impl std::error::Error for CivicElaborationVerificationFailure {} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct OpeningSet { - openings: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct RoleSet { - roles: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct RetrievalQueryPlan { - queries: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum DestinationIdentityDecision { - Existing, - New, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -struct DestinationIdentityResolution { - decision: DestinationIdentityDecision, - existing_location_id: Option, - rationale: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct OpeningRetrievalPlan { - early_frame_query: String, - transition_frame_query: String, - late_frame_query: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct EvidenceUsePlan { - coverage: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledRelationship { - subject_id: String, - description: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledActorState { - id: String, - name: String, - location_id: String, - capabilities: BTreeSet, - knowledge: BTreeSet, - equipment: BTreeSet, - conditions: BTreeSet, - obligations: BTreeSet, - relationships: Vec, - goals: Vec, - #[serde(default)] - memories: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledRoute { - route_id: String, - destination_id: String, - distance: String, - #[schemars(range(min = 1))] - travel_minutes: u32, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledLocation { - id: String, - name: String, - #[schemars( - description = "Geometric containment only. This does not create an implicit movement edge." - )] - container_id: Option, - #[schemars( - description = "Explicit directed movement edges. A playable opening must provide route chains from the player location to every supplied location and back." - )] - routes: Vec, - persistent_features: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledGestaltMemberDelta { - schema: String, - #[schemars( - description = "Local stable member ID without the world-subject `member:` namespace prefix." - )] - id: String, - gestalt_id: String, - version: u64, - name: String, - capability_additions: BTreeSet, - capability_removals: BTreeSet, - knowledge_additions: BTreeSet, - knowledge_removals: BTreeSet, - equipment: BTreeSet, - conditions: BTreeSet, - obligations: BTreeSet, - relationships: Vec, - goals: Vec, - memories: Vec, - last_location_id: Option, - materialized_actor_id: Option, - #[serde(default)] - last_relevant_revision: u64, - #[serde(default)] - relevance_lease_until_revision: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledSeed { - title: String, - canon_cutoff: String, - world_time: DateTime, - #[schemars(range(min = 1))] - tick_hours: u32, - player: CompiledActorState, - locations: Vec, - #[schemars( - description = "Autonomous nonplayer actors only. Never duplicate or proxy the singular player subject here." - )] - actors: Vec, - #[serde(default)] - gestalts: Vec, - #[serde(default)] - gestalt_members: Vec, - institutions: Vec, - clocks: Vec, - facts: Vec, - #[schemars( - description = "Only premise-blocking gaps. Ordinary missing game-scale geometry, routes, people, procedures, daily texture, intentionally unresolved population detail, and safely omitted remote candidates are branch-local elaboration or coverage limits, never material gaps." - )] - gaps: Vec, - branch_assumptions: Vec, - opening_narration: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)] -#[serde(rename_all = "snake_case")] -enum CompiledMaterialGapKind { - ContradictoryCanonBaselines, - UnanchoredRequestedBaseline, - ApprovedCapabilityConflict, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -struct CompiledMaterialGap { - kind: CompiledMaterialGapKind, - #[schemars( - description = "Concise description of why no compatible branch-local elaboration can preserve the approved premise." - )] - summary: String, - #[schemars( - description = "Exact approved request or Session Zero premise clause that cannot be preserved." - )] - premise_clause: String, - #[schemars( - description = "The mutually exclusive canon baseline, premise change, or capability bargain the table must choose." - )] - blocked_choice: String, - #[schemars( - description = "Exact supplied Vault receipt IDs supporting the contradiction, when the gap is grounded in conflicting canon." - )] - evidence_receipt_ids: Vec, -} - -impl From for CompiledActorState { - fn from(actor: ActorState) -> Self { - Self { - id: actor.id, - name: actor.name, - location_id: actor.location_id, - capabilities: actor.capabilities, - knowledge: actor.knowledge, - equipment: actor.equipment, - conditions: actor.conditions, - obligations: actor.obligations, - relationships: actor - .relationships - .into_iter() - .map(|(subject_id, description)| CompiledRelationship { - subject_id, - description, - }) - .collect(), - goals: actor.goals, - memories: actor.memories, - } - } -} - -impl CompiledActorState { - fn into_actor(self) -> Result { - Ok(ActorState { - id: self.id, - name: self.name, - location_id: self.location_id, - capabilities: self.capabilities, - knowledge: self.knowledge, - equipment: self.equipment, - conditions: self.conditions, - obligations: self.obligations, - relationships: compiled_relationship_map(self.relationships)?, - goals: self.goals, - memories: self.memories, - }) - } -} - -impl CompiledLocation { - fn into_location(self) -> Result { - let routes = compiled_route_map(self.routes, &self.id)?; - Ok(Location { - id: self.id, - name: self.name, - container_id: self.container_id, - routes, - persistent_features: self.persistent_features, - }) - } -} - -fn compiled_route_map( - compiled_routes: Vec, - origin_id: &str, -) -> Result> { - let mut routes = BTreeMap::new(); - for route in compiled_routes { - if route.route_id.trim().is_empty() - || routes - .insert( - route.route_id.clone(), - Route { - destination_id: route.destination_id, - distance: route.distance, - travel_minutes: route.travel_minutes, - }, - ) - .is_some() - { - return Err(anyhow!( - "compiled location {origin_id} has an empty or duplicate route ID {:?}", - route.route_id - )); - } - } - Ok(routes) -} - -impl CompiledGestaltMemberDelta { - fn into_member(self) -> Result { - Ok(GestaltMemberDelta { - schema: self.schema, - id: self.id, - gestalt_id: self.gestalt_id, - version: self.version, - name: self.name, - capability_additions: self.capability_additions, - capability_removals: self.capability_removals, - knowledge_additions: self.knowledge_additions, - knowledge_removals: self.knowledge_removals, - equipment: self.equipment, - conditions: self.conditions, - obligations: self.obligations, - relationships: compiled_relationship_map(self.relationships)?, - goals: self.goals, - memories: self.memories, - last_location_id: self.last_location_id, - materialized_actor_id: self.materialized_actor_id, - last_relevant_revision: self.last_relevant_revision, - relevance_lease_until_revision: self.relevance_lease_until_revision, - }) - } -} - -fn compiled_relationship_map( - relationships: Vec, -) -> Result> { - let mut mapped = BTreeMap::new(); - for relationship in relationships { - if relationship.subject_id.trim().is_empty() - || relationship.description.trim().is_empty() - || mapped - .insert(relationship.subject_id.clone(), relationship.description) - .is_some() - { - return Err(anyhow!( - "compiled relationships require unique non-empty subject IDs and descriptions; rejected subject {:?}", - relationship.subject_id - )); - } - } - Ok(mapped) -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct PrivateRelationshipActorCandidate { - name: String, - location_id: String, - capabilities: BTreeSet, - knowledge: BTreeSet, - equipment: BTreeSet, - conditions: BTreeSet, - obligations: BTreeSet, - relationships: Vec, - goals: Vec, - #[serde(default)] - memories: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct PrivateRelationshipActorSet { - #[schemars(length(max = 64))] - actors: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledAgencySkeleton { - agency_profiles: Vec, - agency_relations: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct ExtractedRemoteInstitution { - name: String, - #[schemars(length(min = 1, max = 3))] - supporting_claims: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct ExtractedGlobalAgencyCatalog { - #[schemars(length(max = 64))] - institutions: Vec, - gaps: Vec, -} - -#[derive(Clone, Debug, PartialEq)] -struct GroundedRemoteInstitution { - name: String, - supporting_claims: Vec, - evidence_receipt_ids: Vec, -} - -#[derive(Clone, Debug, PartialEq)] -struct GroundedGlobalAgencyCatalog { - institutions: Vec, - gaps: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct SynthesizedRemoteInstitution { - name: String, - strategic_doctrine: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct StrategicDoctrineCatalog { - institutions: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct StrategicDoctrineVerdict { - name: String, - compatible_with_canon: bool, - rationale: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct StrategicDoctrineVerification { - verdicts: Vec, -} - -#[derive(Clone, Debug, PartialEq)] -struct CompiledRemoteInstitution { - name: String, - strategic_doctrine: String, - evidence_receipt_ids: Vec, -} - -#[derive(Clone, Debug, PartialEq)] -struct CompiledGlobalAgencyCatalog { - institutions: Vec, - gaps: Vec, -} - -#[derive(Clone, Debug, Serialize, JsonSchema, PartialEq)] -struct AgencySubjectBrief { - subject_id: String, - subject_kind: AgencySubjectKind, - name: String, - location_ids: BTreeSet, - capabilities_or_resources: Vec, - knowledge_or_posture: Vec, - goals: Vec, - pressures_or_obligations: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledAgencyProfile { - subject_id: String, - subject_kind: AgencySubjectKind, - collective_authority_id: Option, - facets: CompiledAgencyFacets, - location_ids: BTreeSet, - information_channels: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledAgencyFacets { - geography: BTreeSet, - ideology: BTreeSet, - authority: BTreeSet, - economy_role: BTreeSet, - species_body: BTreeSet, - information: BTreeSet, -} - -impl CompiledAgencyFacets { - fn into_map(self) -> BTreeMap> { - BTreeMap::from([ - (AgencyAxis::Geography, self.geography), - (AgencyAxis::Ideology, self.ideology), - (AgencyAxis::Authority, self.authority), - (AgencyAxis::EconomyRole, self.economy_role), - (AgencyAxis::SpeciesBody, self.species_body), - (AgencyAxis::Information, self.information), - ]) - } -} - -impl From>> for CompiledAgencyFacets { - fn from(mut facets: BTreeMap>) -> Self { - Self { - geography: facets.remove(&AgencyAxis::Geography).unwrap_or_default(), - ideology: facets.remove(&AgencyAxis::Ideology).unwrap_or_default(), - authority: facets.remove(&AgencyAxis::Authority).unwrap_or_default(), - economy_role: facets.remove(&AgencyAxis::EconomyRole).unwrap_or_default(), - species_body: facets.remove(&AgencyAxis::SpeciesBody).unwrap_or_default(), - information: facets.remove(&AgencyAxis::Information).unwrap_or_default(), - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledAgencyRelation { - id: String, - from_subject_id: String, - to_subject_id: String, - kind: AgencyRelationKind, - #[schemars(range(min = 1, max = 100))] - strength: u8, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledExpansionSeed { - origin_routes: Vec, - locations: Vec, - facts: Vec, - #[serde(default)] - #[schemars(length(max = 8))] - populations: Vec, - #[serde(default)] - #[schemars(length(max = 12))] - institutions: Vec, - #[serde(default)] - #[schemars(length(max = 48))] - local_relations: Vec, - #[serde(default)] - civic_system: Option, - #[serde(default)] - #[schemars(length(max = 32))] - migration_relations: Vec, - #[serde(default)] - #[schemars( - length(max = 32), - description = "Consequential compatible game-scale inventions admitted only for this campaign. Missing routes, geometry, ordinary procedures, supplies, local responsibilities, and operating doctrine belong here rather than in gaps." - )] - branch_assumptions: Vec, - #[serde(default)] - #[schemars( - description = "Only premise-blocking material gaps for which no compatible branch-local elaboration can preserve the exact requested destination." - )] - gaps: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledDestinationPopulation { - id: String, - name: String, - home_location_id: String, - shared_capabilities: BTreeSet, - /// Exact IDs from this expansion's `facts`. The compiler resolves them to - /// statements after validation so a population cannot acquire unsupported - /// free-text knowledge during admission. - shared_fact_ids: BTreeSet, - resources: BTreeSet, - goals: Vec, - pressures: Vec, - collective_authority_id: Option, - facets: CompiledAgencyFacets, - information_channels: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledDestinationInstitution { - id: String, - name: String, - resources: Vec, - goals: Vec, - posture: String, - location_ids: BTreeSet, - facets: CompiledAgencyFacets, - information_channels: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CompiledCivicInstitutionUpdate { - institution_id: String, - resources: Vec, - posture: String, - facets: CompiledAgencyFacets, - information_channels: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CivicSystemVerification { - authority_legible: bool, - selection_or_succession_legible: bool, - public_resources_legible: bool, - redress_legible: bool, - institutional_relations_coherent: bool, - resident_answer_grounded: bool, - political_form_distinct_or_deliberately_shared: bool, - opposed_interests_have_distinct_means: bool, - constituencies_cross_boundaries_or_local_homogeneity_justified: bool, - explicit_request_constraints_satisfied: bool, - public_names_do_not_repeat_an_overused_template: bool, - candidate_text_intact: bool, - #[schemars(length(min = 1, max = 1_000))] - rationale: String, -} - -fn civic_verification_semantic_diagnostic(verdict: &CivicSystemVerification) -> String { - let failed_checks = [ - ("authority_legible", verdict.authority_legible), - ( - "selection_or_succession_legible", - verdict.selection_or_succession_legible, - ), - ("public_resources_legible", verdict.public_resources_legible), - ("redress_legible", verdict.redress_legible), - ( - "institutional_relations_coherent", - verdict.institutional_relations_coherent, - ), - ("resident_answer_grounded", verdict.resident_answer_grounded), - ( - "political_form_distinct_or_deliberately_shared", - verdict.political_form_distinct_or_deliberately_shared, - ), - ( - "opposed_interests_have_distinct_means", - verdict.opposed_interests_have_distinct_means, - ), - ( - "constituencies_cross_boundaries_or_local_homogeneity_justified", - verdict.constituencies_cross_boundaries_or_local_homogeneity_justified, - ), - ( - "explicit_request_constraints_satisfied", - verdict.explicit_request_constraints_satisfied, - ), - ( - "public_names_do_not_repeat_an_overused_template", - verdict.public_names_do_not_repeat_an_overused_template, - ), - ("candidate_text_intact", verdict.candidate_text_intact), - ] - .into_iter() - .filter_map(|(name, accepted)| (!accepted).then_some(name)) - .collect::>(); - serde_json::json!({ - "failed_checks":failed_checks, - "rationale":verdict.rationale, - }) - .to_string() -} - -#[derive(Clone, Debug, Serialize, PartialEq)] -struct CompiledResidentFactKnowledge { - population_id: String, - fact_ids: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, PartialEq)] -struct CompiledCivicSystemReconciliation { - schema: String, - jurisdiction_location_id: String, - governing_institution_ids: BTreeSet, - resident_population_ids: BTreeSet, - public_authority_fact_ids: BTreeSet, - public_selection_fact_ids: BTreeSet, - public_resource_fact_ids: BTreeSet, - public_redress_fact_ids: BTreeSet, - political_relation_ids: BTreeSet, -} - -impl From for CivicSystemManifest { - fn from(value: CompiledCivicSystemReconciliation) -> Self { - Self { - schema: value.schema, - version: 0, - jurisdiction_location_id: value.jurisdiction_location_id, - governing_institution_ids: value.governing_institution_ids, - resident_population_ids: value.resident_population_ids, - public_authority_fact_ids: value.public_authority_fact_ids, - public_selection_fact_ids: value.public_selection_fact_ids, - public_resource_fact_ids: value.public_resource_fact_ids, - public_redress_fact_ids: value.public_redress_fact_ids, - political_relation_ids: value.political_relation_ids, - semantic_verification_receipt_id: String::new(), - } - } -} - -#[derive(Clone, Debug, Serialize, PartialEq)] -struct CompiledDestinationReconciliation { - facts: Vec, - resident_fact_knowledge: Vec, - institution_updates: Vec, - local_relations: Vec, - civic_system: CompiledCivicSystemReconciliation, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CompiledCivicSystemLanesUpdate { - governing_institution_ids: BTreeSet, - resident_population_ids: BTreeSet, - public_authority_fact_ids: BTreeSet, - public_selection_fact_ids: BTreeSet, - public_resource_fact_ids: BTreeSet, - public_redress_fact_ids: BTreeSet, - political_relation_ids: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(tag = "edit", rename_all = "snake_case", deny_unknown_fields)] -enum DestinationReconciliationEdit { - ReplaceFact { - #[schemars(range(max = 31))] - fact_index: usize, - fact: WorldFact, - }, - SetResidentFactKnowledge { - population_id: String, - fact_ids: BTreeSet, - }, - UpdateInstitution { - update: CompiledCivicInstitutionUpdate, - }, - AddLocalRelation { - relation: CompiledAgencyRelation, - }, - ReplaceLocalRelation { - #[schemars(range(max = 47))] - relation_index: usize, - relation: CompiledAgencyRelation, - }, - RemoveLocalRelation { - #[schemars(range(max = 47))] - relation_index: usize, - }, - UpdateCivicSystemLanes { - civic_system: CompiledCivicSystemLanesUpdate, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(rename_all = "snake_case")] -enum DestinationReconciliationTool { - ValidateCurrent, - ReviseAndValidate, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct DestinationReconciliationToolAction { - tool: DestinationReconciliationTool, - #[serde(default)] - #[schemars(length(min = 1, max = 12))] - edits: Option>, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum DestinationFactFindingKind { - EmptyId, - ExistingId, - DuplicateId, - EmptyStatement, - DuplicateStatement, - EmptyEvidenceReceiptId, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -struct DestinationFactFinding { - kind: DestinationFactFindingKind, - fact_index: usize, - submitted_fact_id: String, - statement: String, - conflicts_with_fact_ids: Vec, -} - -#[derive(Clone, Debug, Serialize, PartialEq)] -#[serde(tag = "kind", rename_all = "snake_case")] -enum DestinationReconciliationFinding { - #[serde(rename = "edit_rejection")] - Edit { message: String }, - #[serde(rename = "candidate_apply_rejection")] - CandidateApply { message: String }, - #[serde(rename = "fact_namespace_rejection")] - FactNamespace { - findings: Vec, - }, - #[serde(rename = "candidate_lowering_rejection")] - CandidateLowering { message: String }, - #[serde(rename = "structural_validation_rejection")] - StructuralValidation { message: String }, - #[serde(rename = "civic_verifier_rejection")] - CivicVerifier { verdict: CivicSystemVerification }, -} - -#[derive(Clone, Debug, Serialize, PartialEq)] -struct DestinationReconciliationObservation { - draft_digest: String, - applied_edits: Vec, - finding: DestinationReconciliationFinding, -} - -struct AcceptedDestinationReconciliation { - seed: CompiledExpansionSeed, - expansion: crate::domain::RegionExpansion, -} - -struct DestinationReconciliationAgentTool<'a> { - compiler: &'a WorldCompiler, - campaign: &'a Campaign, - destination_request: &'a str, - evidence: &'a str, - current_civic_context: &'a Option, - frozen_seed: &'a CompiledExpansionSeed, - draft: CompiledDestinationReconciliation, - expansion_origin_location_id: &'a str, - existing_destination_id: Option<&'a str>, - snapshot: &'a str, - admission_evidence_receipt_ids: &'a [String], - action_schema: serde_json::Value, -} - -enum CivicSystemVerificationOutcome { - Accepted { - receipts: Vec, - }, - Rejected { - verdict: CivicSystemVerification, - receipts: Vec, - }, - Failed { - message: String, - receipts: Vec, - }, -} - -const MAX_DESTINATION_RECONCILIATION_AGENT_STEPS: usize = 4; - -fn destination_compilation_failure( - message: impl std::fmt::Display, - model_receipts: Vec, -) -> anyhow::Error { - anyhow::Error::new(DestinationCompilationFailure { - message: message.to_string(), - model_receipts, - }) -} - -fn destination_model_receipts( - identity_receipts: &[ModelStageReceipt], - retrieval_receipt: Option<&ModelStageReceipt>, - compiler_receipts: &[ModelStageReceipt], -) -> Vec { - identity_receipts - .iter() - .chain(retrieval_receipt) - .chain(compiler_receipts) - .cloned() - .collect() -} - -fn destination_candidate_failure( - message: impl std::fmt::Display, - identity_receipts: &[ModelStageReceipt], - retrieval_receipt: &ModelStageReceipt, - compiler_receipts: &mut [ModelStageReceipt], -) -> anyhow::Error { - let message = message.to_string(); - if let Some(receipt) = compiler_receipts.last_mut() { - mark_semantic_invalid(receipt, &message); - } - destination_compilation_failure( - message, - destination_model_receipts( - identity_receipts, - Some(retrieval_receipt), - compiler_receipts, - ), - ) -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledDestinationMigrationRelation { - id: String, - from_gestalt_id: String, - to_gestalt_id: String, - #[schemars(range(min = 1, max = 100))] - strength: u8, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledFissionSeed { - children: Vec, - child_partition_values: Vec, - #[serde(default)] - member_child_assignments: Vec, - resource_child_assignments: Vec, - gaps: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledChildPartitionValue { - child_id: String, - value: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledMemberChildAssignment { - member_id: String, - child_id: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -struct CompiledResourceChildAssignment { - resource_id: String, - child_id: String, -} - -fn compiled_assignment_map( - label: &str, - assignments: impl IntoIterator, -) -> Result> { - let mut mapped = BTreeMap::new(); - for (subject_id, child_id) in assignments { - if subject_id.trim().is_empty() - || child_id.trim().is_empty() - || mapped.insert(subject_id.clone(), child_id).is_some() - { - return Err(anyhow!( - "compiled {label} require unique non-empty subject IDs and child IDs; rejected subject {subject_id:?}" - )); - } - } - Ok(mapped) -} - -pub struct WorldCompiler { - vault: Arc, - model: Arc, - retrieval_model: String, - compiler_model: String, - vault_id: String, -} - -impl WorldCompiler { - pub fn new( - vault: Arc, - model: Arc, - retrieval_model: impl Into, - compiler_model: impl Into, - ) -> Self { - Self { - vault, - model, - retrieval_model: retrieval_model.into(), - compiler_model: compiler_model.into(), - vault_id: DEFAULT_VAULT_ID.into(), - } - } - - pub fn for_vault(&self, vault_id: &str) -> Result { - let vault_id = canonical_vault_id(vault_id) - .ok_or_else(|| anyhow!("unknown or unavailable lore Vault {vault_id:?}"))?; - Ok(Self { - vault: self.vault.clone(), - model: self.model.clone(), - retrieval_model: self.retrieval_model.clone(), - compiler_model: self.compiler_model.clone(), - vault_id: vault_id.into(), - }) - } - - pub async fn suggest_openings(&self, request: OpeningRequest) -> Result { - validate_user_text("setting", &request.setting, 120)?; - if request.constraints.len() > 8 { - return Err(anyhow!("opening request accepts at most 8 constraints")); - } - for constraint in &request.constraints { - validate_user_text("opening constraint", constraint, 240)?; - } - let (queries, retrieval_receipt) = self.plan_opening_queries(&request).await?; - let receipts = self.retrieve_all_player_visible(&queries, "all", 8).await?; - let evidence = opening_evidence_text(&queries, &receipts); - let base_prompt = format!( - "Generate exactly three source-grounded openings, taking one from each labeled historical-frame evidence group when that group contains adequate support. The three literal `era` values must name specific, genuinely different historical periods and be pairwise distinct after trimming and case-folding. An umbrella label such as `Post-Elysium` is insufficient when used twice: qualify each with its distinct source-supported event, phase, or date. The three `place` values and three `pressure` values must independently be pairwise distinct. Do not return aliases for the same period or place merely to satisfy spelling-level diversity. Do not fill material evidence gaps with invention. Before returning, verify the nine axis values yourself. REQUEST:\n{}\nEVIDENCE GROUPS:\n{}", - serde_json::to_string(&request)?, - evidence - ); - let schema = serde_json::to_value(schema_for!(OpeningSet))?; - let source_receipts = receipt_ids(&receipts); - let mut correction = String::new(); - let mut model_receipts = Vec::new(); - for attempt in 0..2 { - let (value, stage) = self - .structured( - "world_openings", - "opening-suggestions", - &format!("{base_prompt}{correction}"), - schema.clone(), - source_receipts.clone(), - ) - .await?; - model_receipts.push(stage); - let mut parsed: OpeningSet = serde_json::from_value(value.clone())?; - for opening in &mut parsed.openings { - deduplicate_ids(&mut opening.evidence_receipt_ids); - } - let validation = if parsed.openings.len() != 3 { - Err(anyhow!("world compiler must return exactly three openings")) - } else { - validate_opening_suggestions(&parsed.openings, &source_receipts) - }; - match validation { - Ok(()) => { - return Ok(SuggestedOpenings { - openings: parsed.openings, - evidence_receipts: receipts, - model_receipts, - retrieval_receipt, - }); - } - Err(error) if attempt == 0 => { - mark_semantic_invalid( - model_receipts - .last_mut() - .expect("opening receipt was just stored"), - &error, - ); - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS OPENINGS: {error}\nPREVIOUS_REJECTED_OPENINGS:\n{}\nReturn one complete corrected set. Replace the specifically collided values named by the validator with different source-supported values. All three literal values on each axis must be pairwise distinct after trimming and case-folding. Preserve source grounding and use only supplied evidence.", - serde_json::to_string(&value)? - ); - } - Err(error) => { - return Err(anyhow!( - "world opening compiler failed local validation after one correction: {error}" - )); - } - } - } - unreachable!() - } - - pub async fn suggest_roles(&self, opening: &OpeningSuggestion) -> Result { - let (queries, retrieval_receipt) = self - .plan_queries( - "role_retrieval_plan", - &format!("roles:{}", opening.id), - &serde_json::to_string(opening)?, - 2, - ) - .await?; - let receipts = self - .retrieve_all_player_visible(&queries, &opening.era, 8) - .await?; - let base_prompt = format!( - "Generate exactly three materially distinct player roles grounded in this opening and evidence. Names and premises must each be pairwise distinct after trimming and case-folding. The roles must differ in social position, capabilities, and obligations rather than being cosmetic aliases. OPENING:\n{}\nEVIDENCE:\n{}", - serde_json::to_string(opening)?, - evidence_text(&receipts) - ); - let schema = serde_json::to_value(schema_for!(RoleSet))?; - let source_receipts = receipt_ids(&receipts); - let mut correction = String::new(); - let mut model_receipts = Vec::new(); - for attempt in 0..2 { - let (value, stage) = self - .structured( - "world_roles", - &format!("roles:{}", opening.id), - &format!("{base_prompt}{correction}"), - schema.clone(), - source_receipts.clone(), - ) - .await?; - model_receipts.push(stage); - let mut parsed: RoleSet = serde_json::from_value(value.clone())?; - for role in &mut parsed.roles { - deduplicate_ids(&mut role.evidence_receipt_ids); - } - let validation = if parsed.roles.len() != 3 { - Err(anyhow!("world compiler must return exactly three roles")) - } else { - validate_role_suggestions(&parsed.roles, &source_receipts) - }; - match validation { - Ok(()) => { - return Ok(SuggestedRoles { - roles: parsed.roles, - evidence_receipts: receipts, - model_receipts, - retrieval_receipt, - }); - } - Err(error) if attempt == 0 => { - mark_semantic_invalid( - model_receipts - .last_mut() - .expect("role receipt was just stored"), - &error, - ); - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS ROLES: {error}\nPREVIOUS_REJECTED_ROLES:\n{}\nReturn one complete corrected set. Replace the specifically collided names or premises named by the validator and make the roles materially different while preserving source grounding.", - serde_json::to_string(&value)? - ); - } - Err(error) => { - return Err(anyhow!( - "world role compiler failed local validation after one correction: {error}" - )); - } - } - } - unreachable!() - } - - pub async fn compile_custom( - &self, - start: CustomStart, - ) -> Result<(WorldCompilePreview, Vec)> { - self.compile_custom_with_owned_subjects(start, &[], &[], None, None) - .await - } - - async fn compile_custom_with_owned_subjects( - &self, - start: CustomStart, - required_relationship_actors: &[RequiredRelationshipActor], - player_names: &[String], - private_operational_context: Option<&serde_json::Value>, - approved_contract: Option<&CampaignContract>, - ) -> Result<(WorldCompilePreview, Vec)> { - validate_user_text("campaign name", &start.campaign_name, 80)?; - validate_user_text("player identity", &start.who, MAX_PARTY_IDENTITY_CHARS)?; - validate_user_text("starting location", &start.where_, 500)?; - validate_user_text("starting time", &start.when, 500)?; - validate_user_text("player goal", &start.goal, 1_000)?; - validate_required_relationship_actor_inputs(required_relationship_actors)?; - let retrieval_subject = serde_json::to_string(&serde_json::json!({ - "start": &start, - "approved_contract": approved_contract, - }))?; - let (planned_queries, retrieval_receipt) = self - .plan_queries( - "custom_retrieval_plan", - "custom-start", - &retrieval_subject, - 3, - ) - .await?; - let queries = planned_queries; - let global_queries = global_agency_queries(&start); - let (local_evidence, global_evidence) = tokio::join!( - self.retrieve_all(&queries, &start.when, 8), - self.retrieve_all(&global_queries, &start.when, 12), - ); - let receipts = local_evidence?; - let global_receipts = global_evidence?; - let (classified, global_catalog) = tokio::join!( - self.classify_evidence(&start, approved_contract, &receipts), - self.compile_global_agency_catalog(&start, &global_receipts), - ); - let (evidence_coverage, relevance_receipts) = classified?; - let (global_catalog, global_catalog_receipts) = global_catalog?; - let scoped_evidence = direct_seed_evidence_text(&receipts, &evidence_coverage); - let shared_prefix = format!( - "SOURCE-GROUNDED WORLD COMPILATION\nSTART:\n{}\nSCOPED EVIDENCE:\n{}\n\n", - serde_json::to_string(&start)?, - scoped_evidence - ); - let approved_contract_context = approved_contract - .map(|contract| -> Result { - Ok(format!( - "\nAPPROVED SESSION ZERO CONTRACT:\n{}\nThis public table-approved contract is causal compilation input. Preserve its premise, opening pressure, tone, pacing, consequences, narrative focus, internal tension, and DM style together; do not reconstruct or substitute them from the narrower legacy START fields. Materialize exact public branch-local opening requirements named by the contract unless they contradict Vault evidence, in which case report an explicit gap.\n", - serde_json::to_string(contract)? - )) - }) - .transpose()? - .unwrap_or_default(); - let player_identity_context = if player_names.is_empty() { - String::new() - } else { - format!( - "\nHUMAN-CONTROLLED PLAYER NAMES:\n{}\nThese people are input context, not world-cast outputs. Do not emit them in actors or gestalt_members; Session Zero materializes their canonical actors after world compilation. The singular player field is only a provisional starting-position marker and must not also appear in actors or gestalt_members.\n", - serde_json::to_string(player_names)? - ) - }; - let operational_playability_context = private_operational_context - .map(|context| -> Result { - Ok(format!( - "\nPRIVATE OPERATIONAL PLAYABILITY INPUT:\n{}\nThis input exists only to make approved player capabilities, equipment, obligations, goals, and extraordinary-permission ceilings actionable in the starting world. It is not public narration, NPC knowledge, or world-cast material. Never copy it into actors, gestalts, institutions, dialogue, or the opening transcript. Use it only to seed bounded branch_local or provisional_local environmental facts at exact relevant locations, or report an explicit evidence gap. For every concrete opening problem that an approved capability or permission could investigate, seed at least one discoverable fact precise enough to produce a meaningful result within that capability's effect ceiling. A generic restatement of the overall crisis is not sufficient. Do not encode private history, secrets, relationships, or pre-existing character knowledge; none are supplied here.\n", - serde_json::to_string(context)? - )) - }) - .transpose()? - .unwrap_or_default(); - let base_prompt = format!( - "{shared_prefix}{approved_contract_context}{player_identity_context}{operational_playability_context}Compile a bounded playable region with stable topology, local actors, populations, clocks, and only those remote institutions that have a direct causal relationship to this requested start. SCOPED EVIDENCE contains direct_seed witnesses only. Setting-background and excluded witnesses remain visible in the approval coverage but are deliberately absent here: they cannot donate cast, incidents, clocks, location state, goals, or institutional posture to this branch. Use evidence as canon constraints, not as an exhaustive game map. A source marked with a `.gm_canon` authority lane may constrain hidden canonical state, but it must not be quoted or paraphrased into opening narration or granted as player or NPC knowledge merely because this compiler received it. When the Vault omits game-scale geometry, routes, local people, procedures, or daily texture, invent the smallest coherent playable elaboration, mark facts branch_local or provisional_local, and disclose consequential choices in branch_assumptions. An unevidenced route needed to connect the bounded region is branch-local geometry, not an evidence gap. Intentionally unresolved identities or population detail remain unresolved branch assumptions, not material gaps. Safely omitted remote candidates are global coverage limits, not material gaps. The `gaps` array is legal only when no compatible elaboration can preserve an exact approved premise clause without choosing between contradictory canon baselines, inventing an unanchored baseline explicitly required by the premise, or exceeding an approved capability. Every gap must name that exact premise clause and the exact choice requiring table approval. `The Vault does not specify X` is never sufficient. Use an empty gaps array when branch-local invention preserves the premise. Never borrow a nearby story to fill a gap. Do not eagerly materialize remote settlements or people outside the bounded playable region. Private character history, secrets, relationships, and relationship subjects are deliberately absent and compile in a separate private stage; do not assume or reconstruct them. Emit only supported canon facts. A canon_baseline fact must cite one or more exact receipt_id values printed in SCOPED EVIDENCE whose witnesses directly support the whole statement. Never label an invented proper noun canon. Facts that an actor can uncover through an admitted local observation must exist before play and list the exact discoverable_at_location_ids where that observation is possible. Seed enough branch_local or provisional_local discoverable facts to make the requested opening pressure and immediate goal actionable; at least one such non-canon fact must be discoverable at the player's exact starting location. The later action assessor can reveal an existing fact but cannot invent one. Facts that are private history or not directly observable have an empty discovery-location set. The singular player object is the sole human-controlled subject projection. Never repeat its id, name, role, representative, or proxy in actors or gestalt_members; actors contains autonomous nonplayer individuals only. The player location and every actor location must exist. Containment describes nested geometry; it never creates implicit movement. Every supplied location is a playable occupancy node. When the region contains more than one location, explicit route chains must let the player reach every supplied location from the starting location and return. Model inaccessible scenery as a persistent feature instead of an unreachable location. Every route record needs a stable route_id within its origin, an exact supplied destination_id, a distance, and positive travel_minutes. Every fact discovery location must exist, clocks need positive thresholds, and the player id must be unique. Every clock consequence_scope must name the smallest exact non-player actors, institutions, populations, and locations that experience its declared consequence; it must include at least one supplied location and one supplied autonomous subject. Leave public_channels empty during compilation unless an exact admitted route is supplied later by the consumer. Actor relationship records must use subject_id values copied from exact actor, institution, gestalt, or named-member subject IDs declared in this candidate, never display names, roles, undeclared groups, or location IDs. A relationship to a collective population names its exact gestalt; it does not union that population's knowledge or turn the actor into its authority. Represent populations that can act collectively (villages, crews, crowds, departments, corporations) as gestalt Personas. Seed a small roster of plausible durable member identities for people the player may encounter; member deltas contain only departures from their gestalt baseline and begin dematerialized. Do not duplicate a gestalt member in actors. Keep named plot-critical people as ordinary actors. Every gestalt home location and member gestalt reference must exist. Do not emit agency profiles or relations; those are compiled from the exact validated subject roster in the next stage." - ); - let schema = serde_json::to_value(schema_for!(CompiledSeed))?; - let sources = receipt_ids_for_coverage(&receipts, &evidence_coverage); - let mut compiler_receipts = Vec::new(); - let mut correction = String::new(); - let mut seed = loop { - let output = self - .structured( - "world_compile", - "custom-start", - &format!("{base_prompt}{correction}"), - schema.clone(), - sources.clone(), - ) - .await?; - compiler_receipts.push(output.1); - let seed: CompiledSeed = serde_json::from_value(output.0)?; - let validation = validate_compiled_material_gaps(&seed.gaps, &receipts) - .and_then(|()| { - validate_shared_seed_excludes_locally_owned_subjects( - &seed, - required_relationship_actors, - player_names, - ) - }) - .and_then(|()| seed_to_campaign(seed.clone(), &receipts)) - .and_then(|campaign| { - validate_campaign_seed(&campaign)?; - validate_opening_playability(&campaign)?; - Ok(campaign) - }); - match validation { - Ok(_) => break seed, - Err(error) if compiler_receipts.len() == 1 => { - mark_semantic_invalid( - compiler_receipts - .last_mut() - .expect("receipt was just stored"), - &error, - ); - let previous_structure = - serde_json::to_string(&compiled_seed_structure(&seed))?; - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS CANDIDATE: {error}\nPREVIOUS_CANDIDATE_STRUCTURE:\n{previous_structure}\nReturn a corrected complete candidate against the same START and EVIDENCE. Preserve valid detail, but make every reference use an ID declared by the corrected candidate. ROUTE REPAIR REQUIREMENT: routes are directed movement authority and container_id is geometry only. The corrected candidate must contain an explicit bidirectional spanning route tree rooted at the player's location: every supplied location must have a directed route chain from the player and a directed route chain back. A physically navigable contained location should normally connect to its container in both directions; otherwise connect it through the nearest legitimate occupancy node. Each route record needs a stable route_id within its origin, an exact supplied destination_id, a distance, and positive travel_minutes. Before returning, internally trace player-to-location and location-to-player paths for every location. Do not emit the trace separately." - ); - } - Err(error) => { - return Err(anyhow!( - "world compiler failed local validation after one correction: {error}" - )); - } - } - }; - let (private_relationship_actors, private_actor_receipts) = self - .compile_private_relationship_actors( - &start, - &seed, - required_relationship_actors, - &receipts, - ) - .await?; - seed.actors.extend( - private_relationship_actors - .into_iter() - .map(CompiledActorState::from), - ); - compiler_receipts.extend(private_actor_receipts); - let campaign_with_private_actors = seed_to_campaign(seed.clone(), &receipts)?; - validate_campaign_seed(&campaign_with_private_actors)?; - validate_opening_playability(&campaign_with_private_actors)?; - validate_required_relationship_actors( - &campaign_with_private_actors, - required_relationship_actors, - )?; - let (remote_institution_evidence, global_agency_assumptions) = - merge_global_agency_catalog(&mut seed, global_catalog)?; - let remote_institution_ids = remote_institution_evidence - .keys() - .cloned() - .collect::>(); - let all_receipts = merge_evidence_receipts(&receipts, &global_receipts); - let evidence_coverage = merge_global_evidence_coverage(evidence_coverage, &global_receipts); - let mut campaign = seed_to_campaign(seed.clone(), &all_receipts)?; - apply_coarse_remote_agency_profiles(&mut campaign, &remote_institution_evidence)?; - validate_campaign_seed(&campaign)?; - validate_opening_playability(&campaign)?; - validate_required_relationship_actors(&campaign, required_relationship_actors)?; - let subject_briefs = agency_subject_briefs(&campaign, &remote_institution_ids); - let modeled_subject_ids = subject_briefs - .iter() - .map(|brief| brief.subject_id.clone()) - .collect::>(); - let agency_prompt = format!( - "MULTIRESOLUTION AGENCY SKELETON\nCompile only this exact, already validated subject roster:\n{}\n\nReturn exactly one agency profile for every supplied subject and no other subject. Copy every subject_id, subject_kind, and location_ids exactly. Every profile must contain exactly the six facet axes geography, ideology, authority, economy_role, species_body, and information. Derive facets only from the supplied roster fields; use an explicit unknown value when they do not support a sharper facet claim. information_channels are concrete routes through which the subject can publish or receive reports (for example a courier wire, bulletin, newspaper, radio net, or word of mouth), never facts the subject knows; do not copy knowledge_or_posture values into information_channels, and use an empty set rather than an unknown placeholder when no route is supported. collective_authority_id must be null or one supplied subject ID; it denotes real shared authority, never mere alliance or proximity. Relations may use only supplied subject IDs and strength must be an integer from 1 through 100. Cross-faction relations never imply shared speech, knowledge, or authority. Preserve geographic, ideological, institutional, economic, biological, and information boundaries that predict different behavior under pressure.", - serde_json::to_string(&subject_briefs)? - ); - let agency_schema = serde_json::to_value(schema_for!(CompiledAgencySkeleton))?; - let mut agency_correction = String::new(); - let agency_sources = receipt_ids(&all_receipts); - while !subject_briefs.is_empty() { - let output = self - .structured( - "agency_compile", - "custom-start", - &format!("{agency_prompt}{agency_correction}"), - agency_schema.clone(), - agency_sources.clone(), - ) - .await?; - compiler_receipts.push(output.1); - let skeleton: CompiledAgencySkeleton = serde_json::from_value(output.0)?; - let mut candidate = campaign.clone(); - match apply_compiled_agency_skeleton( - &mut candidate, - &modeled_subject_ids, - skeleton.agency_profiles, - skeleton.agency_relations, - ) - .and_then(|_| validate_campaign_seed(&candidate)) - { - Ok(()) => { - campaign = candidate; - break; - } - Err(error) if agency_correction.is_empty() => { - mark_semantic_invalid( - compiler_receipts - .last_mut() - .expect("receipt was just stored"), - &error, - ); - agency_correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS AGENCY SKELETON: {error}\nReturn one corrected complete agency skeleton for the same exact roster." - ); - } - Err(error) => { - return Err(anyhow!( - "agency compiler failed local validation after one correction: {error}" - )); - } - } - } - let mut model_receipts = vec![retrieval_receipt]; - model_receipts.extend(relevance_receipts); - model_receipts.extend(global_catalog_receipts); - model_receipts.extend(compiler_receipts); - Ok(( - WorldCompilePreview { - schema: "ghostlight.world_compile_preview.v1".into(), - title: seed.title, - campaign, - evidence_receipts: all_receipts, - evidence_coverage, - gaps: seed.gaps.iter().map(material_gap_text).collect(), - branch_assumptions: seed - .branch_assumptions - .into_iter() - .chain(global_agency_assumptions) - .collect(), - requires_approval: true, - }, - model_receipts, - )) - } - - async fn compile_private_relationship_actors( - &self, - start: &CustomStart, - seed: &CompiledSeed, - anchors: &[RequiredRelationshipActor], - evidence_receipts: &[VaultEvidenceReceipt], - ) -> Result<(Vec, Vec)> { - if anchors.is_empty() { - return Ok((Vec::new(), Vec::new())); - } - validate_required_relationship_actor_inputs(anchors)?; - let private_context = serde_json::json!({ - "start": start, - "approved_private_subjects": anchors.iter().map(|anchor| serde_json::json!({ - "name":anchor.name, - "approved_relationship_descriptions":anchor.approved_relationship_descriptions, - })).collect::>(), - "locations": seed.locations.iter().map(|location| serde_json::json!({ - "id": location.id, - "name": location.name, - "container_id": location.container_id, - "persistent_features": location.persistent_features, - })).collect::>(), - "public_actors": seed.actors.iter().map(|actor| serde_json::json!({ - "id": actor.id, - "name": actor.name, - "location_id": actor.location_id, - })).collect::>(), - "public_institutions": seed.institutions.iter().map(|institution| serde_json::json!({ - "id": institution.id, - "name": institution.name, - "posture": institution.posture, - })).collect::>(), - "public_populations": seed.gestalts.iter().map(|gestalt| serde_json::json!({ - "id": gestalt.id, - "name": gestalt.name, - "home_location_id": gestalt.home_location_id, - "pressures": gestalt.pressures, - })).collect::>(), - }); - let base_prompt = format!( - "PRIVATE RELATIONSHIP ACTOR COMPILATION\nThis is a private branch-local stage. Synthesize exactly one ordinary actor candidate for every approved_private_subject in the supplied order. Copy each name exactly. Choose one exact location id from the supplied topology. The approved relationship descriptions are private, player-approved context: use them only to preserve facts explicitly owned by the counterpart, such as that person's role, affiliation, capabilities, knowledge, goals, obligations, or stated feelings. Do not infer that the counterpart knows the player's secrets or private history, and do not convert player-only interpretation into counterpart knowledge. When ownership is ambiguous, omit the fact and let the private approval preview expose the gap. Candidate relationships may name only exact actor, institution, or population IDs supplied in the public world context and should preserve an explicit affiliation or obligation; never invent a player ID or relationship-anchor ID. Return actor candidates only: no canonical IDs, narration, facts, evidence gaps, branch assumptions, agency profiles, or changes to the public world.\nCONTEXT:\n{}", - serde_json::to_string(&private_context)? - ); - let mut schema = serde_json::to_value(schema_for!(PrivateRelationshipActorSet))?; - constrain_private_relationship_actor_schema(&mut schema, anchors, seed)?; - let sources = receipt_ids(evidence_receipts); - let mut receipts = Vec::new(); - let mut correction = String::new(); - loop { - let output = self - .structured( - "private_relationship_actor_compile", - "custom-start-private-relationships", - &format!("{base_prompt}{correction}"), - schema.clone(), - sources.clone(), - ) - .await - .map_err(|_| { - anyhow!( - "private relationship actor model stage failed safely; no private diagnostic was published" - ) - })?; - receipts.push(output.1); - let candidates: PrivateRelationshipActorSet = serde_json::from_value(output.0) - .map_err(|_| { - anyhow!( - "private relationship actor model stage failed safely; no private diagnostic was published" - ) - })?; - match materialize_private_relationship_actors(seed, anchors, candidates) { - Ok(actors) => return Ok((actors, receipts)), - Err(error) if receipts.len() == 1 => { - mark_semantic_invalid( - receipts.last_mut().expect("receipt was just stored"), - &error, - ); - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS PRIVATE ACTOR CANDIDATES: {error}\nReturn one corrected complete candidate set against the same private context." - ); - } - Err(_) => { - return Err(anyhow!( - "private relationship actor compiler failed local validation after one correction; exact diagnostics remain private" - )); - } - } - } - } - - pub async fn compile_approved_brief( - &self, - brief: &ApprovedCampaignBrief, - ) -> Result<(WorldCompilePreview, Vec)> { - if brief.characters.is_empty() || brief.characters.len() > 8 { - return Err(anyhow!( - "approved campaign brief must contain one to eight characters" - )); - } - let host_actor_id = brief - .member_actor_ids - .get(&brief.host_member_id) - .ok_or_else(|| anyhow!("approved campaign brief has no host actor binding"))? - .clone(); - let public_party = brief - .characters - .iter() - .map(|character| format!("{} — {}", character.name, character.public_premise)) - .collect::>() - .join("; "); - let relationship_plan = approved_relationship_plan(brief)?; - let player_names = brief - .characters - .iter() - .map(|character| character.name.clone()) - .collect::>(); - let operational_playability_context = serde_json::json!({ - "characters":brief.characters.iter().map(|character| serde_json::json!({ - "actor_id":character.actor_id, - "name":character.name, - "public_premise":character.public_premise, - "capabilities":character.capabilities, - "equipment":character.equipment, - "obligations":character.obligations, - "goals":character.goals, - "extraordinary_permissions":character.extraordinary_permissions.iter().map(|permission| serde_json::json!({ - "name":permission.name, - "reliable_scope":permission.reliable_scope, - "prerequisites":permission.prerequisites, - "costs":permission.costs, - "limits":permission.limits, - "opposition":permission.opposition, - "exposure":permission.exposure, - "effect_ceiling":permission.effect_ceiling, - })).collect::>(), - })).collect::>() - }); - let mut compiled = self - .compile_custom_with_owned_subjects( - CustomStart { - campaign_name: brief.contract.campaign_name.clone(), - who: format!( - "A cooperative party whose public starting identities are: {public_party}. Private histories, secrets, and individual knowledge are deliberately withheld from world generation." - ), - where_: brief.contract.starting_where.clone(), - when: brief.contract.starting_when.clone(), - goal: brief.contract.desired_goal.clone(), - }, - &relationship_plan.anchors, - &player_names, - Some(&operational_playability_context), - Some(&brief.contract), - ) - .await?; - let campaign = &mut compiled.0.campaign; - let generated_player_id = campaign.player_actor_id.clone(); - let starting_location = campaign - .actors - .get(&generated_player_id) - .ok_or_else(|| anyhow!("compiled campaign lost its provisional player"))? - .location_id - .clone(); - campaign.actors.remove(&generated_player_id); - campaign.agency_profiles.remove(&generated_player_id); - campaign.agency_relations.retain(|_, relation| { - relation.from_subject_id != generated_player_id - && relation.to_subject_id != generated_player_id - }); - for actor in campaign.actors.values_mut() { - actor.relationships.remove(&generated_player_id); - } - let member_actor_ids = brief - .member_actor_ids - .values() - .cloned() - .collect::>(); - if member_actor_ids.len() != brief.characters.len() { - return Err(anyhow!("approved characters must have unique actor IDs")); - } - let mut approved_relationship_targets = canonical_relationship_subject_ids(campaign); - approved_relationship_targets.extend(member_actor_ids.iter().cloned()); - for character in &brief.characters { - if brief.member_actor_ids.get(&character.member_id) != Some(&character.actor_id) { - return Err(anyhow!("character and membership actor binding disagree")); - } - if campaign.actors.contains_key(&character.actor_id) { - return Err(anyhow!("approved actor ID collides with compiled cast")); - } - let mut actor = actor_from_character(character, starting_location.clone()); - actor.relationships = actor - .relationships - .into_iter() - .map(|(subject, relationship)| { - let resolved = relationship_plan - .targets - .get(&(character.member_id.clone(), subject.clone())) - .cloned() - .ok_or_else(|| { - anyhow!("approved character relationship lost its compiled subject") - })?; - Ok((resolved, relationship)) - }) - .collect::>>()?; - if actor - .relationships - .keys() - .any(|id| !approved_relationship_targets.contains(id)) - { - return Err(anyhow!( - "character relationship refers to an unknown canonical subject" - )); - } - campaign.actors.insert(actor.id.clone(), actor); - } - campaign.player_actor_id = host_actor_id; - campaign.name = brief.contract.campaign_name.clone(); - campaign.resolution_policy.active_cell_budget = - (brief.characters.len() as u8).saturating_mul(8).min(128); - campaign.resolution_cover = None; - crate::resolution::ensure_agency_profiles(campaign); - for actor_id in member_actor_ids { - let profile = campaign - .agency_profiles - .get_mut(&actor_id) - .ok_or_else(|| anyhow!("approved actor has no agency profile"))?; - profile.simulation_eligible = false; - } - validate_campaign_seed(campaign)?; - validate_opening_playability(campaign)?; - compiled.0.branch_assumptions.push(format!( - "Campaign contract approved in Session Zero {} at shared digest {}.", - brief.session_zero_id, brief.shared_digest - )); - if !relationship_plan.anchors.is_empty() { - compiled.0.branch_assumptions.push(format!( - "{} private player-approved relationship subject(s) were materialized without exposing their relationship details to the shared opening.", - relationship_plan.anchors.len() - )); - } - Ok(compiled) - } - - pub async fn compile_selected( - &self, - start: SelectedStart, - ) -> Result<(WorldCompilePreview, Vec)> { - let role = start.role.clone(); - let (mut preview, receipts) = self - .compile_custom(CustomStart { - campaign_name: start.campaign_name, - who: format!("{} — {}", start.role.name, start.role.premise), - where_: start.opening.place, - when: start.opening.era, - goal: format!("{}; {}", start.opening.player_hook, start.opening.pressure), - }) - .await?; - let player_id = preview.campaign.player_actor_id.clone(); - let player = preview - .campaign - .actors - .get_mut(&player_id) - .ok_or_else(|| anyhow!("compiled campaign lost its player actor"))?; - player.capabilities.extend(role.capabilities.clone()); - player.obligations.extend(role.obligations.clone()); - preview.branch_assumptions.push(format!( - "The approved generated role '{}' grants the player capabilities [{}] and obligations [{}].", - role.name, - role.capabilities.join(", "), - role.obligations.join(", ") - )); - validate_campaign_seed(&preview.campaign)?; - Ok((preview, receipts)) - } - - pub async fn compile_fission( - &self, - campaign: &Campaign, - request: GestaltFissionRequest, - ) -> Result<( - crate::domain::GestaltFissionPreview, - Vec, - Vec, - )> { - let requested = validate_fission_request(&request)?; - let parent = campaign - .gestalts - .get(&request.parent_gestalt_id) - .ok_or_else(|| anyhow!("fission parent is unknown"))?; - let subject = serde_json::json!({ - "request":request, - "parent":parent, - "member_deltas":campaign.gestalt_members.values().filter(|member| member.gestalt_id == parent.id).collect::>(), - "campaign_time":campaign.world_time, - "canon_cutoff":campaign.branch_origin.canon_cutoff - }); - let (queries, retrieval_receipt) = self - .plan_queries( - "gestalt_fission_retrieval_plan", - &format!("fission:{}:{}", campaign.id, parent.id), - &serde_json::to_string(&subject)?, - 3, - ) - .await?; - let receipts = self - .retrieve_all(&queries, &campaign.branch_origin.canon_cutoff, 12) - .await?; - let base_prompt = format!( - "Refine one canonical leaf gestalt along exactly the requested facet. Produce one child per requested value plus one mandatory child whose value is exactly 'other/unknown'. Every child starts at version 0 and uses an existing campaign location. Each child must copy the parent's shared capabilities, shared knowledge, goals, and pressures exactly; the partition facet belongs to the agency profile and does not silently rewrite the population baseline. Emit one child_partition_values record per child with child_id and value. Exact scarce resources are not inheritable traits: assign every parent resource to exactly one child through a resource_id/child_id record in resource_child_assignments, and make each child's resources set equal exactly the resources assigned to that child. Do not create, duplicate, omit, or rename a resource. Do not erase or rewrite member deltas. Assign a member only when evidence or durable existing delta supports the cut, using a member_id/child_id record; unassigned members will remain in other/unknown. List every material lore gap. This is an approval preview, not a commit. SUBJECT:\n{}\nEVIDENCE:\n{}", - serde_json::to_string(&subject)?, - evidence_text(&receipts), - ); - let schema = serde_json::to_value(schema_for!(CompiledFissionSeed))?; - let mut stages = vec![retrieval_receipt]; - let mut correction = String::new(); - for attempt in 0..2 { - let (value, stage) = self - .structured( - "gestalt_fission_compile", - &format!( - "campaign:{}:revision:{}:fission:{}", - campaign.id, campaign.revision, parent.id - ), - &format!("{base_prompt}{correction}"), - schema.clone(), - receipt_ids(&receipts), - ) - .await?; - stages.push(stage); - let compiled: CompiledFissionSeed = serde_json::from_value(value)?; - let child_partition_values = compiled_assignment_map( - "child partition values", - compiled - .child_partition_values - .iter() - .map(|entry| (entry.child_id.clone(), entry.value.clone())), - )?; - let member_child_assignments = compiled_assignment_map( - "member child assignments", - compiled - .member_child_assignments - .iter() - .map(|entry| (entry.member_id.clone(), entry.child_id.clone())), - )?; - let resource_child_assignments = compiled_assignment_map( - "resource child assignments", - compiled - .resource_child_assignments - .iter() - .map(|entry| (entry.resource_id.clone(), entry.child_id.clone())), - )?; - let residual_child_id = child_partition_values - .iter() - .find(|(_, value)| value.trim().eq_ignore_ascii_case("other/unknown")) - .map(|(id, _)| id.clone()); - let gaps = compiled.gaps.clone(); - let evidence_receipt_ids = receipt_ids(&receipts); - let affected_sources: Vec<_> = receipts - .iter() - .flat_map(|receipt| { - receipt - .witnesses - .iter() - .map(|witness| witness.source_id.clone()) - }) - .collect::>() - .into_iter() - .collect(); - let canon_candidates = gaps - .iter() - .enumerate() - .map(|(index, gap)| crate::domain::CanonCandidate { - schema: "ghostlight.canon_candidate.v1".into(), - id: format!( - "canon-candidate:{}:fission:{}:{}", - campaign.id, - parent.id, - index + 1 - ), - originating_campaign_id: campaign.id, - gap: gap.clone(), - evidence_receipt_ids: evidence_receipt_ids.clone(), - conflicts: vec![], - proposed_wording: format!( - "Clarify population division for {}: {gap}", - parent.name - ), - affected_vault_sources: affected_sources.clone(), - status: "review".into(), - }) - .collect(); - let preview = crate::domain::GestaltFissionPreview { - schema: "ghostlight.gestalt_fission_preview.v1".into(), - campaign_id: campaign.id, - expected_world_revision: campaign.revision, - parent_gestalt_id: parent.id.clone(), - partition_axis: request.partition_axis.clone(), - children: compiled.children, - child_partition_values, - residual_child_id: residual_child_id.unwrap_or_default(), - member_child_assignments, - resource_child_assignments, - evidence_receipt_ids, - gaps, - canon_candidates, - requires_approval: true, - }; - let returned_values: BTreeSet<_> = preview - .child_partition_values - .values() - .map(|value| value.trim().to_ascii_lowercase()) - .filter(|value| value != "other/unknown") - .collect(); - match crate::resolution::validate_fission(campaign, &preview).and_then(|_| { - if returned_values == requested { - Ok(()) - } else { - Err(anyhow!( - "fission did not preserve the requested enumerated cut" - )) - } - }) { - Ok(()) => return Ok((preview, receipts, stages)), - Err(error) if attempt == 0 => { - mark_semantic_invalid( - stages.last_mut().expect("receipt was just stored"), - &error, - ); - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS FISSION: {error}\nReturn one corrected complete preview against the same subject and evidence." - ); - } - Err(error) => { - return Err(anyhow!( - "gestalt fission failed local validation after one correction: {error}" - )); - } - } - } - unreachable!() - } - - async fn resolve_destination_identity( - &self, - campaign: &Campaign, - destination_request: &str, - snapshot_binding: &str, - ) -> Result<(Option, Vec)> { - let mut schema = serde_json::to_value(schema_for!(DestinationIdentityResolution))?; - schema["properties"]["existing_location_id"] = serde_json::json!({ - "anyOf":[ - { - "type":"string", - "enum":campaign.locations.keys().collect::>() - }, - {"type":"null"} - ] - }); - let locations = campaign - .locations - .values() - .map(|location| { - serde_json::json!({ - "id":location.id, - "name":location.name, - "container_id":location.container_id, - }) - }) - .collect::>(); - let base_prompt = format!( - "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nResolve only the identity of the player's primary requested destination. `existing` means the place they ultimately ask to reach, revisit, inspect, or materialize is one exact canonical location in KNOWN LOCATIONS, even when they also ask for missing route detail or a playable approach. Copy that exact ID. `new` means the requested primary destination is a genuinely new place; a new room, district, waystation, refuge, route feature, or site may be new even when its description mentions an existing location as context. Do not treat an existing place as new merely because the request asks the compiler to elaborate it. Do not infer aliases without strong support from the request and supplied names. This stage identifies only; it does not plan routes, compile facts, or change state. Keep rationale to one sentence.\n\nKNOWN LOCATIONS:\n{}\n\nREQUEST:\n{}", - serde_json::to_string(&schema)?, - serde_json::to_string(&locations)?, - destination_request, - ); - let mut correction = String::new(); - let mut receipts = Vec::new(); - for attempt in 0..2 { - let output = match run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "destination_identity_resolution".into(), - model: self.retrieval_model.clone(), - snapshot_binding: snapshot_binding.into(), - lived_stream: format!("{base_prompt}{correction}"), - output_schema: Some(schema.clone()), - source_receipt_ids: vec![], - temperature: Some(0.0), - max_output_tokens: Some(384), - }, - ) - .await - { - Ok(output) => output, - Err(error) => return Err(destination_compilation_failure(error, receipts)), - }; - let mut receipt = output.receipt; - let resolution = output - .structured - .ok_or_else(|| { - anyhow!("destination identity resolver returned no structured output") - }) - .and_then(|value| { - serde_json::from_value::(value) - .map_err(Into::into) - }); - let validated = resolution.and_then(|resolution| { - let rationale_chars = resolution.rationale.trim().chars().count(); - if rationale_chars == 0 || rationale_chars > 500 { - return Err(anyhow!( - "destination identity rationale must contain 1 to 500 characters" - )); - } - match (&resolution.decision, &resolution.existing_location_id) { - (DestinationIdentityDecision::Existing, Some(location_id)) - if campaign.locations.contains_key(location_id) => - { - Ok(Some(location_id.clone())) - } - (DestinationIdentityDecision::New, None) => Ok(None), - (DestinationIdentityDecision::Existing, _) => Err(anyhow!( - "existing destination resolution must name one exact known location" - )), - (DestinationIdentityDecision::New, Some(_)) => Err(anyhow!( - "new destination resolution must not name an existing location" - )), - } - }); - match validated { - Ok(location_id) => { - receipts.push(receipt); - return Ok((location_id, receipts)); - } - Err(error) if attempt == 0 => { - mark_semantic_invalid(&mut receipt, &error); - receipts.push(receipt); - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS IDENTITY RESOLUTION: {error}\nReturn one corrected complete resolution against the same KNOWN LOCATIONS and REQUEST." - ); - } - Err(error) => { - mark_semantic_invalid(&mut receipt, &error); - receipts.push(receipt); - return Err(destination_compilation_failure( - format!( - "destination identity resolution failed local validation after one correction: {error}" - ), - receipts, - )); - } - } - } - unreachable!() - } - - pub async fn compile_destination( - &self, - campaign: &Campaign, - origin_location_id: &str, - destination_request: &str, - ) -> Result<(DestinationCompilationPreview, Vec)> { - validate_user_text("destination request", destination_request, 500)?; - let origin = campaign - .locations - .get(origin_location_id) - .ok_or_else(|| anyhow!("origin location is unknown"))?; - let snapshot = format!("campaign:{}:revision:{}", campaign.id, campaign.revision); - let (existing_destination_id, identity_receipts) = self - .resolve_destination_identity(campaign, destination_request, &snapshot) - .await?; - if let Some(existing_destination_id) = existing_destination_id.as_deref() { - let destination = campaign - .locations - .get(existing_destination_id) - .expect("destination identity resolver was locally validated"); - let Some((_path, _travel_minutes)) = - shortest_location_path(campaign, origin_location_id, existing_destination_id) - else { - return Err(destination_compilation_failure( - format!( - "{} already exists in canonical campaign topology, but no committed route currently reaches it from {}. No substitute location or route preview was created; request a genuinely new intermediary place or resolve the missing topology explicitly.", - destination.name, origin.name, - ), - identity_receipts.clone(), - )); - }; - } - let expansion_origin_location_id = existing_destination_id - .as_deref() - .unwrap_or(origin_location_id); - let expansion_origin = campaign - .locations - .get(expansion_origin_location_id) - .expect("expansion origin is either the validated origin or destination"); - let retrieval_subject = serde_json::to_string(&serde_json::json!({ - "origin": origin, - "elaboration_anchor": expansion_origin, - "existing_destination_id": existing_destination_id, - "destination": destination_request, - "canon_cutoff": campaign.branch_origin.canon_cutoff, - })) - .map_err(|error| destination_compilation_failure(error, identity_receipts.clone()))?; - let (queries, retrieval_receipt) = self - .plan_queries( - "destination_retrieval_plan", - &format!("campaign:{}:revision:{}", campaign.id, campaign.revision), - &retrieval_subject, - 2, - ) - .await - .map_err(|error| destination_compilation_failure(error, identity_receipts.clone()))?; - let receipts = self - .retrieve_all(&queries, &campaign.branch_origin.canon_cutoff, 10) - .await - .map_err(|error| { - destination_compilation_failure( - error, - destination_model_receipts(&identity_receipts, Some(&retrieval_receipt), &[]), - ) - })?; - let source_population_ids = campaign - .gestalts - .values() - .filter(|gestalt| { - gestalt.home_location_id == expansion_origin_location_id - && campaign - .agency_profiles - .get(&gestalt.id) - .is_some_and(|profile| profile.active_leaf) - }) - .map(|gestalt| gestalt.id.clone()) - .collect::>(); - let origin_population_context = campaign - .gestalts - .values() - .filter(|gestalt| source_population_ids.contains(&gestalt.id)) - .map(|gestalt| { - serde_json::json!({ - "id":gestalt.id, - "name":gestalt.name, - "home_location_id":gestalt.home_location_id, - "goals":gestalt.goals, - "pressures":gestalt.pressures, - "named_members":campaign.gestalt_members.values() - .filter(|member| member.gestalt_id == gestalt.id - && member.materialized_actor_id.is_none() - && member.last_location_id.as_deref().unwrap_or(&gestalt.home_location_id) == expansion_origin_location_id) - .map(|member| serde_json::json!({ - "id":member.id, - "name":member.name, - "goals":member.goals, - "obligations":member.obligations, - "memories":member.memories, - })) - .collect::>(), - }) - }) - .collect::>(); - let current_civic_context = civic_context(campaign, expansion_origin_location_id); - let peer_civic_context = - peer_civic_generation_contexts(campaign, expansion_origin_location_id); - let scope_instruction = if let Some(target_id) = existing_destination_id.as_deref() { - format!( - "The primary destination already exists as exact canonical location {target_id}. Elaborate it in place. Never emit that location again, rename it, replace it, or alter its existing routes or container. Every new location must be a bounded child whose containment chain reaches {target_id}; origin_routes are new local routes owned by {target_id}." - ) - } else { - "The primary destination is genuinely new. Admit it and its bounded child detail from the supplied origin without rewriting any existing place.".into() - }; - let completed_model_receipts = |compiler_receipts: &[ModelStageReceipt]| { - destination_model_receipts( - &identity_receipts, - Some(&retrieval_receipt), - compiler_receipts, - ) - }; - let location_generation_context = serde_json::to_string( - &destination_location_generation_context(campaign, expansion_origin_location_id), - ) - .map_err(|error| destination_compilation_failure(error, completed_model_receipts(&[])))?; - let current_civic_apparatus = - serde_json::to_string(¤t_civic_context).map_err(|error| { - destination_compilation_failure(error, completed_model_receipts(&[])) - })?; - let peer_civic_apparatuses = - serde_json::to_string(&peer_civic_context).map_err(|error| { - destination_compilation_failure(error, completed_model_receipts(&[])) - })?; - let source_population_context = - serde_json::to_string(&origin_population_context).map_err(|error| { - destination_compilation_failure(error, completed_model_receipts(&[])) - })?; - let base_prompt = format!( - "Compile only the requested bounded destination region. {scope_instruction} Every new location id must be new. Return explicit origin_routes records owned by expansion anchor id {} into the new region or child locality, and give every such destination a reciprocal route record back to the anchor with the same positive travel time. Every route record needs a stable route_id local to its exact origin, an exact destination_id, a distance, and positive travel_minutes; the same local route_id may exist under another origin without naming the same route. Do not rewrite existing geography. Every place has a non-empty name, valid container, and concrete persistent features. Any locally observable clue must already exist as a fact and list exact discoverable_at_location_ids from the combined existing and new topology; later action assessment can reveal facts but cannot invent them.\n\nUse evidence as canon constraints, not as an exhaustive game map. Missing game-scale routes, geometry, people, ordinary procedures, supplies, local responsibilities, capacity choices, and operating doctrine require the smallest coherent playable elaboration. Mark the resulting facts branch_local or provisional_local and disclose consequential inventions in branch_assumptions. Variation between campaigns is permitted; if a detail must not vary, it belongs in the Vault. Never put a compatible elaboration in gaps merely because the Vault is silent.\n\nWhen CURRENT CIVIC APPARATUS is null, a playable inhabited destination needs one to eight non-overlapping population leaves and two to twelve distinct institutions. Each population and institution needs a materially executable means such as custody, work, mobility, ritual authority, price setting, force, refusal, or mutual aid, not merely a notice channel or aspiration. When it is present, preserve it and add only genuinely new detail needed by the request; population and institution arrays may be empty. New local relations may join new subjects to exact subjects in the current apparatus. Never duplicate a resident body, office, fact, or relation under a fresh name. Each new population home_location_id must be one new location. Each new institution location_ids set may name the jurisdiction or its new children. shared_fact_ids may contain exact fact IDs from the current apparatus or this candidate, never free-text knowledge. collective_authority_id may be null or the exact ID of one new population and denotes real shared authority.\n\nPEER CIVIC DIVERSITY INDEX entries are compact contrast evidence, not complete remote state. Reuse a political form only when shared history or material dependence explains it. Redress need not be a tribunal or petition: exit, kin restitution, feud mediation, ritual appeal, patronage, strike, refusal, and other locally coherent remedies are valid when their power and limits are legible. Preserve mixed, diasporic, and cross-border constituencies; ancestry or species alone is not a sufficient civic partition. Return one complete civic_system manifest for every inhabited candidate. On an existing apparatus it is the next version and must retain every existing governing institution, resident population, public fact, and political relation while adding any new IDs. It must identify the exact jurisdiction, its governing institutions and resident populations, at least one committed public fact in each of four domains—current authority, selection or succession, public resources or revenue, and redress or appeal—and the political relations that make implementation, hierarchy, or contestation legible. Every named resident population must share those public civic facts. If REQUEST presupposes a mayor, election, throne, council, or other office that this locality does not use, commit facts that let a resident correct the premise; never manufacture the requested institution merely to agree with the question. The question selects the missing domain, not its answer.\n\nThe gaps array is legal only when no compatible elaboration can preserve an exact clause of REQUEST without choosing between contradictory canon baselines, inventing an unanchored canon baseline explicitly required by the request, or exceeding an approved capability. Every gap must name that exact premise clause and the exact table choice blocking compilation. `The Vault does not specify X` is never sufficient. Use an empty gaps array when branch-local invention preserves the request.\n\nA migration relation is a directed available path for a later voluntary strategic choice; it does not move anyone, establish that admission occurred, or erase destination-community agency. It may originate only from one exact co-located active population ID supplied below and may target only one new population ID. Emit a relation only when the request and supplied source population/member goals support that migration possibility. Never invent a source population or named member. The approval preview must make all branch-local assumptions explicit without misclassifying them as canon gaps.\n\nCAMPAIGN LOCATION INDEX AND FULL EXPANSION ANCHOR:\n{}\nCURRENT CIVIC APPARATUS:\n{}\nPEER CIVIC DIVERSITY INDEX:\n{}\nCO-LOCATED SOURCE POPULATIONS AND NAMED MEMBER DELTAS:\n{}\nREQUEST:\n{}\nEVIDENCE:\n{}", - expansion_origin_location_id, - location_generation_context, - current_civic_apparatus, - peer_civic_apparatuses, - source_population_context, - destination_request, - evidence_text(&receipts) - ); - let mut schema = - serde_json::to_value(schema_for!(CompiledExpansionSeed)).map_err(|error| { - destination_compilation_failure(error, completed_model_receipts(&[])) - })?; - constrain_destination_expansion_schema(&mut schema, &source_population_ids).map_err( - |error| destination_compilation_failure(error, completed_model_receipts(&[])), - )?; - let admission_evidence_receipt_ids = receipt_ids(&receipts); - let model_causal_source_receipt_ids = identity_receipts - .iter() - .chain(std::iter::once(&retrieval_receipt)) - .map(|receipt| receipt.storage_key().to_owned()) - .chain(admission_evidence_receipt_ids.iter().cloned()) - .collect::>() - .into_iter() - .collect::>(); - let destination_evidence = evidence_text(&receipts); - let mut compiler_receipts: Vec = Vec::new(); - let mut correction = String::new(); - let mut local_corrections = 0; - let mut semantic_regenerations = 0; - let (seed, expansion) = loop { - let output = self - .structured( - "destination_compile", - &snapshot, - &format!("{base_prompt}{correction}"), - schema.clone(), - model_causal_source_receipt_ids.clone(), - ) - .await - .map_err(|error| { - destination_compilation_failure( - error, - completed_model_receipts(&compiler_receipts), - ) - })?; - compiler_receipts.push(output.1); - let seed: CompiledExpansionSeed = match serde_json::from_value(output.0) { - Ok(seed) => seed, - Err(error) => { - return Err(destination_candidate_failure( - error, - &identity_receipts, - &retrieval_receipt, - &mut compiler_receipts, - )); - } - }; - if let Err(error) = validate_compiled_material_gaps(&seed.gaps, &receipts) - .and_then(|_| validate_branch_assumptions(&seed.branch_assumptions)) - .and_then(|_| { - validate_compiled_destination_population_names(campaign, &seed.populations) - }) - { - mark_semantic_invalid( - compiler_receipts - .last_mut() - .expect("receipt was just stored"), - &error, - ); - if local_corrections == 0 { - local_corrections += 1; - correction.push_str(&format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS CANDIDATE: {error}\nReturn a corrected complete candidate against the same CAMPAIGN, REQUEST, and EVIDENCE. Compatible game-scale invention belongs in branch_assumptions, not gaps." - )); - continue; - } - return Err(destination_compilation_failure( - format!( - "destination compiler failed local validation after one correction: {error}" - ), - completed_model_receipts(&compiler_receipts), - )); - } - let mut repair_finding = None; - let mut expansion = match lower_compiled_destination( - campaign, - &seed, - &admission_evidence_receipt_ids, - expansion_origin_location_id, - ) { - Ok(expansion) => Some(expansion), - Err(error) => { - mark_semantic_invalid( - compiler_receipts - .last_mut() - .expect("destination compile receipt was just stored"), - &error, - ); - if seed.civic_system.is_some() { - repair_finding = - Some(DestinationReconciliationFinding::CandidateLowering { - message: error.to_string(), - }); - None - } else if local_corrections == 0 { - local_corrections += 1; - correction.push_str(&format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS CANDIDATE: {error}\nReturn a corrected complete candidate against the same CAMPAIGN, REQUEST, and EVIDENCE." - )); - continue; - } else { - return Err(destination_candidate_failure( - format!( - "destination compiler failed local validation after one correction: {error}" - ), - &identity_receipts, - &retrieval_receipt, - &mut compiler_receipts, - )); - } - } - }; - if repair_finding.is_none() { - let expansion_candidate = expansion - .as_mut() - .expect("a destination without a repair finding was lowered"); - match validate_compiled_destination( - campaign, - expansion_candidate, - existing_destination_id.as_deref(), - ) { - Ok(()) if expansion_candidate.civic_system.is_none() => { - break ( - seed, - expansion - .take() - .expect("validated destination expansion is present"), - ); - } - Ok(()) => { - let verification_sources = model_causal_source_receipt_ids - .iter() - .cloned() - .chain( - compiler_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()), - ) - .collect::>() - .into_iter() - .collect::>(); - match self - .verify_destination_civic_system( - campaign, - destination_request, - &destination_evidence, - ¤t_civic_context, - expansion_candidate, - &snapshot, - &verification_sources, - ) - .await - { - CivicSystemVerificationOutcome::Accepted { receipts } => { - compiler_receipts.extend(receipts); - break ( - seed, - expansion - .take() - .expect("verified destination expansion is present"), - ); - } - CivicSystemVerificationOutcome::Rejected { verdict, receipts } => { - compiler_receipts.extend(receipts); - if semantic_regenerations == 0 { - semantic_regenerations += 1; - correction.push_str(&format!( - "\n\nINDEPENDENT CIVIC VERIFIER REJECTED THE PREVIOUS COMPLETE CANDIDATE:\n{}\nRegenerate the complete destination candidate. You own every candidate field; correct the rejected semantics and prose without weakening the request, evidence, topology, or civic invariants.", - serde_json::to_string(&verdict).unwrap_or_else(|_| verdict.rationale.clone()) - )); - continue; - } - return Err(destination_compilation_failure( - format!( - "destination civic verifier rejected the regenerated candidate: {}", - verdict.rationale.trim() - ), - completed_model_receipts(&compiler_receipts), - )); - } - CivicSystemVerificationOutcome::Failed { message, receipts } => { - compiler_receipts.extend(receipts); - return Err(destination_compilation_failure( - message, - completed_model_receipts(&compiler_receipts), - )); - } - } - } - Err(error) => { - mark_semantic_invalid( - compiler_receipts - .last_mut() - .expect("destination compile receipt was just stored"), - &error, - ); - if seed.civic_system.is_some() { - repair_finding = - Some(DestinationReconciliationFinding::StructuralValidation { - message: error.to_string(), - }); - } else if !seed.populations.is_empty() { - return Err(destination_candidate_failure( - format!( - "inhabited destination cannot be reconciled without a frozen civic manifest: {error}" - ), - &identity_receipts, - &retrieval_receipt, - &mut compiler_receipts, - )); - } else if local_corrections == 0 { - local_corrections += 1; - correction.push_str(&format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS CANDIDATE: {error}\nReturn a corrected complete candidate against the same CAMPAIGN, REQUEST, and EVIDENCE." - )); - continue; - } else { - return Err(destination_candidate_failure( - format!( - "destination compiler failed local validation after one correction: {error}" - ), - &identity_receipts, - &retrieval_receipt, - &mut compiler_receipts, - )); - } - } - } - } - let finding = repair_finding.expect("repairable civic candidate has one finding"); - let reconciliation_sources = model_causal_source_receipt_ids - .iter() - .cloned() - .chain( - compiler_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()), - ) - .collect::>() - .into_iter() - .collect::>(); - match self - .run_destination_reconciliation_agent( - campaign, - destination_request, - &seed, - &finding, - &destination_evidence, - ¤t_civic_context, - expansion_origin_location_id, - existing_destination_id.as_deref(), - &snapshot, - &admission_evidence_receipt_ids, - &reconciliation_sources, - ) - .await - { - Ok(run) => { - compiler_receipts.extend(run.receipts); - break (run.output.seed, run.output.expansion); - } - Err(failure) => { - compiler_receipts.extend(failure.receipts); - return Err(destination_compilation_failure( - failure.message, - completed_model_receipts(&compiler_receipts), - )); - } - } - }; - let evidence_ids = admission_evidence_receipt_ids; - let affected_sources: Vec = receipts - .iter() - .flat_map(|r| r.witnesses.iter().map(|w| w.source_id.clone())) - .collect::>() - .into_iter() - .collect(); - let gap_texts = seed.gaps.iter().map(material_gap_text).collect::>(); - let candidates = gap_texts - .iter() - .enumerate() - .map(|(index, gap)| crate::domain::CanonCandidate { - schema: "ghostlight.canon_candidate.v1".into(), - id: format!( - "canon-candidate:{}:r{}:{}", - campaign.id, - campaign.revision, - index + 1 - ), - originating_campaign_id: campaign.id, - gap: gap.clone(), - evidence_receipt_ids: evidence_ids.clone(), - conflicts: vec![], - proposed_wording: format!("Clarify the documented answer to: {gap}"), - affected_vault_sources: affected_sources.clone(), - status: "review".into(), - }) - .collect(); - let preview = if let Some(target_location_id) = existing_destination_id { - DestinationCompilationPreview::LocalityElaboration(LocalityElaborationPreview { - schema: "ghostlight.locality_elaboration_preview.v1".into(), - campaign_id: campaign.id, - expected_revision: campaign.revision, - elaboration: LocalityElaboration { - target_location_id, - expansion, - }, - evidence_receipts: receipts, - branch_assumptions: seed.branch_assumptions, - gaps: gap_texts, - canon_candidates: candidates, - requires_approval: true, - }) - } else { - DestinationCompilationPreview::RegionExpansion(crate::domain::RegionExpansionPreview { - schema: "ghostlight.region_expansion_preview.v1".into(), - campaign_id: campaign.id, - expected_revision: campaign.revision, - expansion, - evidence_receipts: receipts, - branch_assumptions: seed.branch_assumptions, - gaps: gap_texts, - canon_candidates: candidates, - requires_approval: true, - }) - }; - Ok((preview, completed_model_receipts(&compiler_receipts))) - } - - async fn retrieve_all( - &self, - queries: &[String], - temporal_scope: &str, - limit: u8, - ) -> Result> { - self.retrieve_all_with_visibility(queries, temporal_scope, limit, false) - .await - } - - async fn retrieve_all_player_visible( - &self, - queries: &[String], - temporal_scope: &str, - limit: u8, - ) -> Result> { - self.retrieve_all_with_visibility(queries, temporal_scope, limit, true) - .await - } - - async fn retrieve_all_with_visibility( - &self, - queries: &[String], - temporal_scope: &str, - limit: u8, - player_visible_only: bool, - ) -> Result> { - let mut receipts = Vec::new(); - for query in queries { - let mut authority_lanes = vec![self.vault_id.clone()]; - if player_visible_only { - authority_lanes.push("visibility.player".into()); - } - receipts.push( - self.vault - .search(&VaultQuery { - query: query.clone(), - authority_lanes, - temporal_scope: temporal_scope.into(), - limit, - }) - .await?, - ); - } - if receipts.iter().all(|r| r.witnesses.is_empty()) { - return Err(anyhow!("Vault returned no evidence; compilation refused")); - } - let source_ids = receipts - .iter() - .flat_map(|receipt| { - receipt - .witnesses - .iter() - .map(|witness| witness.source_id.clone()) - }) - .collect::>(); - let mut tasks = tokio::task::JoinSet::new(); - for source_id in source_ids { - let vault = self.vault.clone(); - tasks.spawn(async move { - let exact = vault.exact_document(&source_id).await?; - Ok::<_, anyhow::Error>((source_id, exact)) - }); - } - let mut exact_documents = BTreeMap::new(); - while let Some(result) = tasks.join_next().await { - let (source_id, exact) = result??; - exact_documents.insert(source_id, exact); - } - for witness in receipts - .iter_mut() - .flat_map(|receipt| receipt.witnesses.iter_mut()) - { - let exact = exact_documents - .get(&witness.source_id) - .ok_or_else(|| anyhow!("Vault omitted exact document for {}", witness.source_id))?; - if !normalized_contains(&exact.excerpt, &witness.excerpt) { - return Err(anyhow!( - "retrieval excerpt is not witnessed by exact document {}", - witness.source_id - )); - } - witness.content_hash = exact.content_hash.clone(); - } - Ok(receipts) - } - - async fn plan_queries( - &self, - stage: &str, - binding: &str, - subject: &str, - count: usize, - ) -> Result<(Vec, ModelStageReceipt)> { - let schema = serde_json::to_value(schema_for!(RetrievalQueryPlan))?; - let prompt = format!( - "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nPlan exactly {count} distinct source-search queries for the supplied subject. Each query must be a concise natural-language search string of 1 to 240 Unicode characters. Preserve proper nouns, era, place, institutions, mechanics, geography, and pressure when relevant. When the subject contains an approved_contract, at least one query must directly target its named canon_horizon; synthesize a bounded search query instead of copying an overlong paragraph verbatim. Do not answer the subject. SUBJECT:\n{subject}", - serde_json::to_string(&schema)? - ); - let output = run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: stage.into(), - model: self.retrieval_model.clone(), - snapshot_binding: binding.into(), - lived_stream: prompt, - output_schema: Some(schema), - source_receipt_ids: vec![], - temperature: Some(0.0), - max_output_tokens: Some(512), - }, - ) - .await?; - let plan: RetrievalQueryPlan = serde_json::from_value( - output - .structured - .ok_or_else(|| anyhow!("retrieval planner returned no structured output"))?, - )?; - let normalized = plan - .queries - .into_iter() - .map(|query| query.trim().to_owned()) - .collect::>(); - let unique = normalized.iter().collect::>(); - if normalized.len() != count || unique.len() != count { - return Err(anyhow!( - "retrieval planner must return exactly {count} distinct queries" - )); - } - if normalized - .iter() - .any(|query| query.is_empty() || query.chars().count() > 240) - { - return Err(anyhow!( - "retrieval planner query must contain 1 to 240 characters" - )); - } - Ok((normalized, output.receipt)) - } - - async fn plan_opening_queries( - &self, - request: &OpeningRequest, - ) -> Result<(Vec, ModelStageReceipt)> { - let schema = serde_json::to_value(schema_for!(OpeningRetrievalPlan))?; - let prompt = format!( - "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nPlan three source-search queries for distinct historical frames in the requested setting. `early_frame_query` must seek the earliest well-documented playable period and its geography and pressure. `transition_frame_query` must seek a materially later transition, shunt, collapse, migration, or institutional realignment. `late_frame_query` must seek the latest well-documented playable period and a different geography and pressure. Use setting-specific terms from the request where available. Each value is only a concise natural-language search query of 1 to 240 Unicode characters; do not answer the request. REQUEST:\n{}", - serde_json::to_string(&schema)?, - serde_json::to_string(request)? - ); - let output = run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "opening_retrieval_plan".into(), - model: self.retrieval_model.clone(), - snapshot_binding: "opening-suggestions".into(), - lived_stream: prompt, - output_schema: Some(schema), - source_receipt_ids: vec![], - temperature: Some(0.0), - max_output_tokens: Some(512), - }, - ) - .await?; - let plan: OpeningRetrievalPlan = - serde_json::from_value(output.structured.ok_or_else(|| { - anyhow!("opening retrieval planner returned no structured output") - })?)?; - let queries = vec![ - plan.early_frame_query.trim().to_owned(), - plan.transition_frame_query.trim().to_owned(), - plan.late_frame_query.trim().to_owned(), - ]; - let unique = queries.iter().collect::>(); - if unique.len() != 3 { - return Err(anyhow!( - "opening retrieval planner must return three distinct historical-frame queries" - )); - } - if queries - .iter() - .any(|query| query.is_empty() || query.chars().count() > 240) - { - return Err(anyhow!( - "opening retrieval query must contain 1 to 240 characters" - )); - } - Ok((queries, output.receipt)) - } - - async fn classify_evidence( - &self, - start: &CustomStart, - approved_contract: Option<&CampaignContract>, - receipts: &[VaultEvidenceReceipt], - ) -> Result<(Vec, Vec)> { - let mut source_briefs = BTreeMap::new(); - for witness in receipts.iter().flat_map(|receipt| &receipt.witnesses) { - source_briefs - .entry(witness.source_id.clone()) - .or_insert_with(|| { - serde_json::json!({ - "source_id":witness.source_id, - "authority_lane":witness.authority_lane, - "temporal_scope":witness.temporal_scope, - "excerpt":witness.excerpt.chars().take(1_200).collect::(), - }) - }); - } - let expected: BTreeSet<_> = source_briefs.keys().cloned().collect(); - let authority_by_source = receipts - .iter() - .flat_map(|receipt| receipt.witnesses.iter()) - .map(|witness| (witness.source_id.clone(), witness.authority_lane.clone())) - .collect::>(); - // Keep the provider schema stable across campaigns for prefix-cache reuse. - // Exact membership and cardinality belong to the local validator below. - let schema = serde_json::to_value(schema_for!(EvidenceUsePlan))?; - let approved_contract_context = approved_contract - .map(serde_json::to_string) - .transpose()? - .unwrap_or_else(|| "null".into()); - let base_prompt = format!( - "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nClassify every supplied source exactly once for this requested custom start. When APPROVED CONTRACT is present, its premise and canon_horizon are retrieval authority: a source that directly witnesses a named canon anchor belongs in direct_seed even when the requested opening geometry is branch-local. direct_seed means the source directly supports this specific local place, era, role, goal, pressure, canon anchor, or a causal actor/institution that should actually be present. setting_background means the source supports general setting history, mechanics, geography, or institution identity, but its story-specific cast, incident, clocks, goals, and postures must not be imported into the new branch. excluded means it is merely nearby in search space. A shared place name or era alone does not make another story episode current. Keep each rationale to one short sentence.\nSTART:\n{}\nAPPROVED CONTRACT:\n{}\nSOURCES:\n{}", - serde_json::to_string(&schema)?, - serde_json::to_string(start)?, - approved_contract_context, - serde_json::to_string(&source_briefs.values().collect::>())?, - ); - let source_receipt_ids = receipt_ids(receipts); - let mut stage_receipts = Vec::new(); - let mut correction = String::new(); - for attempt in 0..2 { - let output = run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "evidence_relevance".into(), - model: self.retrieval_model.clone(), - snapshot_binding: "custom-start".into(), - lived_stream: format!("{base_prompt}{correction}"), - output_schema: Some(schema.clone()), - source_receipt_ids: source_receipt_ids.clone(), - temperature: Some(0.0), - max_output_tokens: Some(2_500), - }, - ) - .await?; - let candidate = output - .structured - .clone() - .ok_or_else(|| anyhow!("evidence classifier returned no structured output")) - .and_then(|value| serde_json::from_value::(value).map_err(Into::into)) - .and_then(|plan| { - let mut counts = BTreeMap::::new(); - for item in &plan.coverage { - *counts.entry(item.source_id.clone()).or_default() += 1; - } - let actual = counts.keys().cloned().collect::>(); - let missing = expected.difference(&actual).cloned().collect::>(); - let unexpected = actual.difference(&expected).cloned().collect::>(); - let duplicates = counts - .iter() - .filter(|(_, count)| **count > 1) - .map(|(source_id, count)| format!("{source_id} ({count} times)")) - .collect::>(); - let empty_rationales = plan - .coverage - .iter() - .filter(|item| item.rationale.trim().is_empty()) - .map(|item| item.source_id.clone()) - .collect::>(); - if !missing.is_empty() - || !unexpected.is_empty() - || !duplicates.is_empty() - || !empty_rationales.is_empty() - { - return Err(anyhow!( - "evidence classifier must cover every exact source once with a rationale; missing={missing:?}; unexpected={unexpected:?}; duplicates={duplicates:?}; empty_rationales={empty_rationales:?}" - )); - } - if let Some(item) = plan.coverage.iter().find(|item| { - item.lane == EvidenceUseLane::DirectSeed - && authority_by_source - .get(&item.source_id) - .is_some_and(|lane| !authority_allows_direct_seed(lane)) - }) { - return Err(anyhow!( - "source {} belongs to authority lane {} and cannot seed a new branch directly", - item.source_id, - authority_by_source - .get(&item.source_id) - .expect("source coverage was validated") - )); - } - Ok(plan.coverage) - }); - let mut receipt = output.receipt; - match candidate { - Ok(coverage) => { - stage_receipts.push(receipt); - return Ok((coverage, stage_receipts)); - } - Err(error) if attempt == 0 => { - mark_semantic_invalid(&mut receipt, &error); - stage_receipts.push(receipt); - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS CLASSIFICATION: {error}\nPREVIOUS_REJECTED_CLASSIFICATION:\n{}\nReturn one corrected complete classification against the same START and SOURCES. Preserve valid records, add every missing literal source_id, remove unexpected or duplicate records, and supply every missing rationale.", - output - .structured - .as_ref() - .map(serde_json::to_string) - .transpose()? - .unwrap_or_else(|| "null".into()) - ); - } - Err(error) => { - return Err(anyhow!( - "evidence classifier failed local validation after one correction: {error}" - )); - } - } - } - unreachable!() - } - - async fn compile_global_agency_catalog( - &self, - start: &CustomStart, - receipts: &[VaultEvidenceReceipt], - ) -> Result<(CompiledGlobalAgencyCatalog, Vec)> { - let receipts = canonical_worldbuilding_receipts(receipts); - let schema = serde_json::to_value(schema_for!(ExtractedGlobalAgencyCatalog))?; - let base_prompt = format!( - "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nExtract evidence for the coarse remote strategic agency catalog at the requested historical horizon. This stage extracts; it does not write simulation doctrine. Include major powers and strategically distinct movements supported by the supplied witnesses. For each candidate, copy its exact displayed name and 1-3 contiguous supporting_claims verbatim from institution-specific source prose; every claim must contain 1 to 320 Unicode characters. A claim may establish the institution's existence or identity, or an explicit role, interest, method, constraint, refusal, or pressure. Exact institution-specific evidence of existence is enough to admit a major power; missing operational detail will be compiled later as branch-local doctrine. Do not use mere index links, shared headings, category descriptions, movement lists, or story-specific incidents. Do not infer current posture, territory, capability inventory, or branch facts. Report a material evidence gap only when the witnesses cannot anchor the institution or historical horizon at all, not merely because they omit game-scale doctrine, routes, or daily operations. Return no narrative analysis.\nHORIZON:\n{}\nREQUESTED PLACE (relevance only; not local authority):\n{}\nEVIDENCE:\n{}", - serde_json::to_string(&schema)?, - start.when, - start.where_, - bounded_evidence_text(&receipts, 1_200), - ); - let source_receipt_ids = receipt_ids(&receipts); - let mut stage_receipts = Vec::new(); - let mut correction = String::new(); - for attempt in 0..2 { - let output = run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "global_agency_compile".into(), - model: self.retrieval_model.clone(), - snapshot_binding: format!("global-agency:{}", start.when), - lived_stream: format!("{base_prompt}{correction}"), - output_schema: Some(schema.clone()), - source_receipt_ids: source_receipt_ids.clone(), - temperature: Some(0.0), - max_output_tokens: Some(5_000), - }, - ) - .await?; - let candidate = output - .structured - .clone() - .ok_or_else(|| anyhow!("global agency compiler returned no structured output")) - .and_then(|value| { - serde_json::from_value::(value) - .map_err(Into::into) - }) - .and_then(|catalog| ground_global_agency_catalog(catalog, &receipts)); - let mut receipt = output.receipt; - match candidate { - Ok((catalog, grounding_gaps)) => { - if !grounding_gaps.is_empty() { - receipt.validation_result = "valid_with_grounding_gaps".into(); - receipt.local_validation_error = - Some(grounding_gaps.join("; ").chars().take(1_000).collect()); - } - stage_receipts.push(receipt); - let (catalog, mut doctrine_receipts) = self - .synthesize_global_agency_doctrine(start, catalog) - .await?; - stage_receipts.append(&mut doctrine_receipts); - return Ok((catalog, stage_receipts)); - } - Err(error) if attempt == 0 => { - mark_semantic_invalid(&mut receipt, &error); - stage_receipts.push(receipt); - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS GLOBAL AGENCY CATALOG: {error}\nPREVIOUS_REJECTED_CATALOG:\n{}\nReturn one corrected complete catalog against the same HORIZON and EVIDENCE. Shorten or replace the exact invalid claim while preserving verbatim source grounding.", - output - .structured - .as_ref() - .map(serde_json::to_string) - .transpose()? - .unwrap_or_else(|| "null".into()) - ); - } - Err(error) => { - return Err(anyhow!( - "global agency compiler failed local validation after one correction: {error}" - )); - } - } - } - unreachable!() - } - - async fn synthesize_global_agency_doctrine( - &self, - start: &CustomStart, - grounded: GroundedGlobalAgencyCatalog, - ) -> Result<(CompiledGlobalAgencyCatalog, Vec)> { - if grounded.institutions.is_empty() { - return Ok(( - CompiledGlobalAgencyCatalog { - institutions: vec![], - gaps: grounded.gaps, - }, - vec![], - )); - } - let evidence = grounded.institutions.iter().map(|institution| { - serde_json::json!({"name": institution.name, "supporting_claims": institution.supporting_claims}) - }).collect::>(); - let synthesis_schema = serde_json::to_value(schema_for!(StrategicDoctrineCatalog))?; - let synthesis_prompt = format!( - "Synthesize one concise strategic_doctrine for every supplied institution. Doctrine is durable branch-local simulation state, not a claim that the Vault exhaustively specified policy. Preserve every canon anchor in the supplied exact claims, then fill missing operational detail with the smallest coherent interests, characteristic methods, constraints, or refusals needed for this institution to make meaningful strategic decisions at the requested horizon. Compatible elaboration is required and may vary between campaigns; absence from the claims is not itself a gap. Do not contradict or erase a supplied claim, merge institutions, borrow story-specific incidents, assert that an invented detail is sourced canon, or grant setting-breaking power without an anchor. Do not invent a current branch event or posture; those belong to later simulation state. Return the same names exactly once and no others. Keep each doctrine under 600 characters.\nHORIZON:\n{}\nCANON ANCHORS:\n{}", - start.when, - serde_json::to_string(&evidence)? - ); - let verification_schema = serde_json::to_value(schema_for!(StrategicDoctrineVerification))?; - let source_receipt_ids = grounded - .institutions - .iter() - .flat_map(|i| i.evidence_receipt_ids.clone()) - .collect::>(); - let mut stage_receipts = Vec::new(); - let mut correction = String::new(); - for attempt in 0..=1 { - let (value, mut synthesis_receipt) = self - .structured( - "global_agency_doctrine_synthesis", - &format!("global-agency-doctrine:{}", start.when), - &format!("{synthesis_prompt}{correction}"), - synthesis_schema.clone(), - source_receipt_ids.clone(), - ) - .await?; - let synthesized: StrategicDoctrineCatalog = serde_json::from_value(value)?; - if let Err(error) = validate_doctrine_catalog(&grounded.institutions, &synthesized) { - mark_semantic_invalid(&mut synthesis_receipt, &error); - stage_receipts.push(synthesis_receipt); - if attempt == 0 { - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS DOCTRINE CATALOG: {error}\nReturn one corrected complete catalog against the same CANON ANCHORS." - ); - continue; - } - return Err(anyhow!( - "strategic doctrine synthesis failed local validation after one correction: {error}" - )); - } - stage_receipts.push(synthesis_receipt); - - let verification_prompt = format!( - "Verify each strategic doctrine as canon-constrained branch elaboration. compatible_with_canon is true when the doctrine preserves every supplied canon anchor, does not contradict or erase one, does not merge institutions or borrow a story-specific incident, and remains a plausible bounded policy at the requested horizon. The doctrine is intentionally allowed to invent missing operational interests, methods, constraints, refusals, and reasons as branch-local state. Do not reject a clause merely because the anchors are silent about it, and do not pretend an elaboration was stated by the source. Reject actual contradiction, canon erasure, identity conflation, an invented current branch event, or unanchored setting-breaking power. Return one verdict for each name exactly once.\nHORIZON:\n{}\nCANON ANCHORS:\n{}\nBRANCH DOCTRINES:\n{}", - start.when, - serde_json::to_string(&evidence)?, - serde_json::to_string(&synthesized)? - ); - let (value, mut verification_receipt) = self - .structured( - "global_agency_doctrine_verification", - &format!("global-agency-doctrine-verification:{}", start.when), - &verification_prompt, - verification_schema.clone(), - source_receipt_ids.clone(), - ) - .await?; - let verification: StrategicDoctrineVerification = serde_json::from_value(value)?; - match validate_doctrine_verification(&grounded.institutions, &verification) { - Ok(incompatible) if incompatible.is_empty() => { - stage_receipts.push(verification_receipt); - let catalog = lower_compatible_doctrine_catalog(grounded, synthesized); - return Ok((catalog, stage_receipts)); - } - Ok(incompatible) if attempt == 0 => { - let error = doctrine_incompatibility_error(&incompatible); - mark_semantic_invalid(&mut verification_receipt, &error); - stage_receipts.push(verification_receipt); - correction = format!( - "\n\nTHE COMPATIBILITY VERIFIER REJECTED THE PREVIOUS BRANCH DOCTRINES: {error}\nRewrite the complete catalog against the same CANON ANCHORS. Remove the contradiction, canon erasure, identity conflation, branch event, or unanchored setting-breaking power identified by the verifier while retaining useful compatible branch elaboration. Do not collapse back to quotation when a playable doctrine can be generated.\nPREVIOUS DOCTRINES:\n{}", - serde_json::to_string(&synthesized)? - ); - } - Ok(incompatible) => { - let error = doctrine_incompatibility_error(&incompatible); - mark_semantic_invalid(&mut verification_receipt, &error); - stage_receipts.push(verification_receipt); - return Err(anyhow!( - "strategic doctrine contradicted canon after one correction: {error}" - )); - } - Err(error) if attempt == 0 => { - mark_semantic_invalid(&mut verification_receipt, &error); - stage_receipts.push(verification_receipt); - correction = format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS DOCTRINE VERIFICATION: {error}\nReturn one corrected verdict for every grounded institution exactly once against the same CANON ANCHORS and BRANCH DOCTRINES." - ); - } - Err(error) => { - mark_semantic_invalid(&mut verification_receipt, &error); - return Err(anyhow!( - "strategic doctrine verification failed local validation after one correction: {error}" - )); - } - } - } - unreachable!() - } - - #[allow(clippy::too_many_arguments)] - async fn run_destination_reconciliation_agent( - &self, - campaign: &Campaign, - destination_request: &str, - seed: &CompiledExpansionSeed, - finding: &DestinationReconciliationFinding, - evidence: &str, - current_civic_context: &Option, - expansion_origin_location_id: &str, - existing_destination_id: Option<&str>, - snapshot: &str, - admission_evidence_receipt_ids: &[String], - causal_source_receipt_ids: &[String], - ) -> std::result::Result< - crate::agent::ModelAgentRun, - crate::agent::ModelAgentFailure, - > { - if seed.civic_system.is_none() { - return Err(crate::agent::ModelAgentFailure { - message: "destination reconciliation agent requires a frozen civic candidate" - .into(), - receipts: Vec::new(), - }); - } - let frozen_projection = serde_json::json!({ - "candidate_facts":&seed.facts, - "campaign_fact_namespace":campaign.facts.values().map(|fact| serde_json::json!({ - "id":fact.id, - "statement":fact.statement, - })).collect::>(), - "resident_fact_knowledge":seed.populations.iter().map(|population| serde_json::json!({ - "population_id":population.id, - "name":population.name, - "fact_ids":population.shared_fact_ids, - })).collect::>(), - "institutions":&seed.institutions, - "local_relations":&seed.local_relations, - "civic_system":&seed.civic_system, - "immutable_geography":{ - "origin_routes":&seed.origin_routes, - "locations":&seed.locations, - "migration_relations":&seed.migration_relations, - }, - "immutable_material_classification":{ - "branch_assumptions":&seed.branch_assumptions, - "gaps":&seed.gaps, - }, - }); - let frozen_projection = serde_json::to_string(&frozen_projection).map_err(|error| { - crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts: Vec::new(), - } - })?; - let mut schema = serde_json::to_value(schema_for!(DestinationReconciliationToolAction)) - .map_err(|error| crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts: Vec::new(), - })?; - constrain_civic_reconciliation_action_schema(&mut schema, seed).map_err(|error| { - crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts: Vec::new(), - } - })?; - let initial_finding = - serde_json::to_string(finding).map_err(|error| crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts: Vec::new(), - })?; - let draft = - civic_reconciliation_draft(seed).map_err(|error| crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts: Vec::new(), - })?; - let seed_bytes = - serde_json::to_vec(seed).map_err(|error| crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts: Vec::new(), - })?; - let binding = format!( - "{snapshot}:destination-reconciliation-agent:sha256:{:x}", - Sha256::digest(seed_bytes) - ); - let instructions = format!( - "You are the autonomous destination reconciliation worker. World invention has already happened. You operate a private candidate workbench through small typed actions. Use validate_current when the typed finding may be a false negative or a fresh independent verdict is sufficient. Use revise_and_validate for a bounded transactional batch of only the edits needed to answer the finding. The tool preserves valid draft edits between steps, runs the actual fact, lowering, structural, and independent civic validators after every action, and returns exact observations.\n\nYour writable authority is deliberately narrow: replace a fact at its stable frozen slot; set one exact resident population's complete fact-ID knowledge; update operational resources, posture, facets, and information channels for one exact frozen institution; add, replace, or remove local political relations; and update civic-manifest membership and fact lanes. A single batch may atomically repair a fact ID and every reference to it. You cannot change institution IDs, names, goals, or locations; population IDs, names, homes, goals, pressures, or capabilities; jurisdiction; geography; routes; migration; branch assumptions; or gaps. Never copy a campaign fact into candidate facts under the same or a new ID; reference exact campaign IDs only where resident knowledge legitimately uses already committed facts. Do not resubmit the complete candidate. Only the tool can declare success.\n\nREQUEST:\n{}\n\nINITIAL TYPED FINDING:\n{}\n\nFROZEN DESTINATION PROJECTION AND READ-ONLY NAMESPACE:\n{}", - destination_request, initial_finding, frozen_projection, - ); - let spec = ModelAgentSpec { - stage: "destination_reconciliation_agent_action".into(), - model: MODEL_BALANCED.into(), - snapshot_binding: binding, - instructions, - source_receipt_ids: causal_source_receipt_ids.to_vec(), - temperature: Some(0.0), - max_output_tokens: Some(2_500), - max_steps: MAX_DESTINATION_RECONCILIATION_AGENT_STEPS, - }; - let mut tool = DestinationReconciliationAgentTool { - compiler: self, - campaign, - destination_request, - evidence, - current_civic_context, - frozen_seed: seed, - draft, - expansion_origin_location_id, - existing_destination_id, - snapshot, - admission_evidence_receipt_ids, - action_schema: schema, - }; - run_model_agent(self.model.as_ref(), &spec, &mut tool).await - } - - #[allow(clippy::too_many_arguments)] - async fn verify_destination_civic_system( - &self, - campaign: &Campaign, - destination_request: &str, - evidence: &str, - current_civic_context: &Option, - expansion: &mut crate::domain::RegionExpansion, - snapshot: &str, - sources: &[String], - ) -> CivicSystemVerificationOutcome { - let civic_system = expansion - .civic_system - .as_ref() - .expect("civic verification is called only for an inhabited apparatus"); - let previous_resident_fact_knowledge = campaign - .civic_systems - .get(&civic_system.jurisdiction_location_id) - .into_iter() - .flat_map(|system| system.resident_population_ids.iter()) - .filter_map(|id| campaign.gestalts.get(id)) - .map(|population| { - Self::civic_resident_fact_projection(population, campaign.facts.values()) - }) - .collect::>(); - let new_resident_fact_knowledge = expansion - .populations - .iter() - .map(|population| { - Self::civic_resident_fact_projection( - population, - campaign.facts.values().chain(expansion.facts.iter()), - ) - }) - .collect::>(); - let candidate = match serde_json::to_string(&serde_json::json!({ - "previous_civic_apparatus":current_civic_context, - "peer_civic_apparatuses":peer_civic_contexts( - campaign, - &civic_system.jurisdiction_location_id, - ), - "complete_candidate":expansion, - "previous_resident_fact_knowledge":previous_resident_fact_knowledge, - "civic_system":civic_system, - "new_facts":&expansion.facts, - "new_institutions":&expansion.institutions, - "new_local_relations":&expansion.local_relations, - "new_resident_populations":new_resident_fact_knowledge, - })) { - Ok(candidate) => candidate, - Err(error) => { - return CivicSystemVerificationOutcome::Failed { - message: error.to_string(), - receipts: Vec::new(), - }; - } - }; - let base_prompt = format!( - "Independently verify the admitted civic apparatus. Judge meaning, not JSON shape. The public facts must actually explain current authority, selection or succession, public resources or revenue, and redress or appeal. The institutions and political relations must form a coherent local apparatus. Use previous_resident_fact_knowledge and each new resident population's exact shared_fact_ids as the authoritative identity projection for deciding whether every resident can ground an ordinary answer about local government; raw shared_knowledge elsewhere is canonical statement text, not a missing ID field. A question may select a civic domain but must not have forced its presupposed office, election, or answer into the candidate. Compare complete_candidate with peer_civic_apparatuses. A reused political form passes only when shared history or material dependence explains it; redress may be exit, restitution, mediation, ritual appeal, patronage, strike, refusal, or another locally effective path rather than a tribunal. Confirm opposed populations and institutions possess different executable means in their capabilities, resources, relationships, and operating posture, not merely different notices. Confirm constituencies cross ancestry, species, and jurisdictional boundaries where the setting supports it; a locally homogeneous constituency passes only when the candidate gives a material reason rather than using ancestry or species as its civic partition by default. Separately confirm every explicit REQUEST constraint is satisfied: a request that requires a mixed, diasporic, or cross-border constituency cannot be waived by a good explanation for local homogeneity, and exact requested counts or forms remain exact. Reject public population or institution names that repeat an overused surname, epithet, grammatical mold, bureaucratic construction, or lightly varied quota template across this candidate or peer civic apparatuses unless shared history or material dependence grounds the resemblance. Inspect every human-readable string field in complete_candidate, excluding stable IDs and schema tags. Reject clipped words, unfinished sentences, placeholder fragments, and corrupted prose in facts, names, goals, pressures, capabilities, knowledge, resources, posture, persistent features, route distances, facet values, information channels, and relation descriptions. Do not rewrite or complete the candidate; return verdicts only.\n\nREQUEST:\n{}\nEVIDENCE:\n{}\nCANDIDATE:\n{}", - destination_request, evidence, candidate, - ); - let schema = match serde_json::to_value(schema_for!(CivicSystemVerification)) { - Ok(schema) => schema, - Err(error) => { - return CivicSystemVerificationOutcome::Failed { - message: error.to_string(), - receipts: Vec::new(), - }; - } - }; - let (value, mut receipt) = match self - .structured( - "destination_civic_verification", - snapshot, - &base_prompt, - schema, - sources.to_vec(), - ) - .await - { - Ok(output) => output, - Err(error) => { - return CivicSystemVerificationOutcome::Failed { - message: error.to_string(), - receipts: Vec::new(), - }; - } - }; - let verdict = match serde_json::from_value::(value) { - Ok(verdict) => verdict, - Err(error) => { - mark_semantic_invalid(&mut receipt, &error); - return CivicSystemVerificationOutcome::Failed { - message: error.to_string(), - receipts: vec![receipt], - }; - } - }; - let rationale_chars = verdict.rationale.trim().chars().count(); - let accepted = rationale_chars > 0 - && rationale_chars <= 1_000 - && verdict.authority_legible - && verdict.selection_or_succession_legible - && verdict.public_resources_legible - && verdict.redress_legible - && verdict.institutional_relations_coherent - && verdict.resident_answer_grounded - && verdict.political_form_distinct_or_deliberately_shared - && verdict.opposed_interests_have_distinct_means - && verdict.constituencies_cross_boundaries_or_local_homogeneity_justified - && verdict.explicit_request_constraints_satisfied - && verdict.public_names_do_not_repeat_an_overused_template - && verdict.candidate_text_intact; - if !accepted { - let error = anyhow!( - "destination civic verifier rejected the candidate: {}", - verdict.rationale.trim() - ); - mark_semantic_invalid(&mut receipt, &error); - return CivicSystemVerificationOutcome::Rejected { - verdict, - receipts: vec![receipt], - }; - } - let candidate_digest = match civic_candidate_digest(expansion) { - Ok(digest) => digest, - Err(error) => { - mark_semantic_invalid(&mut receipt, &error); - return CivicSystemVerificationOutcome::Failed { - message: error.to_string(), - receipts: vec![receipt], - }; - } - }; - receipt.rebind_snapshot(civic_verifier_binding(campaign, &candidate_digest)); - expansion - .civic_system - .as_mut() - .expect("verified civic system remains present") - .semantic_verification_receipt_id = receipt.storage_key().to_owned(); - CivicSystemVerificationOutcome::Accepted { - receipts: vec![receipt], - } - } - - fn civic_resident_fact_projection<'a>( - population: &crate::domain::GestaltPersonaState, - facts: impl Iterator, - ) -> serde_json::Value { - let shared_fact_ids = facts - .filter(|fact| population.shared_knowledge.contains(&fact.statement)) - .map(|fact| fact.id.clone()) - .collect::>(); - serde_json::json!({ - "id":population.id, - "name":population.name, - "shared_fact_ids":shared_fact_ids, - }) - } - - /// Independently verifies a complete titled-elaboration candidate without - /// granting the verifier any rewrite authority. Accepted and rejected - /// receipts are bound to the exact compiler candidate before inference so - /// recovery cannot attach a verdict to another draft. - pub async fn verify_titled_locality_elaboration( - &self, - campaign: &Campaign, - destination_request: &str, - evidence: &str, - elaboration: &LocalityElaboration, - causal_source_receipt_ids: &[String], - ) -> Result { - validate_locality_elaboration(campaign, elaboration)?; - let mut expansion = elaboration.expansion.clone(); - let current_civic_context = civic_context(campaign, &elaboration.target_location_id); - let snapshot = titled_civic_verifier_binding(campaign, elaboration)?; - match self - .verify_destination_civic_system( - campaign, - destination_request, - evidence, - ¤t_civic_context, - &mut expansion, - &snapshot, - causal_source_receipt_ids, - ) - .await - { - CivicSystemVerificationOutcome::Accepted { mut receipts } => receipts - .pop() - .ok_or_else(|| anyhow!("civic verifier accepted without a receipt")), - CivicSystemVerificationOutcome::Rejected { verdict, receipts } => { - let semantic_diagnostic = civic_verification_semantic_diagnostic(&verdict); - Err(anyhow::Error::new(CivicElaborationVerificationFailure { - message: format!( - "titled elaboration civic verifier rejected the candidate: {}", - verdict.rationale.trim() - ), - semantic_diagnostic: Some(semantic_diagnostic), - model_receipts: receipts, - })) - } - CivicSystemVerificationOutcome::Failed { message, receipts } => { - Err(anyhow::Error::new(CivicElaborationVerificationFailure { - message, - semantic_diagnostic: None, - model_receipts: receipts, - })) - } - } - } - - async fn structured( - &self, - stage: &str, - binding: &str, - prompt: &str, - schema: serde_json::Value, - sources: Vec, - ) -> Result<(serde_json::Value, ModelStageReceipt)> { - let prompt = format!( - "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nTASK CONTEXT:\n{prompt}", - serde_json::to_string(&schema)? - ); - let model = if stage == "destination_compile" { - MODEL_BALANCED.to_string() - } else { - self.compiler_model.clone() - }; - let request = ModelStageRequest { - stage: stage.into(), - model, - snapshot_binding: binding.into(), - lived_stream: prompt, - output_schema: Some(schema), - source_receipt_ids: sources, - temperature: Some(0.0), - max_output_tokens: Some(match stage { - "world_compile" => 6_000, - "private_relationship_actor_compile" => 4_000, - "agency_compile" => 3_500, - "world_openings" => 1_800, - "world_roles" => 1_200, - "destination_compile" => 3_000, - "gestalt_fission" => 2_500, - _ => 2_500, - }), - }; - let out = run_validated_stage(self.model.as_ref(), &request).await?; - Ok(( - out.structured - .ok_or_else(|| anyhow!("compiler returned no structured output"))?, - out.receipt, - )) - } -} - -impl DestinationReconciliationAgentTool<'_> { - fn observation( - &self, - applied_edits: Vec, - finding: DestinationReconciliationFinding, - ) -> DestinationReconciliationObservation { - let bytes = serde_json::to_vec(&self.draft) - .expect("the typed destination reconciliation draft serializes"); - DestinationReconciliationObservation { - draft_digest: format!("sha256:{:x}", Sha256::digest(bytes)), - applied_edits, - finding, - } - } - - async fn validate_current( - &mut self, - context: &ModelAgentToolContext, - applied_edits: Vec, - ) -> ModelAgentToolOutcome< - AcceptedDestinationReconciliation, - DestinationReconciliationObservation, - > { - let fact_findings = destination_fact_findings(self.campaign, &self.draft.facts); - if !fact_findings.is_empty() { - return ModelAgentToolOutcome::Continue { - observation: self.observation( - applied_edits, - DestinationReconciliationFinding::FactNamespace { - findings: fact_findings, - }, - ), - receipts: Vec::new(), - }; - } - let corrected = - match apply_civic_reconciliation(self.campaign, self.frozen_seed, self.draft.clone()) { - Ok(corrected) => corrected, - Err(error) => { - return ModelAgentToolOutcome::Continue { - observation: self.observation( - applied_edits, - DestinationReconciliationFinding::CandidateApply { - message: error.to_string(), - }, - ), - receipts: Vec::new(), - }; - } - }; - let mut expansion = match lower_compiled_destination( - self.campaign, - &corrected, - self.admission_evidence_receipt_ids, - self.expansion_origin_location_id, - ) { - Ok(expansion) => expansion, - Err(error) => { - return ModelAgentToolOutcome::Continue { - observation: self.observation( - applied_edits, - DestinationReconciliationFinding::CandidateLowering { - message: error.to_string(), - }, - ), - receipts: Vec::new(), - }; - } - }; - if let Err(error) = - validate_compiled_destination(self.campaign, &expansion, self.existing_destination_id) - { - return ModelAgentToolOutcome::Continue { - observation: self.observation( - applied_edits, - DestinationReconciliationFinding::StructuralValidation { - message: error.to_string(), - }, - ), - receipts: Vec::new(), - }; - } - match self - .compiler - .verify_destination_civic_system( - self.campaign, - self.destination_request, - self.evidence, - self.current_civic_context, - &mut expansion, - self.snapshot, - &context.source_receipt_ids, - ) - .await - { - CivicSystemVerificationOutcome::Accepted { receipts } => { - ModelAgentToolOutcome::Accepted { - output: AcceptedDestinationReconciliation { - seed: corrected, - expansion, - }, - receipts, - } - } - CivicSystemVerificationOutcome::Rejected { verdict, receipts } => { - if !verdict.candidate_text_intact - || !verdict.constituencies_cross_boundaries_or_local_homogeneity_justified - || !verdict.explicit_request_constraints_satisfied - || !verdict.public_names_do_not_repeat_an_overused_template - { - ModelAgentToolOutcome::Failed { - message: format!( - "full destination owner must regenerate the broad civic candidate: {}", - serde_json::to_string(&verdict) - .unwrap_or_else(|_| verdict.rationale.clone()) - ), - receipts, - } - } else { - ModelAgentToolOutcome::Continue { - observation: self.observation( - applied_edits, - DestinationReconciliationFinding::CivicVerifier { verdict }, - ), - receipts, - } - } - } - CivicSystemVerificationOutcome::Failed { message, receipts } => { - ModelAgentToolOutcome::Failed { message, receipts } - } - } - } -} - -#[async_trait] -impl ModelAgentTool for DestinationReconciliationAgentTool<'_> { - type Action = DestinationReconciliationToolAction; - type Output = AcceptedDestinationReconciliation; - type Finding = DestinationReconciliationObservation; - - fn action_schema(&self) -> std::result::Result { - Ok(self.action_schema.clone()) - } - - async fn invoke( - &mut self, - action: Self::Action, - context: &ModelAgentToolContext, - ) -> ModelAgentToolOutcome { - match (action.tool, action.edits) { - (DestinationReconciliationTool::ValidateCurrent, None) => { - self.validate_current(context, Vec::new()).await - } - (DestinationReconciliationTool::ReviseAndValidate, Some(edits)) - if (1..=12).contains(&edits.len()) => - { - let applied_edits = - match apply_destination_reconciliation_edits(&mut self.draft, edits) { - Ok(applied_edits) => applied_edits, - Err(error) => { - return ModelAgentToolOutcome::Rejected { - finding: self.observation( - Vec::new(), - DestinationReconciliationFinding::Edit { - message: error.to_string(), - }, - ), - receipts: Vec::new(), - }; - } - }; - self.validate_current(context, applied_edits).await - } - (tool, edits) => ModelAgentToolOutcome::Rejected { - finding: self.observation( - Vec::new(), - DestinationReconciliationFinding::Edit { - message: format!( - "reconciliation tool {:?} received an invalid edit batch of length {}", - tool, - edits.as_ref().map_or(0, Vec::len) - ), - }, - ), - receipts: Vec::new(), - }, - } - } -} - -fn civic_reconciliation_draft( - seed: &CompiledExpansionSeed, -) -> Result { - let civic_system = seed - .civic_system - .as_ref() - .ok_or_else(|| anyhow!("civic reconciliation requires an existing civic manifest"))?; - Ok(CompiledDestinationReconciliation { - facts: seed.facts.clone(), - resident_fact_knowledge: seed - .populations - .iter() - .map(|population| CompiledResidentFactKnowledge { - population_id: population.id.clone(), - fact_ids: population.shared_fact_ids.clone(), - }) - .collect(), - institution_updates: seed - .institutions - .iter() - .map(|institution| CompiledCivicInstitutionUpdate { - institution_id: institution.id.clone(), - resources: institution.resources.clone(), - posture: institution.posture.clone(), - facets: institution.facets.clone(), - information_channels: institution.information_channels.clone(), - }) - .collect(), - local_relations: seed.local_relations.clone(), - civic_system: CompiledCivicSystemReconciliation { - schema: civic_system.schema.clone(), - jurisdiction_location_id: civic_system.jurisdiction_location_id.clone(), - governing_institution_ids: civic_system.governing_institution_ids.clone(), - resident_population_ids: civic_system.resident_population_ids.clone(), - public_authority_fact_ids: civic_system.public_authority_fact_ids.clone(), - public_selection_fact_ids: civic_system.public_selection_fact_ids.clone(), - public_resource_fact_ids: civic_system.public_resource_fact_ids.clone(), - public_redress_fact_ids: civic_system.public_redress_fact_ids.clone(), - political_relation_ids: civic_system.political_relation_ids.clone(), - }, - }) -} - -fn reserve_reconciliation_edit_slot(slots: &mut BTreeSet, slot: String) -> Result { - if !slots.insert(slot.clone()) { - return Err(anyhow!( - "destination reconciliation edit batch targets {slot} more than once" - )); - } - Ok(slot) -} - -fn apply_destination_reconciliation_edits( - draft: &mut CompiledDestinationReconciliation, - edits: Vec, -) -> Result> { - if edits.is_empty() || edits.len() > 12 { - return Err(anyhow!( - "destination reconciliation edit batch must contain between 1 and 12 edits" - )); - } - let mut revised = draft.clone(); - let mut slots = BTreeSet::new(); - let mut changed_slots = Vec::with_capacity(edits.len()); - let mut relation_replacements = BTreeMap::new(); - let mut relation_removals = BTreeSet::new(); - let mut relation_additions = Vec::new(); - - for edit in edits { - match edit { - DestinationReconciliationEdit::ReplaceFact { fact_index, fact } => { - let slot = reserve_reconciliation_edit_slot( - &mut slots, - format!("fact_index:{fact_index}"), - )?; - let fact_count = revised.facts.len(); - let current = revised.facts.get_mut(fact_index).ok_or_else(|| { - anyhow!( - "destination reconciliation fact index {fact_index} is outside the frozen {}-fact workbench", - fact_count - ) - })?; - *current = fact; - changed_slots.push(slot); - } - DestinationReconciliationEdit::SetResidentFactKnowledge { - population_id, - fact_ids, - } => { - let slot = reserve_reconciliation_edit_slot( - &mut slots, - format!("resident_fact_knowledge:{population_id}"), - )?; - let knowledge = revised - .resident_fact_knowledge - .iter_mut() - .find(|knowledge| knowledge.population_id == population_id) - .ok_or_else(|| { - anyhow!( - "destination reconciliation cannot edit unknown frozen population {population_id}" - ) - })?; - knowledge.fact_ids = fact_ids; - changed_slots.push(slot); - } - DestinationReconciliationEdit::UpdateInstitution { update } => { - let slot = reserve_reconciliation_edit_slot( - &mut slots, - format!("institution: {}", update.institution_id), - )?; - let current = revised - .institution_updates - .iter_mut() - .find(|current| current.institution_id == update.institution_id) - .ok_or_else(|| { - anyhow!( - "destination reconciliation cannot edit unknown frozen institution {}", - update.institution_id - ) - })?; - *current = update; - changed_slots.push(slot); - } - DestinationReconciliationEdit::AddLocalRelation { relation } => { - let slot = reserve_reconciliation_edit_slot( - &mut slots, - format!("local_relation_add:{}", relation.id), - )?; - relation_additions.push(relation); - changed_slots.push(slot); - } - DestinationReconciliationEdit::ReplaceLocalRelation { - relation_index, - relation, - } => { - let slot = reserve_reconciliation_edit_slot( - &mut slots, - format!("local_relation_index:{relation_index}"), - )?; - if relation_index >= revised.local_relations.len() { - return Err(anyhow!( - "destination reconciliation relation index {relation_index} is outside the current {}-relation workbench", - revised.local_relations.len() - )); - } - relation_replacements.insert(relation_index, relation); - changed_slots.push(slot); - } - DestinationReconciliationEdit::RemoveLocalRelation { relation_index } => { - let slot = reserve_reconciliation_edit_slot( - &mut slots, - format!("local_relation_index:{relation_index}"), - )?; - if relation_index >= revised.local_relations.len() { - return Err(anyhow!( - "destination reconciliation relation index {relation_index} is outside the current {}-relation workbench", - revised.local_relations.len() - )); - } - relation_removals.insert(relation_index); - changed_slots.push(slot); - } - DestinationReconciliationEdit::UpdateCivicSystemLanes { civic_system } => { - let slot = - reserve_reconciliation_edit_slot(&mut slots, "civic_system_lanes".into())?; - revised.civic_system.governing_institution_ids = - civic_system.governing_institution_ids; - revised.civic_system.resident_population_ids = civic_system.resident_population_ids; - revised.civic_system.public_authority_fact_ids = - civic_system.public_authority_fact_ids; - revised.civic_system.public_selection_fact_ids = - civic_system.public_selection_fact_ids; - revised.civic_system.public_resource_fact_ids = - civic_system.public_resource_fact_ids; - revised.civic_system.public_redress_fact_ids = civic_system.public_redress_fact_ids; - revised.civic_system.political_relation_ids = civic_system.political_relation_ids; - changed_slots.push(slot); - } - } - } - - for (relation_index, relation) in relation_replacements { - revised.local_relations[relation_index] = relation; - } - for relation_index in relation_removals.into_iter().rev() { - revised.local_relations.remove(relation_index); - } - revised.local_relations.extend(relation_additions); - if revised.local_relations.len() > 48 { - return Err(anyhow!( - "destination reconciliation workbench exceeds the 48-relation bound" - )); - } - - *draft = revised; - Ok(changed_slots) -} - -fn civic_public_fact_ids(civic_system: &CivicSystemManifest) -> BTreeSet { - civic_system - .public_authority_fact_ids - .iter() - .chain(civic_system.public_selection_fact_ids.iter()) - .chain(civic_system.public_resource_fact_ids.iter()) - .chain(civic_system.public_redress_fact_ids.iter()) - .cloned() - .collect() -} - -fn apply_civic_reconciliation( - campaign: &Campaign, - seed: &CompiledExpansionSeed, - reconciliation: CompiledDestinationReconciliation, -) -> Result { - let original_civic_system = seed - .civic_system - .as_ref() - .ok_or_else(|| anyhow!("civic reconciliation requires an existing civic manifest"))?; - if reconciliation.civic_system.jurisdiction_location_id - != original_civic_system.jurisdiction_location_id - { - return Err(anyhow!( - "civic reconciliation cannot change the frozen jurisdiction" - )); - } - - let population_ids = seed - .populations - .iter() - .map(|population| population.id.clone()) - .collect::>(); - let reconciled_population_ids = reconciliation - .resident_fact_knowledge - .iter() - .map(|knowledge| knowledge.population_id.clone()) - .collect::>(); - if reconciliation.resident_fact_knowledge.len() != reconciled_population_ids.len() - || reconciled_population_ids != population_ids - { - return Err(anyhow!( - "civic reconciliation must name every frozen candidate population exactly once" - )); - } - - let institution_ids = seed - .institutions - .iter() - .map(|institution| institution.id.clone()) - .collect::>(); - let reconciled_institution_ids = reconciliation - .institution_updates - .iter() - .map(|update| update.institution_id.clone()) - .collect::>(); - if reconciliation.institution_updates.len() != reconciled_institution_ids.len() - || reconciled_institution_ids != institution_ids - { - return Err(anyhow!( - "civic reconciliation must update every frozen candidate institution exactly once" - )); - } - - if reconciliation.facts.len() != seed.facts.len() { - return Err(anyhow!( - "destination reconciliation must return every frozen candidate fact exactly once" - )); - } - let reconciled_fact_ids = reconciliation - .facts - .iter() - .map(|fact| fact.id.clone()) - .collect::>(); - let committed_civic_fact_ids = campaign - .civic_systems - .get(&original_civic_system.jurisdiction_location_id) - .map(civic_public_fact_ids) - .unwrap_or_default(); - let allowed_civic_fact_ids = reconciled_fact_ids - .iter() - .chain(committed_civic_fact_ids.iter()) - .cloned() - .collect::>(); - let reconciled_public_fact_ids = reconciliation - .civic_system - .public_authority_fact_ids - .iter() - .chain(reconciliation.civic_system.public_selection_fact_ids.iter()) - .chain(reconciliation.civic_system.public_resource_fact_ids.iter()) - .chain(reconciliation.civic_system.public_redress_fact_ids.iter()) - .cloned() - .collect::>(); - let unauthorized_public_fact_ids = reconciled_public_fact_ids - .difference(&allowed_civic_fact_ids) - .cloned() - .collect::>(); - if !unauthorized_public_fact_ids.is_empty() { - return Err(anyhow!( - "civic reconciliation referenced facts outside returned or committed civic authority: {unauthorized_public_fact_ids:?}" - )); - } - let allowed_population_fact_ids = reconciled_fact_ids - .iter() - .chain(campaign.facts.keys()) - .cloned() - .collect::>(); - for knowledge in &reconciliation.resident_fact_knowledge { - let unauthorized_knowledge = knowledge - .fact_ids - .difference(&allowed_population_fact_ids) - .cloned() - .collect::>(); - if !unauthorized_knowledge.is_empty() { - return Err(anyhow!( - "destination reconciliation gave population {} unknown fact IDs: {unauthorized_knowledge:?}", - knowledge.population_id - )); - } - if !reconciled_public_fact_ids.is_subset(&knowledge.fact_ids) { - return Err(anyhow!( - "civic reconciliation must give population {} every reconciled public civic fact", - knowledge.population_id - )); - } - } - - let mut corrected = seed.clone(); - corrected.facts = reconciliation.facts; - let mut resident_fact_knowledge = reconciliation - .resident_fact_knowledge - .into_iter() - .map(|knowledge| (knowledge.population_id, knowledge.fact_ids)) - .collect::>(); - for population in &mut corrected.populations { - population.shared_fact_ids = resident_fact_knowledge - .remove(&population.id) - .expect("reconciled population set was proven exact"); - } - let mut institution_updates = reconciliation - .institution_updates - .into_iter() - .map(|update| (update.institution_id.clone(), update)) - .collect::>(); - for institution in &mut corrected.institutions { - let update = institution_updates - .remove(&institution.id) - .expect("reconciled institution set was proven exact"); - institution.resources = update.resources; - institution.posture = update.posture; - institution.facets = update.facets; - institution.information_channels = update.information_channels; - } - corrected.local_relations = reconciliation.local_relations; - corrected.civic_system = Some(reconciliation.civic_system.into()); - Ok(corrected) -} - -fn lower_compiled_destination( - campaign: &Campaign, - seed: &CompiledExpansionSeed, - sources: &[String], - expansion_origin_location_id: &str, -) -> Result { - let fact_statements = campaign - .facts - .values() - .chain(seed.facts.iter()) - .map(|fact| (fact.id.as_str(), fact.statement.as_str())) - .collect::>(); - let populations = seed - .populations - .iter() - .map(|population| { - let shared_knowledge = population - .shared_fact_ids - .iter() - .map(|fact_id| { - fact_statements - .get(fact_id.as_str()) - .map(|value| (*value).to_owned()) - .ok_or_else(|| { - anyhow!( - "destination population {} references unknown shared fact {fact_id}", - population.id - ) - }) - }) - .collect::>>()?; - Ok(GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: population.id.clone(), - name: population.name.clone(), - version: 0, - home_location_id: population.home_location_id.clone(), - shared_capabilities: population.shared_capabilities.clone(), - shared_knowledge, - resources: population.resources.clone(), - goals: population.goals.clone(), - pressures: population.pressures.clone(), - }) - }) - .collect::>>()?; - let population_profiles = seed - .populations - .iter() - .map(|population| AgencyProfile { - schema: "ghostlight.agency_profile.v1".into(), - id: format!("agency:{}", population.id), - subject_id: population.id.clone(), - subject_kind: AgencySubjectKind::Gestalt, - profile_version: 0, - collective_authority_id: population.collective_authority_id.clone(), - parent_subject_id: None, - active_leaf: true, - simulation_eligible: true, - facets: population.facets.clone().into_map(), - location_ids: BTreeSet::from([population.home_location_id.clone()]), - information_channels: population.information_channels.clone(), - detail_debt: 0, - last_detail_tick: campaign.strategic_tick_count, - evidence_receipt_ids: sources.to_vec(), - }) - .collect::>(); - let institutions = seed - .institutions - .iter() - .map(|institution| InstitutionState { - id: institution.id.clone(), - name: institution.name.clone(), - resources: institution.resources.clone(), - goals: institution.goals.clone(), - posture: institution.posture.clone(), - }) - .collect::>(); - let institution_profiles = seed - .institutions - .iter() - .map(|institution| AgencyProfile { - schema: "ghostlight.agency_profile.v1".into(), - id: format!("agency:{}", institution.id), - subject_id: institution.id.clone(), - subject_kind: AgencySubjectKind::Institution, - profile_version: 0, - collective_authority_id: None, - parent_subject_id: None, - active_leaf: true, - simulation_eligible: true, - facets: institution.facets.clone().into_map(), - location_ids: institution.location_ids.clone(), - information_channels: institution.information_channels.clone(), - detail_debt: 0, - last_detail_tick: campaign.strategic_tick_count, - evidence_receipt_ids: sources.to_vec(), - }) - .collect::>(); - let local_relations = seed - .local_relations - .iter() - .map(|relation| AgencyRelation { - schema: AgencyRelation::SCHEMA.into(), - id: relation.id.clone(), - from_subject_id: relation.from_subject_id.clone(), - to_subject_id: relation.to_subject_id.clone(), - kind: relation.kind.clone(), - strength: relation.strength, - active: true, - evidence_receipt_ids: sources.to_vec(), - }) - .collect::>(); - let migration_relations = seed - .migration_relations - .iter() - .map(|relation| AgencyRelation { - schema: AgencyRelation::SCHEMA.into(), - id: relation.id.clone(), - from_subject_id: relation.from_gestalt_id.clone(), - to_subject_id: relation.to_gestalt_id.clone(), - kind: AgencyRelationKind::Migration, - strength: relation.strength, - active: true, - evidence_receipt_ids: sources.to_vec(), - }) - .collect::>(); - let mut civic_system = seed.civic_system.clone(); - if let Some(system) = &mut civic_system { - system.version = campaign - .civic_systems - .get(&system.jurisdiction_location_id) - .map(|current| current.version.saturating_add(1)) - .unwrap_or(0); - system.semantic_verification_receipt_id.clear(); - } - let origin_routes = - compiled_route_map(seed.origin_routes.clone(), expansion_origin_location_id)?; - let locations = seed - .locations - .clone() - .into_iter() - .map(CompiledLocation::into_location) - .collect::>>()?; - Ok(crate::domain::RegionExpansion { - origin_location_id: expansion_origin_location_id.into(), - origin_routes, - locations, - facts: seed.facts.clone(), - populations, - population_profiles, - migration_relations, - institutions, - institution_profiles, - local_relations, - civic_system, - }) -} - -fn validate_compiled_destination( - campaign: &Campaign, - expansion: &crate::domain::RegionExpansion, - existing_destination_id: Option<&str>, -) -> Result<()> { - if !expansion.populations.is_empty() && expansion.civic_system.is_none() { - return Err(anyhow!( - "compiled inhabited destination omitted its civic system manifest" - )); - } - if let Some(target_location_id) = existing_destination_id { - validate_locality_elaboration( - campaign, - &LocalityElaboration { - target_location_id: target_location_id.into(), - expansion: expansion.clone(), - }, - ) - } else { - validate_new_destination_expansion(campaign, expansion) - } -} - -fn shortest_location_path( - campaign: &Campaign, - origin_location_id: &str, - destination_location_id: &str, -) -> Option<(Vec, u32)> { - if !campaign.locations.contains_key(origin_location_id) - || !campaign.locations.contains_key(destination_location_id) - { - return None; - } - let mut frontier = BinaryHeap::from([Reverse((0_u32, origin_location_id.to_owned()))]); - let mut distances = BTreeMap::from([(origin_location_id.to_owned(), 0_u32)]); - let mut previous = BTreeMap::::new(); - while let Some(Reverse((elapsed, location_id))) = frontier.pop() { - if location_id == destination_location_id { - let mut path = vec![location_id.clone()]; - let mut cursor = location_id; - while let Some(parent) = previous.get(&cursor) { - path.push(parent.clone()); - cursor = parent.clone(); - } - path.reverse(); - return Some((path, elapsed)); - } - if distances - .get(&location_id) - .is_some_and(|best| elapsed > *best) - { - continue; - } - let location = campaign.locations.get(&location_id)?; - for route in location.routes.values() { - if !campaign.locations.contains_key(&route.destination_id) { - continue; - } - let Some(next_elapsed) = elapsed.checked_add(route.travel_minutes) else { - continue; - }; - if distances - .get(&route.destination_id) - .is_some_and(|best| *best <= next_elapsed) - { - continue; - } - distances.insert(route.destination_id.clone(), next_elapsed); - previous.insert(route.destination_id.clone(), location_id.clone()); - frontier.push(Reverse((next_elapsed, route.destination_id.clone()))); - } - } - None -} - -fn validate_user_text(label: &str, value: &str, max_chars: usize) -> Result<()> { - let value = value.trim(); - if value.is_empty() - || value.chars().count() > max_chars - || value - .chars() - .any(|character| character.is_control() && !matches!(character, '\n' | '\r' | '\t')) - { - return Err(anyhow!( - "{label} must contain 1 to {max_chars} readable characters" - )); - } - Ok(()) -} - -fn validate_compiled_material_gaps( - gaps: &[CompiledMaterialGap], - receipts: &[VaultEvidenceReceipt], -) -> Result<()> { - let known_receipt_ids = receipt_ids(receipts).into_iter().collect::>(); - let mut seen = BTreeSet::new(); - for gap in gaps { - for (label, value) in [ - ("summary", gap.summary.as_str()), - ("premise_clause", gap.premise_clause.as_str()), - ("blocked_choice", gap.blocked_choice.as_str()), - ] { - validate_user_text(&format!("compiled material gap {label}"), value, 2_000)?; - } - if !seen.insert(( - gap.kind.clone(), - gap.summary.trim().to_lowercase(), - gap.premise_clause.trim().to_lowercase(), - )) { - return Err(anyhow!("compiled material gaps must be unique")); - } - let supplied_receipts = gap - .evidence_receipt_ids - .iter() - .cloned() - .collect::>(); - if supplied_receipts.len() != gap.evidence_receipt_ids.len() - || !supplied_receipts.is_subset(&known_receipt_ids) - { - return Err(anyhow!( - "compiled material gap cites duplicate or unknown evidence receipt IDs" - )); - } - match gap.kind { - CompiledMaterialGapKind::ContradictoryCanonBaselines - if supplied_receipts.is_empty() => - { - return Err(anyhow!( - "a contradictory canon-baselines gap must cite supplied evidence" - )); - } - CompiledMaterialGapKind::UnanchoredRequestedBaseline - | CompiledMaterialGapKind::ApprovedCapabilityConflict - if !supplied_receipts.is_empty() => - { - return Err(anyhow!( - "only contradictory canon-baselines gaps may cite Vault evidence receipts" - )); - } - _ => {} - } - } - Ok(()) -} - -fn validate_branch_assumptions(assumptions: &[String]) -> Result<()> { - if assumptions.len() > 32 { - return Err(anyhow!("branch assumptions may contain at most 32 entries")); - } - let mut seen = BTreeSet::new(); - for assumption in assumptions { - validate_user_text("branch assumption", assumption, 2_000)?; - if !seen.insert(assumption.trim().to_lowercase()) { - return Err(anyhow!("branch assumptions must be unique")); - } - } - Ok(()) -} - -fn validate_compiled_destination_population_names( - campaign: &Campaign, - populations: &[CompiledDestinationPopulation], -) -> Result<()> { - let established = campaign - .gestalts - .values() - .map(|population| crate::resolution::public_identity_key(&population.name)) - .collect::>(); - let mut candidate = BTreeSet::new(); - for population in populations { - let key = crate::resolution::public_identity_key(&population.name); - if key.is_empty() || established.contains(&key) || !candidate.insert(key) { - return Err(anyhow!( - "destination population {} needs a distinct public population identity", - population.id - )); - } - } - Ok(()) -} - -fn material_gap_text(gap: &CompiledMaterialGap) -> String { - format!( - "{} Affected approved premise: {} Approval must decide: {}", - gap.summary.trim(), - gap.premise_clause.trim(), - gap.blocked_choice.trim() - ) -} - -fn approved_relationship_plan(brief: &ApprovedCampaignBrief) -> Result { - let mut character_names = BTreeMap::>::new(); - for character in &brief.characters { - character_names - .entry(normalized_identity(&character.name)) - .or_default() - .push(character.actor_id.clone()); - } - let member_actor_ids = brief - .member_actor_ids - .values() - .cloned() - .collect::>(); - let mut anchors = BTreeMap::::new(); - let mut anchor_norms = BTreeMap::::new(); - let mut targets = BTreeMap::new(); - for character in &brief.characters { - for (subject, description) in &character.relationships { - validate_user_text("relationship subject", subject, 160)?; - validate_user_text("relationship description", description, 1_000)?; - let normalized = normalized_identity(subject); - let target = if let Some(actor_id) = brief.member_actor_ids.get(subject) { - actor_id.clone() - } else if member_actor_ids.contains(subject) { - subject.clone() - } else if let Some(matches) = character_names.get(&normalized).filter(|v| v.len() == 1) - { - matches[0].clone() - } else { - let digest = format!( - "{:x}", - Sha256::digest(format!("private-relationship-actor\0{normalized}").as_bytes()) - ); - let id = format!("relationship-anchor:{}", &digest[..20]); - if let Some(previous) = anchor_norms.insert(id.clone(), normalized.clone()) - && previous != normalized - { - return Err(anyhow!("relationship anchor ID collision")); - } - let anchor = - anchors - .entry(id.clone()) - .or_insert_with(|| RequiredRelationshipActor { - id: id.clone(), - name: subject.trim().to_owned(), - approved_relationship_descriptions: Vec::new(), - }); - if !anchor - .approved_relationship_descriptions - .contains(description) - { - anchor - .approved_relationship_descriptions - .push(description.clone()); - } - id - }; - targets.insert((character.member_id.clone(), subject.clone()), target); - } - } - Ok(ApprovedRelationshipPlan { - anchors: anchors.into_values().collect(), - targets, - }) -} - -fn validate_required_relationship_actor_inputs( - anchors: &[RequiredRelationshipActor], -) -> Result<()> { - if anchors.len() > 64 { - return Err(anyhow!( - "approved campaign brief cannot require more than 64 relationship actors" - )); - } - let mut ids = BTreeSet::new(); - let mut names = BTreeSet::new(); - for anchor in anchors { - validate_user_text("relationship actor name", &anchor.name, 160)?; - if anchor.approved_relationship_descriptions.is_empty() - || anchor.approved_relationship_descriptions.len() > 8 - { - return Err(anyhow!( - "relationship actors require one to eight approved descriptions" - )); - } - for description in &anchor.approved_relationship_descriptions { - validate_user_text("relationship description", description, 1_000)?; - } - if !anchor.id.starts_with("relationship-anchor:") - || anchor.id.chars().count() > 80 - || !ids.insert(anchor.id.clone()) - || !names.insert(normalized_identity(&anchor.name)) - { - return Err(anyhow!( - "relationship actors require unique server-generated IDs and names" - )); - } - } - Ok(()) -} - -fn validate_shared_seed_excludes_locally_owned_subjects( - seed: &CompiledSeed, - anchors: &[RequiredRelationshipActor], - player_names: &[String], -) -> Result<()> { - let locally_owned_names = anchors - .iter() - .map(|anchor| normalized_identity(&anchor.name)) - .chain(player_names.iter().map(|name| normalized_identity(name))) - .collect::>(); - let collisions = seed - .actors - .iter() - .filter(|actor| locally_owned_names.contains(&normalized_identity(&actor.name))) - .map(|actor| actor.id.clone()) - .chain( - seed.gestalt_members - .iter() - .filter(|member| locally_owned_names.contains(&normalized_identity(&member.name))) - .map(|member| crate::domain::gestalt_member_subject_id(&member.id)), - ) - .collect::>(); - if collisions.is_empty() { - Ok(()) - } else { - Err(anyhow!( - "shared world candidate materialized subject IDs owned outside world-cast compilation; omit those subjects and their derived public references: {collisions:?}" - )) - } -} - -fn materialize_private_relationship_actors( - seed: &CompiledSeed, - anchors: &[RequiredRelationshipActor], - candidates: PrivateRelationshipActorSet, -) -> Result> { - validate_required_relationship_actor_inputs(anchors)?; - if candidates.actors.len() != anchors.len() { - return Err(anyhow!( - "private relationship actor compiler returned {} candidates for {} approved subjects", - candidates.actors.len(), - anchors.len() - )); - } - let reserved_ids = std::iter::once(seed.player.id.as_str()) - .chain(seed.actors.iter().map(|item| item.id.as_str())) - .chain(seed.institutions.iter().map(|item| item.id.as_str())) - .chain(seed.gestalts.iter().map(|item| item.id.as_str())) - .chain(seed.gestalt_members.iter().map(|item| item.id.as_str())) - .collect::>(); - let allowed_relationship_subject_ids = seed - .actors - .iter() - .map(|item| item.id.as_str()) - .chain(seed.institutions.iter().map(|item| item.id.as_str())) - .chain(seed.gestalts.iter().map(|item| item.id.as_str())) - .collect::>(); - let mut used_candidates = BTreeSet::new(); - let mut actors = Vec::with_capacity(anchors.len()); - for (anchor_index, anchor) in anchors.iter().enumerate() { - if reserved_ids.contains(anchor.id.as_str()) { - return Err(anyhow!( - "private relationship actor identity {} collides with an existing canonical subject", - anchor.id - )); - } - let normalized_name = normalized_identity(&anchor.name); - let matches = candidates - .actors - .iter() - .enumerate() - .filter(|(index, actor)| { - !used_candidates.contains(index) - && normalized_identity(&actor.name) == normalized_name - }) - .map(|(index, _)| index) - .collect::>(); - let index = match matches.as_slice() { - [index] => *index, - [] => { - return Err(anyhow!( - "private actor stage omitted approved subject slot {anchor_index}" - )); - } - _ => { - return Err(anyhow!( - "private actor stage returned {} ambiguous candidates for approved subject slot {anchor_index}", - matches.len(), - )); - } - }; - used_candidates.insert(index); - let candidate = &candidates.actors[index]; - if !seed - .locations - .iter() - .any(|location| location.id == candidate.location_id) - { - return Err(anyhow!( - "private actor candidate slot {anchor_index} occupies unknown location {}", - candidate.location_id - )); - } - let relationships = compiled_relationship_map(candidate.relationships.clone())?; - if relationships - .keys() - .any(|subject_id| !allowed_relationship_subject_ids.contains(subject_id.as_str())) - { - return Err(anyhow!( - "private actor candidate slot {anchor_index} relates to a subject outside the exact public actor, institution, and population allowlist" - )); - } - actors.push(ActorState { - id: anchor.id.clone(), - name: anchor.name.clone(), - location_id: candidate.location_id.clone(), - capabilities: candidate.capabilities.clone(), - knowledge: candidate.knowledge.clone(), - equipment: candidate.equipment.clone(), - conditions: candidate.conditions.clone(), - obligations: candidate.obligations.clone(), - relationships, - goals: candidate.goals.clone(), - memories: candidate.memories.clone(), - }); - } - Ok(actors) -} - -fn constrain_private_relationship_actor_schema( - schema: &mut serde_json::Value, - anchors: &[RequiredRelationshipActor], - seed: &CompiledSeed, -) -> Result<()> { - let actors = schema - .pointer_mut("/properties/actors") - .ok_or_else(|| anyhow!("private relationship actor schema has no actors property"))?; - actors["minItems"] = serde_json::json!(anchors.len()); - actors["maxItems"] = serde_json::json!(anchors.len()); - - let candidate = schema - .pointer_mut("/$defs/PrivateRelationshipActorCandidate") - .ok_or_else(|| anyhow!("private relationship actor schema has no candidate definition"))?; - candidate["properties"]["name"] = serde_json::json!({ - "type":"string", - "enum":anchors.iter().map(|anchor| anchor.name.clone()).collect::>() - }); - candidate["properties"]["location_id"] = serde_json::json!({ - "type":"string", - "enum":seed.locations.iter().map(|location| location.id.clone()).collect::>() - }); - - let allowed_relationship_subject_ids = seed - .actors - .iter() - .map(|actor| actor.id.clone()) - .chain( - seed.institutions - .iter() - .map(|institution| institution.id.clone()), - ) - .chain(seed.gestalts.iter().map(|gestalt| gestalt.id.clone())) - .collect::>(); - if allowed_relationship_subject_ids.is_empty() { - candidate["properties"]["relationships"] = serde_json::json!({ - "type":"array", - "maxItems":0 - }); - } else { - let relationship = schema - .pointer_mut("/$defs/CompiledRelationship") - .ok_or_else(|| { - anyhow!("private relationship actor schema has no relationship definition") - })?; - relationship["properties"]["subject_id"] = serde_json::json!({ - "type":"string", - "enum":allowed_relationship_subject_ids - }); - } - Ok(()) -} - -fn constrain_destination_expansion_schema( - schema: &mut serde_json::Value, - source_population_ids: &BTreeSet, -) -> Result<()> { - if source_population_ids.is_empty() { - let relations = schema - .pointer_mut("/properties/migration_relations") - .ok_or_else(|| anyhow!("destination schema has no migration_relations property"))?; - relations["maxItems"] = serde_json::json!(0); - return Ok(()); - } - let relation = schema - .pointer_mut("/$defs/CompiledDestinationMigrationRelation") - .ok_or_else(|| anyhow!("destination schema has no migration relation definition"))?; - relation["properties"]["from_gestalt_id"] = serde_json::json!({ - "type":"string", - "enum":source_population_ids.iter().cloned().collect::>() - }); - Ok(()) -} - -fn constrain_civic_reconciliation_action_schema( - schema: &mut serde_json::Value, - seed: &CompiledExpansionSeed, -) -> Result<()> { - if serde_json::to_string(schema)?.contains("CompiledDestinationReconciliation") { - return Err(anyhow!( - "destination reconciliation action schema exposed the complete workbench candidate" - )); - } - let fact_indices = (0..seed.facts.len()).collect::>(); - let population_ids = seed - .populations - .iter() - .map(|population| population.id.clone()) - .collect::>(); - let institution_ids = seed - .institutions - .iter() - .map(|institution| institution.id.clone()) - .collect::>(); - - constrain_reconciliation_action_properties( - schema, - &fact_indices, - &population_ids, - &institution_ids, - ); - Ok(()) -} - -fn constrain_reconciliation_action_properties( - value: &mut serde_json::Value, - fact_indices: &[usize], - population_ids: &[String], - institution_ids: &[String], -) { - match value { - serde_json::Value::Array(values) => { - for value in values { - constrain_reconciliation_action_properties( - value, - fact_indices, - population_ids, - institution_ids, - ); - } - } - serde_json::Value::Object(object) => { - if let Some(serde_json::Value::Object(properties)) = object.get_mut("properties") { - if !fact_indices.is_empty() - && let Some(property) = properties.get_mut("fact_index") - { - *property = serde_json::json!({ - "type":"integer", - "enum":fact_indices, - }); - } - if !population_ids.is_empty() - && let Some(property) = properties.get_mut("population_id") - { - *property = serde_json::json!({ - "type":"string", - "enum":population_ids, - }); - } - if !institution_ids.is_empty() - && let Some(property) = properties.get_mut("institution_id") - { - *property = serde_json::json!({ - "type":"string", - "enum":institution_ids, - }); - } - } - for child in object.values_mut() { - constrain_reconciliation_action_properties( - child, - fact_indices, - population_ids, - institution_ids, - ); - } - } - _ => {} - } -} - -fn validate_required_relationship_actors( - campaign: &Campaign, - anchors: &[RequiredRelationshipActor], -) -> Result<()> { - let rejected_count = anchors - .iter() - .filter(|anchor| { - campaign - .actors - .get(&anchor.id) - .is_none_or(|actor| actor.name != anchor.name) - }) - .count(); - if rejected_count > 0 { - return Err(anyhow!( - "world seed failed private relationship actor binding for {} subject(s)", - rejected_count - )); - } - Ok(()) -} - -fn canonical_relationship_subject_ids(campaign: &Campaign) -> BTreeSet { - let mut targets = campaign - .actors - .keys() - .chain(campaign.institutions.keys()) - .chain(campaign.gestalts.keys()) - .cloned() - .collect::>(); - targets.extend( - campaign - .gestalt_members - .keys() - .map(|member_id| crate::domain::gestalt_member_subject_id(member_id)), - ); - targets -} - -fn validate_fission_request(request: &GestaltFissionRequest) -> Result> { - validate_user_text("fission reason", &request.reason, 500)?; - if request.requested_partition_values.is_empty() - || request.requested_partition_values.len() > 16 - { - return Err(anyhow!("fission request needs between 1 and 16 named cuts")); - } - for value in &request.requested_partition_values { - validate_user_text("fission cut", value, 160)?; - } - let requested: BTreeSet<_> = request - .requested_partition_values - .iter() - .map(|value| value.trim().to_ascii_lowercase()) - .collect(); - if requested.len() != request.requested_partition_values.len() - || requested.contains("other/unknown") - { - return Err(anyhow!( - "fission request needs distinct named cuts and reserves other/unknown for the compiler" - )); - } - Ok(requested) -} - -fn global_agency_queries(start: &CustomStart) -> Vec { - let horizon = start.when.chars().take(120).collect::(); - vec![ - format!( - "major powers factions institutions and movements active during {horizon} overview index" - ), - format!( - "strategic specialist organizations populations regions and information channels during {horizon}" - ), - ] -} - -fn authority_allows_direct_seed(authority_lane: &str) -> bool { - matches!( - authority_lane, - "aetheria.canon_worldbuilding" - | "aetheria.vault_document" - | "AetheriaLore" - | "kalsa.public" - | "kalsa.gm_canon" - ) -} - -fn canonical_worldbuilding_receipts( - receipts: &[VaultEvidenceReceipt], -) -> Vec { - receipts - .iter() - .filter_map(|receipt| { - let mut filtered = receipt.clone(); - filtered.witnesses.retain(|witness| { - matches!( - witness.authority_lane.as_str(), - "aetheria.canon_worldbuilding" - | "aetheria.vault_document" - | "AetheriaLore" - | "kalsa.public" - | "kalsa.gm_canon" - ) - }); - (!filtered.witnesses.is_empty()).then_some(filtered) - }) - .collect() -} - -fn bounded_evidence_text(receipts: &[VaultEvidenceReceipt], max_chars: usize) -> String { - let mut seen = BTreeSet::new(); - receipts - .iter() - .flat_map(|receipt| { - receipt - .witnesses - .iter() - .map(move |witness| (receipt.id.as_str(), witness)) - }) - .filter(|(_, witness)| { - seen.insert(( - witness.source_id.clone(), - witness.exact_locator.clone(), - witness.content_hash.clone(), - )) - }) - .map(|(receipt_id, witness)| { - let excerpt = witness.excerpt.chars().take(max_chars).collect::(); - format!( - "[receipt_id={} | source={} | locator={} | content_hash={}] {}", - receipt_id, witness.source_id, witness.exact_locator, witness.content_hash, excerpt, - ) - }) - .collect::>() - .join("\n\n") -} - -fn ground_global_agency_catalog( - mut catalog: ExtractedGlobalAgencyCatalog, - receipts: &[VaultEvidenceReceipt], -) -> Result<(GroundedGlobalAgencyCatalog, Vec)> { - if catalog.institutions.len() > 64 { - return Err(anyhow!( - "global agency candidate pool exceeds 64 institutions" - )); - } - if catalog.institutions.is_empty() && catalog.gaps.is_empty() { - return Err(anyhow!( - "global agency catalog must contain witnessed institutions or an explicit evidence gap" - )); - } - if catalog - .gaps - .iter() - .any(|gap| gap.trim().is_empty() || gap.chars().count() > 500) - { - return Err(anyhow!("global agency catalog contains a malformed gap")); - } - let by_source = receipts - .iter() - .flat_map(|receipt| receipt.witnesses.iter()) - .fold(BTreeMap::<&str, Vec<&str>>::new(), |mut map, witness| { - map.entry(witness.source_id.as_str()) - .or_default() - .push(witness.excerpt.as_str()); - map - }); - let receipt_ids_by_source = receipts.iter().fold( - BTreeMap::<&str, BTreeSet>::new(), - |mut map, receipt| { - for witness in &receipt.witnesses { - map.entry(witness.source_id.as_str()) - .or_default() - .insert(receipt.id.clone()); - } - map - }, - ); - let mut names = BTreeSet::new(); - for institution in &catalog.institutions { - let normalized_name = institution - .name - .split_whitespace() - .collect::>() - .join(" ") - .to_lowercase(); - if normalized_name.is_empty() - || institution.name.chars().count() > 160 - || !names.insert(normalized_name.clone()) - { - return Err(anyhow!( - "global agency institution names must be non-empty, bounded, and unique" - )); - } - } - let mut admitted = Vec::new(); - let mut grounding_gaps = Vec::new(); - let mut omitted_names = Vec::new(); - let candidate_names = catalog - .institutions - .iter() - .map(|institution| normalized_identity(&institution.name)) - .collect::>(); - for institution in std::mem::take(&mut catalog.institutions) { - let mut valid_claims = Vec::new(); - let mut claim_sources = BTreeSet::new(); - for claim in institution.supporting_claims { - let sources = matching_agency_claim_sources(&claim, &by_source)?; - let normalized_claim = normalized_identity(&claim); - let named_candidate_count = candidate_names - .iter() - .filter(|name| normalized_identity_contains(&normalized_claim, name)) - .count(); - let specific = sources - .iter() - .any(|source_id| source_document_names_institution(source_id, &institution.name)) - || (normalized_identity_contains( - &normalized_claim, - &normalized_identity(&institution.name), - ) && named_candidate_count == 1); - if !sources.is_empty() && specific { - valid_claims.push(claim); - claim_sources.extend(sources); - } else { - grounding_gaps.push(format!("{} supplied a supporting claim that was not exact institution-specific evidence", institution.name)); - } - } - if valid_claims.is_empty() { - omitted_names.push(institution.name); - continue; - } - let evidence_receipt_ids: Vec = claim_sources - .into_iter() - .flat_map(|source_id| { - receipt_ids_by_source - .get(source_id) - .into_iter() - .flatten() - .cloned() - }) - .collect::>() - .into_iter() - .collect(); - if evidence_receipt_ids.is_empty() { - return Err(anyhow!( - "grounded remote institution has no exact evidence receipt" - )); - } - admitted.push(GroundedRemoteInstitution { - name: institution.name, - supporting_claims: valid_claims, - evidence_receipt_ids, - }); - } - if admitted.len() > 32 { - let overflow = admitted.len() - 32; - admitted.truncate(32); - grounding_gaps.push(format!( - "{overflow} grounded remote agency candidates exceeded the 32-institution simulation catalog capacity" - )); - catalog.gaps.push(format!( - "{overflow} additional source-grounded institutions were omitted at this horizon because the remote agency catalog is capped at 32; they remain available for on-demand compilation." - )); - } - if !omitted_names.is_empty() { - catalog.gaps.push(format!( - "{} remote agency candidates were omitted because no supporting claim could be bound to institution-specific evidence; exact rejection details remain in the private model-stage receipt.", - omitted_names.len() - )); - } - Ok(( - GroundedGlobalAgencyCatalog { - institutions: admitted, - gaps: catalog.gaps, - }, - grounding_gaps, - )) -} - -fn matching_agency_claim_sources<'a>( - claim: &str, - by_source: &'a BTreeMap<&'a str, Vec<&'a str>>, -) -> Result> { - if claim.trim().is_empty() || claim.chars().count() > 320 { - return Err(anyhow!( - "global agency claim must contain 1 to 320 characters" - )); - } - let matches = by_source - .iter() - .filter(|(_, witnesses)| { - witnesses - .iter() - .any(|witness| normalized_contains(witness, claim)) - }) - .map(|(source_id, _)| *source_id) - .collect::>(); - Ok(matches) -} - -fn normalized_identity(value: &str) -> String { - value - .chars() - .map(|character| { - if character.is_alphanumeric() { - character.to_ascii_lowercase() - } else { - ' ' - } - }) - .collect::() - .split_whitespace() - .collect::>() - .join(" ") -} - -fn normalized_identity_contains(normalized_text: &str, normalized_name: &str) -> bool { - !normalized_name.is_empty() - && format!(" {normalized_text} ").contains(&format!(" {normalized_name} ")) -} - -fn source_document_names_institution(source_id: &str, institution_name: &str) -> bool { - let path = source_id - .split_once(':') - .map_or(source_id, |(_, path)| path); - let file_name = path.rsplit(['/', '\\']).next().unwrap_or(path); - let stem = file_name - .rsplit_once('.') - .map_or(file_name, |(stem, _)| stem); - normalized_identity(stem) == normalized_identity(institution_name) -} - -fn validate_doctrine_catalog( - grounded: &[GroundedRemoteInstitution], - synthesized: &StrategicDoctrineCatalog, -) -> Result<()> { - let expected = grounded - .iter() - .map(|i| i.name.as_str()) - .collect::>(); - let actual = synthesized - .institutions - .iter() - .map(|i| i.name.as_str()) - .collect::>(); - if synthesized.institutions.len() != grounded.len() || actual != expected { - return Err(anyhow!( - "strategic doctrine synthesis must cover every grounded institution exactly once" - )); - } - if synthesized.institutions.iter().any(|i| { - i.strategic_doctrine.trim().is_empty() || i.strategic_doctrine.chars().count() > 600 - }) { - return Err(anyhow!( - "strategic doctrine must contain 1 to 600 characters" - )); - } - Ok(()) -} - -fn validate_doctrine_verification( - grounded: &[GroundedRemoteInstitution], - verification: &StrategicDoctrineVerification, -) -> Result> { - let expected = grounded - .iter() - .map(|i| i.name.as_str()) - .collect::>(); - let actual = verification - .verdicts - .iter() - .map(|i| i.name.as_str()) - .collect::>(); - if verification.verdicts.len() != grounded.len() || actual != expected { - return Err(anyhow!( - "strategic doctrine verification must cover every grounded institution exactly once" - )); - } - if verification.verdicts.iter().any(|verdict| { - verdict.rationale.trim().is_empty() || verdict.rationale.chars().count() > 500 - }) { - return Err(anyhow!( - "strategic doctrine verification rationale must contain 1 to 500 characters" - )); - } - Ok(verification - .verdicts - .iter() - .filter(|v| !v.compatible_with_canon) - .cloned() - .collect()) -} - -fn doctrine_incompatibility_error(incompatible: &[StrategicDoctrineVerdict]) -> anyhow::Error { - anyhow!( - "strategic doctrine contradicted its canon anchors: {}", - incompatible - .iter() - .map(|verdict| format!("{}: {}", verdict.name, verdict.rationale)) - .collect::>() - .join("; ") - ) -} - -fn lower_compatible_doctrine_catalog( - grounded: GroundedGlobalAgencyCatalog, - synthesized: StrategicDoctrineCatalog, -) -> CompiledGlobalAgencyCatalog { - let doctrines = synthesized - .institutions - .into_iter() - .map(|institution| (institution.name, institution.strategic_doctrine)) - .collect::>(); - let institutions = grounded - .institutions - .into_iter() - .map(|institution| CompiledRemoteInstitution { - strategic_doctrine: doctrines[&institution.name].clone(), - name: institution.name, - evidence_receipt_ids: institution.evidence_receipt_ids, - }) - .collect(); - CompiledGlobalAgencyCatalog { - institutions, - gaps: grounded.gaps, - } -} - -fn merge_global_agency_catalog( - seed: &mut CompiledSeed, - catalog: CompiledGlobalAgencyCatalog, -) -> Result<(BTreeMap>, Vec)> { - let mut known_names = seed - .institutions - .iter() - .map(|institution| institution.name.to_lowercase()) - .collect::>(); - let mut known_ids = seed - .institutions - .iter() - .map(|institution| institution.id.clone()) - .collect::>(); - let mut remote_evidence = BTreeMap::new(); - let mut branch_assumptions = Vec::new(); - for institution in catalog.institutions { - if !known_names.insert(institution.name.to_lowercase()) { - continue; - } - let digest = format!("{:x}", Sha256::digest(institution.name.as_bytes())); - let id = format!("remote-institution:{}", &digest[..16]); - if !known_ids.insert(id.clone()) { - return Err(anyhow!("global agency institution ID collision")); - } - branch_assumptions.push(format!( - "Campaign-local operational doctrine for {}: {}", - institution.name, institution.strategic_doctrine - )); - seed.institutions.push(InstitutionState { - id: id.clone(), - name: institution.name, - resources: vec![], - goals: vec![institution.strategic_doctrine], - posture: "No branch-local posture has been established.".into(), - }); - remote_evidence.insert(id, institution.evidence_receipt_ids); - } - branch_assumptions.extend( - catalog - .gaps - .into_iter() - .map(|gap| format!("Global agency coverage limit: {gap}")), - ); - Ok((remote_evidence, branch_assumptions)) -} - -fn apply_coarse_remote_agency_profiles( - campaign: &mut Campaign, - remote_institution_evidence: &BTreeMap>, -) -> Result<()> { - let axes = [ - (AgencyAxis::Geography, "remote/unknown"), - (AgencyAxis::Ideology, "unknown"), - (AgencyAxis::Authority, "self-governing institution"), - (AgencyAxis::EconomyRole, "unknown"), - (AgencyAxis::SpeciesBody, "institutional collective"), - (AgencyAxis::Information, "unknown"), - ]; - for (institution_id, evidence_receipt_ids) in remote_institution_evidence { - let profile = campaign - .agency_profiles - .get_mut(institution_id) - .ok_or_else(|| anyhow!("remote agency profile has no canonical institution"))?; - if profile.subject_kind != AgencySubjectKind::Institution { - return Err(anyhow!("remote agency profile has the wrong subject kind")); - } - profile.collective_authority_id = Some(institution_id.clone()); - profile.facets = axes - .iter() - .map(|(axis, value)| (axis.clone(), BTreeSet::from([(*value).into()]))) - .collect(); - profile.facets.insert( - AgencyAxis::Authority, - BTreeSet::from([institution_id.clone()]), - ); - profile.information_channels.clear(); - profile.evidence_receipt_ids = evidence_receipt_ids.clone(); - } - Ok(()) -} - -fn merge_evidence_receipts( - local: &[VaultEvidenceReceipt], - global: &[VaultEvidenceReceipt], -) -> Vec { - let mut seen = BTreeSet::new(); - local - .iter() - .chain(global) - .filter(|receipt| seen.insert(receipt.id.clone())) - .cloned() - .collect() -} - -fn merge_global_evidence_coverage( - local: Vec, - global: &[VaultEvidenceReceipt], -) -> Vec { - let mut coverage = local - .into_iter() - .map(|item| (item.source_id.clone(), item)) - .collect::>(); - for source_id in global - .iter() - .flat_map(|receipt| receipt.witnesses.iter()) - .map(|witness| witness.source_id.clone()) - .collect::>() - { - coverage - .entry(source_id.clone()) - .and_modify(|item| { - if item.lane == EvidenceUseLane::Excluded { - item.lane = EvidenceUseLane::SettingBackground; - item.rationale = - "Supports the remote agency catalog, not the local seed.".into(); - } - }) - .or_insert(EvidenceCoverage { - source_id, - lane: EvidenceUseLane::SettingBackground, - rationale: "Supports the remote agency catalog, not the local seed.".into(), - }); - } - coverage.into_values().collect() -} - -fn normalized_contains(document: &str, excerpt: &str) -> bool { - let document = document.split_whitespace().collect::>().join(" "); - let excerpt = excerpt.split_whitespace().collect::>().join(" "); - !excerpt.is_empty() && document.contains(&excerpt) -} - -/// Projects the exact location namespace needed to generate one bounded -/// destination without feeding every remote place's descriptive payload back -/// into each later region. Full campaign topology remains authoritative for -/// lowering and admission. -fn destination_location_generation_context( - campaign: &Campaign, - expansion_origin_location_id: &str, -) -> serde_json::Value { - let expansion_anchor = campaign - .locations - .get(expansion_origin_location_id) - .expect("destination expansion anchor is a canonical location"); - let location_index = campaign - .locations - .values() - .map(|location| { - serde_json::json!({ - "id":location.id, - "name":location.name, - "container_id":location.container_id, - }) - }) - .collect::>(); - serde_json::json!({ - "location_index":location_index, - "expansion_anchor":expansion_anchor, - }) -} - -/// Gives the destination generator a deterministic anti-cloning index instead -/// of full remote civic state. The independent verifier deliberately retains -/// `peer_civic_contexts`, so this prompt projection cannot weaken admission. -fn peer_civic_generation_contexts( - campaign: &Campaign, - excluded_location_id: &str, -) -> Vec { - campaign - .civic_systems - .values() - .filter(|system| system.jurisdiction_location_id != excluded_location_id) - .take(8) - .map(|system| { - let fact_statements = |ids: &BTreeSet| { - ids.iter() - .filter_map(|id| campaign.facts.get(id)) - .map(|fact| fact.statement.as_str()) - .collect::>() - }; - serde_json::json!({ - "jurisdiction_location_id":system.jurisdiction_location_id, - "jurisdiction_name":campaign.locations.get(&system.jurisdiction_location_id).map(|location|location.name.as_str()), - "institutions":system.governing_institution_ids.iter().filter_map(|id|campaign.institutions.get(id)).map(|institution|serde_json::json!({ - "id":institution.id, - "name":institution.name, - "resources":institution.resources, - "posture":institution.posture, - })).collect::>(), - "resident_populations":system.resident_population_ids.iter().filter_map(|id|campaign.gestalts.get(id)).map(|population|serde_json::json!({ - "id":population.id, - "name":population.name, - "goals":population.goals, - "pressures":population.pressures, - })).collect::>(), - "public_facts":{ - "authority":fact_statements(&system.public_authority_fact_ids), - "selection_or_succession":fact_statements(&system.public_selection_fact_ids), - "resources_or_revenue":fact_statements(&system.public_resource_fact_ids), - "redress_or_appeal":fact_statements(&system.public_redress_fact_ids), - }, - "political_relations":system.political_relation_ids.iter().filter_map(|id|campaign.agency_relations.get(id)).map(|relation|serde_json::json!({ - "from_subject_id":relation.from_subject_id, - "to_subject_id":relation.to_subject_id, - "kind":relation.kind, - "strength":relation.strength, - "active":relation.active, - })).collect::>(), - }) - }) - .collect() -} - -fn civic_context(campaign: &Campaign, location_id: &str) -> Option { - campaign.civic_systems.get(location_id).map(|system| { - let political_relations = system.political_relation_ids.iter() - .filter_map(|id|campaign.agency_relations.get(id)) - .collect::>(); - let relation_subject_ids = political_relations.iter() - .flat_map(|relation| [&relation.from_subject_id, &relation.to_subject_id]) - .collect::>(); - let related_institution_ids = relation_subject_ids.iter().copied() - .filter(|id|campaign.institutions.contains_key(*id) && !system.governing_institution_ids.contains(*id)) - .collect::>(); - let related_population_ids = relation_subject_ids.iter().copied() - .filter(|id|campaign.gestalts.contains_key(*id) && !system.resident_population_ids.contains(*id)) - .collect::>(); - let actor_ids = relation_subject_ids.iter().copied() - .filter(|id|campaign.actors.contains_key(*id)) - .collect::>(); - serde_json::json!({ - "manifest":system, - "institutions":system.governing_institution_ids.iter().filter_map(|id|campaign.institutions.get(id)).collect::>(), - "institution_profiles":system.governing_institution_ids.iter().filter_map(|id|campaign.agency_profiles.get(id)).collect::>(), - "related_institutions":related_institution_ids.iter().filter_map(|id|campaign.institutions.get(*id)).collect::>(), - "related_institution_profiles":related_institution_ids.iter().filter_map(|id|campaign.agency_profiles.get(*id)).collect::>(), - "residents":system.resident_population_ids.iter().filter_map(|id|campaign.gestalts.get(id)).collect::>(), - "resident_profiles":system.resident_population_ids.iter().filter_map(|id|campaign.agency_profiles.get(id)).collect::>(), - "related_populations":related_population_ids.iter().filter_map(|id|campaign.gestalts.get(*id)).collect::>(), - "related_population_profiles":related_population_ids.iter().filter_map(|id|campaign.agency_profiles.get(*id)).collect::>(), - "named_people":actor_ids.iter().filter_map(|id|campaign.actors.get(*id)).collect::>(), - "named_person_profiles":actor_ids.iter().filter_map(|id|campaign.agency_profiles.get(*id)).collect::>(), - "public_facts":system.public_authority_fact_ids.iter() - .chain(system.public_selection_fact_ids.iter()) - .chain(system.public_resource_fact_ids.iter()) - .chain(system.public_redress_fact_ids.iter()) - .filter_map(|id|campaign.facts.get(id)).collect::>(), - "political_relations":political_relations, - }) - }) -} - -fn peer_civic_contexts(campaign: &Campaign, excluded_location_id: &str) -> Vec { - campaign - .civic_systems - .values() - .filter(|system| system.jurisdiction_location_id != excluded_location_id) - .take(8) - .map(|system| { - serde_json::json!({ - "jurisdiction_location_id":system.jurisdiction_location_id, - "jurisdiction_name":campaign.locations.get(&system.jurisdiction_location_id).map(|location|location.name.as_str()), - "institutions":system.governing_institution_ids.iter().filter_map(|id|campaign.institutions.get(id)).map(|institution|serde_json::json!({ - "id":institution.id, - "name":institution.name, - "goals":institution.goals, - "resources":institution.resources, - "posture":institution.posture, - })).collect::>(), - "resident_populations":system.resident_population_ids.iter().filter_map(|id|campaign.gestalts.get(id)).map(|population|serde_json::json!({ - "id":population.id, - "name":population.name, - "goals":population.goals, - "pressures":population.pressures, - })).collect::>(), - "public_facts":system.public_authority_fact_ids.iter() - .chain(system.public_selection_fact_ids.iter()) - .chain(system.public_resource_fact_ids.iter()) - .chain(system.public_redress_fact_ids.iter()) - .filter_map(|id|campaign.facts.get(id)) - .map(|fact|fact.statement.as_str()).collect::>(), - "political_relations":system.political_relation_ids.iter().filter_map(|id|campaign.agency_relations.get(id)).collect::>(), - }) - }) - .collect() -} - -pub(crate) fn civic_candidate_digest(expansion: &crate::domain::RegionExpansion) -> Result { - let mut candidate = expansion.clone(); - if let Some(system) = &mut candidate.civic_system { - system.semantic_verification_receipt_id.clear(); - } - Ok(format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(&candidate)?) - )) -} - -pub(crate) fn civic_verifier_binding(campaign: &Campaign, candidate_digest: &str) -> String { - format!( - "campaign:{}:revision:{}:destination_civic:{}", - campaign.id, campaign.revision, candidate_digest - ) -} - -pub fn titled_civic_verifier_binding( - campaign: &Campaign, - elaboration: &LocalityElaboration, -) -> Result { - validate_locality_elaboration(campaign, elaboration)?; - Ok(civic_verifier_binding( - campaign, - &civic_candidate_digest(&elaboration.expansion)?, - )) -} - -pub(crate) fn validate_civic_admission_receipts( - campaign: &Campaign, - expansion: &crate::domain::RegionExpansion, - model_stage_receipts: &[crate::model::ModelStageReceipt], -) -> Result<()> { - let Some(system) = &expansion.civic_system else { - return Ok(()); - }; - let candidate_digest = civic_candidate_digest(expansion)?; - let expected_binding = civic_verifier_binding(campaign, &candidate_digest); - let receipt = model_stage_receipts - .iter() - .find(|receipt| receipt.storage_key() == system.semantic_verification_receipt_id) - .ok_or_else(|| anyhow!("civic admission lacks its exact semantic verifier receipt"))?; - let mut rebound = receipt.clone(); - rebound.rebind_snapshot(receipt.snapshot_binding.clone()); - if receipt.schema != "ghostlight.persona_stage_receipt.v1" - || receipt.stage != "destination_civic_verification" - || receipt.validation_result != "valid" - || receipt.local_validation_error.is_some() - || receipt.snapshot_binding != expected_binding - || rebound.storage_key() != receipt.storage_key() - { - return Err(anyhow!( - "civic admission semantic verifier receipt is invalid or candidate-mismatched" - )); - } - Ok(()) -} - -fn destination_fact_findings( - campaign: &Campaign, - facts: &[WorldFact], -) -> Vec { - let existing_fact_ids = campaign.facts.keys().cloned().collect::>(); - let mut candidate_fact_ids = BTreeSet::new(); - let mut statement_owners = BTreeMap::>::new(); - for fact in campaign.facts.values() { - statement_owners - .entry(fact.statement.clone()) - .or_default() - .push(fact.id.clone()); - } - let mut findings = Vec::new(); - for (fact_index, fact) in facts.iter().enumerate() { - if fact.id.trim().is_empty() { - findings.push(DestinationFactFinding { - kind: DestinationFactFindingKind::EmptyId, - fact_index, - submitted_fact_id: fact.id.clone(), - statement: fact.statement.clone(), - conflicts_with_fact_ids: Vec::new(), - }); - } - if existing_fact_ids.contains(&fact.id) { - findings.push(DestinationFactFinding { - kind: DestinationFactFindingKind::ExistingId, - fact_index, - submitted_fact_id: fact.id.clone(), - statement: fact.statement.clone(), - conflicts_with_fact_ids: vec![fact.id.clone()], - }); - } - if !candidate_fact_ids.insert(fact.id.clone()) { - findings.push(DestinationFactFinding { - kind: DestinationFactFindingKind::DuplicateId, - fact_index, - submitted_fact_id: fact.id.clone(), - statement: fact.statement.clone(), - conflicts_with_fact_ids: vec![fact.id.clone()], - }); - } - if fact.statement.trim().is_empty() { - findings.push(DestinationFactFinding { - kind: DestinationFactFindingKind::EmptyStatement, - fact_index, - submitted_fact_id: fact.id.clone(), - statement: fact.statement.clone(), - conflicts_with_fact_ids: Vec::new(), - }); - } else if let Some(conflicts) = statement_owners.get(&fact.statement) { - findings.push(DestinationFactFinding { - kind: DestinationFactFindingKind::DuplicateStatement, - fact_index, - submitted_fact_id: fact.id.clone(), - statement: fact.statement.clone(), - conflicts_with_fact_ids: conflicts.clone(), - }); - } - if fact - .evidence_receipt_ids - .iter() - .any(|receipt_id| receipt_id.trim().is_empty()) - { - findings.push(DestinationFactFinding { - kind: DestinationFactFindingKind::EmptyEvidenceReceiptId, - fact_index, - submitted_fact_id: fact.id.clone(), - statement: fact.statement.clone(), - conflicts_with_fact_ids: Vec::new(), - }); - } - if !fact.statement.trim().is_empty() { - statement_owners - .entry(fact.statement.clone()) - .or_default() - .push(fact.id.clone()); - } - } - findings -} - -pub fn validate_region_expansion( - campaign: &Campaign, - expansion: &crate::domain::RegionExpansion, -) -> Result<()> { - if !campaign - .locations - .contains_key(&expansion.origin_location_id) - { - return Err(anyhow!("destination expansion origin is unknown")); - } - let new_ids: BTreeSet<_> = expansion.locations.iter().map(|x| x.id.as_str()).collect(); - if expansion.locations.is_empty() - || new_ids.len() != expansion.locations.len() - || new_ids.iter().any(|id| id.trim().is_empty()) - { - return Err(anyhow!("destination expansion has no unique locations")); - } - if new_ids - .iter() - .any(|id| campaign.locations.contains_key(*id)) - { - return Err(anyhow!( - "destination expansion collides with stable topology" - )); - } - let known = |id: &str| campaign.locations.contains_key(id) || new_ids.contains(id); - let new_locations = expansion - .locations - .iter() - .map(|location| (location.id.as_str(), location)) - .collect::>(); - let existing_origin_route_ids = campaign - .locations - .get(&expansion.origin_location_id) - .map(|location| { - location - .routes - .keys() - .map(String::as_str) - .collect::>() - }) - .unwrap_or_default(); - if expansion.origin_routes.is_empty() { - return Err(anyhow!( - "destination expansion has no explicit route from the origin" - )); - } - for (route_id, route) in &expansion.origin_routes { - if route_id.trim().is_empty() - || existing_origin_route_ids.contains(route_id.as_str()) - || route.travel_minutes == 0 - || route.distance.trim().is_empty() - || !new_ids.contains(route.destination_id.as_str()) - { - return Err(anyhow!("destination expansion has an invalid origin route")); - } - let destination = new_locations - .get(route.destination_id.as_str()) - .expect("origin route destination was admitted above"); - if !destination.routes.values().any(|reverse| { - reverse.destination_id == expansion.origin_location_id - && reverse.travel_minutes == route.travel_minutes - }) { - return Err(anyhow!( - "destination expansion origin route lacks an exact reciprocal return route" - )); - } - } - for location in &expansion.locations { - if location.name.trim().is_empty() - || location - .persistent_features - .iter() - .any(|feature| feature.trim().is_empty()) - || location - .persistent_features - .iter() - .collect::>() - .len() - != location.persistent_features.len() - { - return Err(anyhow!( - "destination expansion has a malformed place profile" - )); - } - if let Some(container_id) = &location.container_id - && (!known(container_id) || container_id == &location.id) - { - return Err(anyhow!("destination expansion has an invalid container")); - } - for (route_id, route) in &location.routes { - if route_id.trim().is_empty() - || route.travel_minutes == 0 - || route.distance.trim().is_empty() - || !known(&route.destination_id) - || route.destination_id == location.id - { - return Err(anyhow!("destination expansion has a dangling route")); - } - } - } - for location in &expansion.locations { - let mut seen = BTreeSet::from([location.id.as_str()]); - let mut cursor = location.container_id.as_deref(); - while let Some(container_id) = cursor { - if !seen.insert(container_id) { - return Err(anyhow!( - "destination expansion containment contains a cycle" - )); - } - cursor = new_locations - .get(container_id) - .and_then(|container| container.container_id.as_deref()) - .or_else(|| { - campaign - .locations - .get(container_id) - .and_then(|container| container.container_id.as_deref()) - }); - } - } - let mut directed_routes = BTreeMap::>::new(); - for location in campaign.locations.values() { - directed_routes - .entry(location.id.clone()) - .or_default() - .extend( - location - .routes - .values() - .map(|route| route.destination_id.clone()), - ); - } - directed_routes - .entry(expansion.origin_location_id.clone()) - .or_default() - .extend( - expansion - .origin_routes - .values() - .map(|route| route.destination_id.clone()), - ); - for location in &expansion.locations { - directed_routes - .entry(location.id.clone()) - .or_default() - .extend( - location - .routes - .values() - .map(|route| route.destination_id.clone()), - ); - } - let reachable_from = |routes: &BTreeMap>, start: &str| { - let mut reachable = BTreeSet::from([start.to_owned()]); - let mut frontier = std::collections::VecDeque::from([start.to_owned()]); - while let Some(origin) = frontier.pop_front() { - for destination in routes.get(&origin).into_iter().flatten() { - if reachable.insert(destination.clone()) { - frontier.push_back(destination.clone()); - } - } - } - reachable - }; - let outward_reachable = reachable_from(&directed_routes, &expansion.origin_location_id); - let mut reverse_routes = BTreeMap::>::new(); - for (origin, destinations) in &directed_routes { - for destination in destinations { - reverse_routes - .entry(destination.clone()) - .or_default() - .insert(origin.clone()); - } - } - let return_reachable = reachable_from(&reverse_routes, &expansion.origin_location_id); - let unreachable_outward = new_ids - .iter() - .filter(|id| !outward_reachable.contains(**id)) - .copied() - .collect::>(); - let unreachable_return = new_ids - .iter() - .filter(|id| !return_reachable.contains(**id)) - .copied() - .collect::>(); - if !unreachable_outward.is_empty() || !unreachable_return.is_empty() { - return Err(anyhow!( - "destination expansion does not provide directed origin reachability for every new location; unreachable outward: {:?}; unreachable return: {:?}", - unreachable_outward, - unreachable_return - )); - } - if let Some(finding) = destination_fact_findings(campaign, &expansion.facts).first() { - return Err(anyhow!( - "destination expansion fact namespace rejected candidate: {}", - serde_json::to_string(finding).unwrap_or_else(|_| "null".into()) - )); - } - let new_fact_ids = expansion - .facts - .iter() - .map(|fact| fact.id.clone()) - .collect::>(); - let fact_statements = campaign - .facts - .values() - .chain(expansion.facts.iter()) - .map(|fact| fact.statement.clone()) - .collect::>(); - for fact in &expansion.facts { - if fact - .discoverable_at_location_ids - .iter() - .any(|id| !known(id)) - { - return Err(anyhow!( - "destination expansion fact {} has an unknown discovery location", - fact.id - )); - } - } - let population_ids = expansion - .populations - .iter() - .map(|population| population.id.as_str()) - .collect::>(); - if expansion.populations.len() > 8 - || population_ids.len() != expansion.populations.len() - || population_ids.iter().any(|id| { - id.trim().is_empty() - || campaign.gestalts.contains_key(*id) - || campaign.actors.contains_key(*id) - || campaign.institutions.contains_key(*id) - }) - { - return Err(anyhow!( - "destination populations need at most eight unique new canonical subject IDs" - )); - } - let established_population_names = campaign - .gestalts - .values() - .map(|population| crate::resolution::public_identity_key(&population.name)) - .collect::>(); - let mut candidate_population_names = BTreeSet::new(); - for population in &expansion.populations { - let name_key = crate::resolution::public_identity_key(&population.name); - if name_key.is_empty() - || established_population_names.contains(&name_key) - || !candidate_population_names.insert(name_key) - { - return Err(anyhow!( - "destination population {} needs a distinct public population identity", - population.id - )); - } - } - let profile_ids = expansion - .population_profiles - .iter() - .map(|profile| profile.subject_id.as_str()) - .collect::>(); - if profile_ids != population_ids - || expansion.population_profiles.len() != expansion.populations.len() - { - return Err(anyhow!( - "destination population profiles must cover every new population exactly once" - )); - } - let axes = BTreeSet::from([ - AgencyAxis::Geography, - AgencyAxis::Ideology, - AgencyAxis::Authority, - AgencyAxis::EconomyRole, - AgencyAxis::SpeciesBody, - AgencyAxis::Information, - ]); - for population in &expansion.populations { - if population.schema != "ghostlight.gestalt_persona_state.v1" - || population.version != 0 - || population.name.trim().is_empty() - || !new_ids.contains(population.home_location_id.as_str()) - || population.goals.is_empty() - || population - .shared_capabilities - .iter() - .chain(population.shared_knowledge.iter()) - .chain(population.resources.iter()) - .chain(population.goals.iter()) - .chain(population.pressures.iter()) - .any(|value| value.trim().is_empty()) - || population - .shared_knowledge - .iter() - .any(|statement| !fact_statements.contains(statement)) - { - return Err(anyhow!( - "destination population {} has malformed or unsupported canonical state", - population.id - )); - } - let profile = expansion - .population_profiles - .iter() - .find(|profile| profile.subject_id == population.id) - .expect("profile coverage was checked above"); - let profile_axes = profile.facets.keys().cloned().collect::>(); - if profile.schema != "ghostlight.agency_profile.v1" - || profile.id != format!("agency:{}", population.id) - || profile.subject_kind != AgencySubjectKind::Gestalt - || profile.profile_version != 0 - || profile.parent_subject_id.is_some() - || !profile.active_leaf - || !profile.simulation_eligible - || profile.location_ids != BTreeSet::from([population.home_location_id.clone()]) - || profile_axes != axes - || profile - .collective_authority_id - .as_ref() - .is_some_and(|authority| !population_ids.contains(authority.as_str())) - || profile - .information_channels - .iter() - .any(|channel| !crate::resolution::information_channel_is_concrete(channel)) - || profile - .information_channels - .intersection(&population.shared_knowledge) - .next() - .is_some() - { - return Err(anyhow!( - "destination population {} has a malformed agency profile", - population.id - )); - } - } - let institution_ids = expansion - .institutions - .iter() - .map(|institution| institution.id.as_str()) - .collect::>(); - if expansion.institutions.len() > 12 - || institution_ids.len() != expansion.institutions.len() - || institution_ids.iter().any(|id| { - id.trim().is_empty() - || population_ids.contains(id) - || campaign.gestalts.contains_key(*id) - || campaign.actors.contains_key(*id) - || campaign.institutions.contains_key(*id) - }) - { - return Err(anyhow!( - "destination institutions need at most twelve unique new canonical subject IDs" - )); - } - let institution_profile_ids = expansion - .institution_profiles - .iter() - .map(|profile| profile.subject_id.as_str()) - .collect::>(); - if institution_profile_ids != institution_ids - || expansion.institution_profiles.len() != expansion.institutions.len() - { - return Err(anyhow!( - "destination institution profiles must cover every new institution exactly once" - )); - } - for institution in &expansion.institutions { - if institution.name.trim().is_empty() - || institution.posture.trim().is_empty() - || institution.posture.chars().count() > MAX_POSTURE_CHARS - || institution.goals.is_empty() - || institution - .resources - .iter() - .chain(institution.goals.iter()) - .any(|value| value.trim().is_empty()) - { - return Err(anyhow!( - "destination institution {} has malformed canonical state", - institution.id - )); - } - let profile = expansion - .institution_profiles - .iter() - .find(|profile| profile.subject_id == institution.id) - .expect("institution profile coverage was checked above"); - let profile_axes = profile.facets.keys().cloned().collect::>(); - let unknown_location_ids = profile - .location_ids - .iter() - .filter(|id| !known(id)) - .cloned() - .collect::>(); - let invalid_information_channels = profile - .information_channels - .iter() - .filter(|channel| !crate::resolution::information_channel_is_concrete(channel)) - .cloned() - .collect::>(); - if profile.location_ids.is_empty() { - return Err(anyhow!( - "destination institution {} agency profile has no location", - institution.id - )); - } - if !unknown_location_ids.is_empty() { - return Err(anyhow!( - "destination institution {} agency profile references unknown locations {:?}", - institution.id, - unknown_location_ids - )); - } - if profile_axes != axes { - return Err(anyhow!( - "destination institution {} agency profile must define exactly the six agency facets", - institution.id - )); - } - if !invalid_information_channels.is_empty() { - return Err(anyhow!( - "destination institution {} agency profile has non-concrete information channels {:?}", - institution.id, - invalid_information_channels - )); - } - if profile.schema != "ghostlight.agency_profile.v1" - || profile.id != format!("agency:{}", institution.id) - || profile.subject_kind != AgencySubjectKind::Institution - || profile.profile_version != 0 - || profile.collective_authority_id.is_some() - || profile.parent_subject_id.is_some() - || !profile.active_leaf - || !profile.simulation_eligible - { - return Err(anyhow!( - "destination institution {} has a malformed compiler-owned agency profile", - institution.id - )); - } - } - let existing_civic = expansion - .civic_system - .as_ref() - .and_then(|system| campaign.civic_systems.get(&system.jurisdiction_location_id)); - let existing_civic_subject_ids = existing_civic - .into_iter() - .flat_map(|system| { - system - .governing_institution_ids - .iter() - .chain(system.resident_population_ids.iter()) - }) - .map(String::as_str) - .collect::>(); - let local_subject_ids = population_ids - .iter() - .copied() - .chain(institution_ids.iter().copied()) - .chain(existing_civic_subject_ids.iter().copied()) - .collect::>(); - let mut local_relation_ids = BTreeSet::new(); - for relation in &expansion.local_relations { - if expansion.local_relations.len() > 48 - || relation.schema != AgencyRelation::SCHEMA - || relation.id.trim().is_empty() - || !local_relation_ids.insert(relation.id.as_str()) - || campaign.agency_relations.contains_key(&relation.id) - || relation.kind == AgencyRelationKind::Migration - || !relation.active - || relation.strength == 0 - || relation.strength > 100 - || relation.from_subject_id == relation.to_subject_id - || !local_subject_ids.contains(relation.from_subject_id.as_str()) - || !local_subject_ids.contains(relation.to_subject_id.as_str()) - { - return Err(anyhow!( - "destination local relation {} is not an exact new local-subject edge", - relation.id - )); - } - } - if let Some(civic) = expansion.civic_system.as_ref() { - let civic_fact_ids = civic - .public_authority_fact_ids - .iter() - .chain(civic.public_selection_fact_ids.iter()) - .chain(civic.public_resource_fact_ids.iter()) - .chain(civic.public_redress_fact_ids.iter()) - .collect::>(); - let previous = campaign.civic_systems.get(&civic.jurisdiction_location_id); - let expected_version = previous - .map(|system| system.version.saturating_add(1)) - .unwrap_or(0); - let previous_institution_ids = previous - .into_iter() - .flat_map(|system| system.governing_institution_ids.iter()) - .collect::>(); - let previous_resident_ids = previous - .into_iter() - .flat_map(|system| system.resident_population_ids.iter()) - .collect::>(); - let previous_relation_ids = previous - .into_iter() - .flat_map(|system| system.political_relation_ids.iter()) - .collect::>(); - let allowed_institution_ids = institution_ids - .iter() - .map(|id| (*id).to_owned()) - .chain(previous_institution_ids.iter().map(|id| (*id).clone())) - .collect::>(); - let expected_resident_ids = population_ids - .iter() - .map(|id| (*id).to_owned()) - .chain(previous_resident_ids.iter().map(|id| (*id).clone())) - .collect::>(); - let allowed_relation_ids = local_relation_ids - .iter() - .map(|id| (*id).to_owned()) - .chain(previous_relation_ids.iter().map(|id| (*id).clone())) - .collect::>(); - let allowed_fact_ids = new_fact_ids - .iter() - .cloned() - .chain(previous.into_iter().flat_map(|system| { - system - .public_authority_fact_ids - .iter() - .chain(system.public_selection_fact_ids.iter()) - .chain(system.public_resource_fact_ids.iter()) - .chain(system.public_redress_fact_ids.iter()) - .cloned() - })) - .collect::>(); - let mut closure_failures = Vec::new(); - if civic.schema != "ghostlight.civic_system_manifest.v1" { - closure_failures.push("schema must be ghostlight.civic_system_manifest.v1".into()); - } - if civic.version != expected_version { - closure_failures.push(format!("version must be {expected_version}")); - } - if !known(&civic.jurisdiction_location_id) { - closure_failures.push("jurisdiction_location_id must name a known location".into()); - } - if civic.governing_institution_ids.len() < 2 { - closure_failures.push("candidate needs at least two governing institutions".into()); - } - if expected_resident_ids.is_empty() { - closure_failures.push("candidate needs at least one resident population".into()); - } - if civic.governing_institution_ids.is_empty() { - closure_failures.push("governing_institution_ids must not be empty".into()); - } - let unknown_institution_ids = civic - .governing_institution_ids - .difference(&allowed_institution_ids) - .cloned() - .collect::>(); - if !unknown_institution_ids.is_empty() { - closure_failures.push(format!( - "governing_institution_ids contain unknown IDs {unknown_institution_ids:?}" - )); - } - let omitted_previous_institution_ids = previous_institution_ids - .iter() - .filter(|id| !civic.governing_institution_ids.contains(**id)) - .map(|id| (*id).clone()) - .collect::>(); - if !omitted_previous_institution_ids.is_empty() { - closure_failures.push(format!( - "governing_institution_ids omitted existing IDs {omitted_previous_institution_ids:?}" - )); - } - if civic.resident_population_ids != expected_resident_ids { - closure_failures.push(format!( - "resident_population_ids must equal {expected_resident_ids:?}" - )); - } - if civic.public_authority_fact_ids.is_empty() { - closure_failures.push("public_authority_fact_ids must not be empty".into()); - } - if civic.public_selection_fact_ids.is_empty() { - closure_failures.push("public_selection_fact_ids must not be empty".into()); - } - if civic.public_resource_fact_ids.is_empty() { - closure_failures.push("public_resource_fact_ids must not be empty".into()); - } - if civic.public_redress_fact_ids.is_empty() { - closure_failures.push("public_redress_fact_ids must not be empty".into()); - } - let unknown_fact_ids = civic_fact_ids - .iter() - .filter(|id| !allowed_fact_ids.contains(**id)) - .map(|id| (*id).clone()) - .collect::>(); - if !unknown_fact_ids.is_empty() { - closure_failures.push(format!( - "public civic fact groups contain unknown IDs {unknown_fact_ids:?}" - )); - } - if civic.political_relation_ids.is_empty() { - closure_failures.push("political_relation_ids must not be empty".into()); - } - let unknown_relation_ids = civic - .political_relation_ids - .difference(&allowed_relation_ids) - .cloned() - .collect::>(); - if !unknown_relation_ids.is_empty() { - closure_failures.push(format!( - "political_relation_ids contain unknown IDs {unknown_relation_ids:?}" - )); - } - let omitted_previous_relation_ids = previous_relation_ids - .iter() - .filter(|id| !civic.political_relation_ids.contains(**id)) - .map(|id| (*id).clone()) - .collect::>(); - if !omitted_previous_relation_ids.is_empty() { - closure_failures.push(format!( - "political_relation_ids omitted existing IDs {omitted_previous_relation_ids:?}" - )); - } - if let Some(previous) = previous { - if !previous - .public_authority_fact_ids - .is_subset(&civic.public_authority_fact_ids) - { - closure_failures.push("public_authority_fact_ids omitted existing facts".into()); - } - if !previous - .public_selection_fact_ids - .is_subset(&civic.public_selection_fact_ids) - { - closure_failures.push("public_selection_fact_ids omitted existing facts".into()); - } - if !previous - .public_resource_fact_ids - .is_subset(&civic.public_resource_fact_ids) - { - closure_failures.push("public_resource_fact_ids omitted existing facts".into()); - } - if !previous - .public_redress_fact_ids - .is_subset(&civic.public_redress_fact_ids) - { - closure_failures.push("public_redress_fact_ids omitted existing facts".into()); - } - } - if !closure_failures.is_empty() { - return Err(anyhow!( - "inhabited destination civic manifest closure failures: {}", - closure_failures.join("; ") - )); - } - let public_statements = civic_fact_ids - .iter() - .map(|fact_id| { - expansion - .facts - .iter() - .find(|fact| fact.id.as_str() == fact_id.as_str()) - .or_else(|| campaign.facts.get(*fact_id)) - .map(|fact| fact.statement.as_str()) - .ok_or_else(|| anyhow!("civic manifest references a missing public fact")) - }) - .collect::>>()?; - if expansion.populations.iter().any(|population| { - public_statements - .iter() - .any(|statement| !population.shared_knowledge.contains(*statement)) - }) { - return Err(anyhow!( - "every resident population must know the committed public civic facts" - )); - } - if expansion.facts.iter().any(|fact| { - civic_fact_ids.contains(&fact.id) - && fact.scope == FactScope::CanonBaseline - && fact.evidence_receipt_ids.is_empty() - }) { - return Err(anyhow!( - "an invented public civic fact cannot claim canon-baseline scope without evidence" - )); - } - if !civic.political_relation_ids.iter().any(|id| { - expansion - .local_relations - .iter() - .find(|relation| relation.id == *id) - .or_else(|| campaign.agency_relations.get(id)) - .is_some_and(|relation| { - matches!( - relation.kind, - AgencyRelationKind::Command - | AgencyRelationKind::Rivalry - | AgencyRelationKind::Coercion - ) && (civic - .governing_institution_ids - .contains(&relation.from_subject_id) - || civic - .governing_institution_ids - .contains(&relation.to_subject_id)) - }) - }) { - return Err(anyhow!( - "civic system needs a command, rivalry, or coercion edge that makes political authority or contestation legible" - )); - } - } - let mut relation_ids = local_relation_ids; - for relation in &expansion.migration_relations { - let source_is_exact_origin_leaf = campaign - .gestalts - .get(&relation.from_subject_id) - .is_some_and(|source| source.home_location_id == expansion.origin_location_id) - && campaign - .agency_profiles - .get(&relation.from_subject_id) - .is_some_and(|profile| { - profile.subject_kind == AgencySubjectKind::Gestalt - && profile.active_leaf - && profile.simulation_eligible - }); - if expansion.migration_relations.len() > 32 - || relation.schema != AgencyRelation::SCHEMA - || relation.id.trim().is_empty() - || !relation_ids.insert(relation.id.as_str()) - || campaign.agency_relations.contains_key(&relation.id) - || relation.kind != AgencyRelationKind::Migration - || !relation.active - || relation.strength == 0 - || relation.strength > 100 - || relation.from_subject_id == relation.to_subject_id - || !source_is_exact_origin_leaf - || !population_ids.contains(relation.to_subject_id.as_str()) - { - return Err(anyhow!( - "destination migration relation {} is not an exact origin-leaf to new-population edge", - relation.id - )); - } - } - if !expansion.migration_relations.is_empty() { - let mut candidate = campaign.clone(); - for location in &expansion.locations { - candidate - .locations - .insert(location.id.clone(), location.clone()); - } - candidate - .locations - .get_mut(&expansion.origin_location_id) - .expect("origin was checked above") - .routes - .extend(expansion.origin_routes.clone()); - for population in &expansion.populations { - candidate - .gestalts - .insert(population.id.clone(), population.clone()); - } - for profile in &expansion.population_profiles { - candidate - .agency_profiles - .insert(profile.subject_id.clone(), profile.clone()); - } - for relation in &expansion.migration_relations { - candidate - .agency_relations - .insert(relation.id.clone(), relation.clone()); - let destination = candidate - .gestalts - .get(&relation.to_subject_id) - .expect("migration target was checked above"); - if crate::resolution::route_travel_minutes_within( - &candidate, - &expansion.origin_location_id, - &destination.home_location_id, - campaign.tick_hours.saturating_mul(60), - ) - .is_none() - { - return Err(anyhow!( - "destination migration relation {} exceeds the strategic travel horizon", - relation.id - )); - } - } - } - Ok(()) -} - -pub fn validate_new_destination_expansion( - campaign: &Campaign, - expansion: &crate::domain::RegionExpansion, -) -> Result<()> { - validate_region_expansion(campaign, expansion)?; - if let Some(civic) = &expansion.civic_system { - if !expansion - .locations - .iter() - .any(|location| location.id == civic.jurisdiction_location_id) - { - return Err(anyhow!( - "new destination civic jurisdiction must be one newly admitted location" - )); - } - validate_civic_locality_scope(campaign, expansion, &civic.jurisdiction_location_id)?; - } - Ok(()) -} - -pub fn validate_locality_elaboration( - campaign: &Campaign, - elaboration: &LocalityElaboration, -) -> Result<()> { - validate_region_expansion(campaign, &elaboration.expansion)?; - if !campaign - .locations - .contains_key(&elaboration.target_location_id) - || elaboration.expansion.origin_location_id != elaboration.target_location_id - { - return Err(anyhow!( - "locality elaboration must preserve one exact canonical target as its expansion anchor" - )); - } - if elaboration.expansion.locations.iter().any(|location| { - !expansion_location_is_within( - campaign, - &elaboration.expansion, - &location.id, - &elaboration.target_location_id, - ) - }) { - return Err(anyhow!( - "locality elaboration may admit only child places beneath its exact target" - )); - } - let civic = elaboration - .expansion - .civic_system - .as_ref() - .ok_or_else(|| anyhow!("locality elaboration requires a civic system manifest"))?; - if civic.jurisdiction_location_id != elaboration.target_location_id { - return Err(anyhow!( - "locality civic jurisdiction must remain the exact canonical target" - )); - } - validate_civic_locality_scope( - campaign, - &elaboration.expansion, - &elaboration.target_location_id, - )?; - Ok(()) -} - -fn validate_civic_locality_scope( - campaign: &Campaign, - expansion: &crate::domain::RegionExpansion, - jurisdiction_location_id: &str, -) -> Result<()> { - if expansion.populations.iter().any(|population| { - !expansion_location_is_within( - campaign, - expansion, - &population.home_location_id, - jurisdiction_location_id, - ) - }) || expansion.institution_profiles.iter().any(|profile| { - profile.location_ids.iter().any(|location_id| { - !expansion_location_is_within( - campaign, - expansion, - location_id, - jurisdiction_location_id, - ) - }) - }) { - return Err(anyhow!( - "civic populations and institutions must be located within their exact jurisdiction" - )); - } - let civic = expansion - .civic_system - .as_ref() - .expect("civic scope validation follows civic manifest validation"); - let public_fact_ids = civic - .public_authority_fact_ids - .iter() - .chain(civic.public_selection_fact_ids.iter()) - .chain(civic.public_resource_fact_ids.iter()) - .chain(civic.public_redress_fact_ids.iter()) - .collect::>(); - if expansion.facts.iter().any(|fact| { - public_fact_ids.contains(&fact.id) - && (fact.discoverable_at_location_ids.is_empty() - || fact.discoverable_at_location_ids.iter().any(|location_id| { - !expansion_location_is_within( - campaign, - expansion, - location_id, - jurisdiction_location_id, - ) - })) - }) { - return Err(anyhow!( - "public civic facts must be discoverable only within their exact jurisdiction" - )); - } - Ok(()) -} - -fn expansion_location_is_within( - campaign: &Campaign, - expansion: &crate::domain::RegionExpansion, - location_id: &str, - ancestor_id: &str, -) -> bool { - let new_locations = expansion - .locations - .iter() - .map(|location| (location.id.as_str(), location)) - .collect::>(); - let mut cursor = Some(location_id); - let mut seen = BTreeSet::new(); - while let Some(id) = cursor { - if id == ancestor_id { - return true; - } - if !seen.insert(id) { - return false; - } - cursor = new_locations - .get(id) - .and_then(|location| location.container_id.as_deref()) - .or_else(|| { - campaign - .locations - .get(id) - .and_then(|location| location.container_id.as_deref()) - }); - } - false -} - -fn evidence_text(receipts: &[VaultEvidenceReceipt]) -> String { - let mut seen = BTreeSet::new(); - receipts - .iter() - .flat_map(|receipt| { - receipt - .witnesses - .iter() - .map(move |witness| (receipt.id.as_str(), witness)) - }) - .filter(|(_, witness)| { - seen.insert(( - witness.source_id.clone(), - witness.exact_locator.clone(), - witness.content_hash.clone(), - )) - }) - .map(|(receipt_id, witness)| { - format!( - "[receipt_id={} | source={} | authority_lane={} | locator={} | content_hash={}] {}", - receipt_id, - witness.source_id, - witness.authority_lane, - witness.exact_locator, - witness.content_hash, - witness.excerpt - ) - }) - .collect::>() - .join("\n\n") -} - -fn opening_evidence_text(queries: &[String], receipts: &[VaultEvidenceReceipt]) -> String { - const FRAME_LABELS: [&str; 3] = ["early", "transition", "late"]; - queries - .iter() - .zip(receipts) - .zip(FRAME_LABELS) - .map(|((query, receipt), frame)| { - let witnesses = evidence_text(std::slice::from_ref(receipt)); - format!("[historical_frame={frame} | retrieval_query={query}]\n{witnesses}") - }) - .collect::>() - .join("\n\n") -} - -fn direct_seed_evidence_text( - receipts: &[VaultEvidenceReceipt], - coverage: &[EvidenceCoverage], -) -> String { - let coverage = coverage - .iter() - .map(|item| (item.source_id.as_str(), item)) - .collect::>(); - let mut seen = BTreeSet::new(); - receipts - .iter() - .flat_map(|receipt| { - receipt - .witnesses - .iter() - .map(move |witness| (receipt.id.as_str(), witness)) - }) - .filter_map(|(receipt_id, witness)| { - let use_plan = coverage.get(witness.source_id.as_str())?; - if use_plan.lane != EvidenceUseLane::DirectSeed - || !authority_allows_direct_seed(&witness.authority_lane) - || !seen.insert(( - witness.source_id.clone(), - witness.exact_locator.clone(), - witness.content_hash.clone(), - )) - { - return None; - } - Some(format!( - "[usage_lane=direct_seed | rationale={} | receipt_id={} | source={} | authority_lane={} | locator={} | content_hash={}] {}", - use_plan.rationale, - receipt_id, - witness.source_id, - witness.authority_lane, - witness.exact_locator, - witness.content_hash, - witness.excerpt - )) - }) - .collect::>() - .join("\n\n") -} - -fn receipt_ids_for_coverage( - receipts: &[VaultEvidenceReceipt], - coverage: &[EvidenceCoverage], -) -> Vec { - let included_sources = coverage - .iter() - .filter(|item| item.lane == EvidenceUseLane::DirectSeed) - .map(|item| item.source_id.as_str()) - .collect::>(); - receipts - .iter() - .filter(|receipt| { - receipt.witnesses.iter().any(|witness| { - included_sources.contains(witness.source_id.as_str()) - && authority_allows_direct_seed(&witness.authority_lane) - }) - }) - .map(|receipt| receipt.id.clone()) - .collect() -} - -fn receipt_ids(receipts: &[VaultEvidenceReceipt]) -> Vec { - let mut ids = receipts - .iter() - .map(|receipt| receipt.id.clone()) - .collect::>(); - deduplicate_ids(&mut ids); - ids -} - -fn ensure_distinct_openings(items: &[OpeningSuggestion]) -> Result<()> { - ensure_distinct_fields( - "openings", - [ - ("era", items.iter().map(|x| x.era.as_str()).collect()), - ("place", items.iter().map(|x| x.place.as_str()).collect()), - ( - "pressure", - items.iter().map(|x| x.pressure.as_str()).collect(), - ), - ], - ) -} - -fn ensure_distinct_roles(items: &[RoleSuggestion]) -> Result<()> { - ensure_distinct_fields( - "roles", - [ - ("name", items.iter().map(|x| x.name.as_str()).collect()), - ( - "premise", - items.iter().map(|x| x.premise.as_str()).collect(), - ), - ], - ) -} - -fn validate_opening_suggestions(items: &[OpeningSuggestion], receipts: &[String]) -> Result<()> { - ensure_distinct_openings(items)?; - let mut ids = BTreeSet::new(); - for item in items { - validate_user_text("opening id", &item.id, 160)?; - validate_user_text("opening title", &item.title, 160)?; - validate_user_text("opening era", &item.era, 160)?; - validate_user_text("opening place", &item.place, 240)?; - validate_user_text("opening pressure", &item.pressure, 500)?; - validate_user_text("opening player hook", &item.player_hook, 500)?; - if !ids.insert(item.id.trim().to_owned()) { - return Err(anyhow!("opening ids must be unique")); - } - validate_suggestion_evidence("opening", &item.evidence_receipt_ids, receipts)?; - } - Ok(()) -} - -fn validate_role_suggestions(items: &[RoleSuggestion], receipts: &[String]) -> Result<()> { - ensure_distinct_roles(items)?; - let mut ids = BTreeSet::new(); - for item in items { - validate_user_text("role id", &item.id, 160)?; - validate_user_text("role name", &item.name, 160)?; - validate_user_text("role premise", &item.premise, 500)?; - if !ids.insert(item.id.trim().to_owned()) { - return Err(anyhow!("role ids must be unique")); - } - if item.capabilities.is_empty() - || item.capabilities.len() > 8 - || item.obligations.is_empty() - || item.obligations.len() > 8 - { - return Err(anyhow!( - "each role needs between 1 and 8 capabilities and obligations" - )); - } - for capability in &item.capabilities { - validate_user_text("role capability", capability, 160)?; - } - for obligation in &item.obligations { - validate_user_text("role obligation", obligation, 160)?; - } - validate_suggestion_evidence("role", &item.evidence_receipt_ids, receipts)?; - } - Ok(()) -} - -fn validate_suggestion_evidence( - label: &str, - supplied: &[String], - allowed: &[String], -) -> Result<()> { - let unique = supplied.iter().collect::>(); - let allowed = allowed.iter().collect::>(); - if supplied.len() > 8 { - return Err(anyhow!( - "{label} evidence may contain at most 8 receipt ids" - )); - } - if unique.len() != supplied.len() { - return Err(anyhow!("{label} evidence repeats a receipt id")); - } - let unknown = unique.difference(&allowed).copied().collect::>(); - if !unknown.is_empty() { - return Err(anyhow!( - "{label} evidence names receipt ids absent from the supplied Vault evidence: {unknown:?}" - )); - } - Ok(()) -} - -fn deduplicate_ids(ids: &mut Vec) { - let mut seen = BTreeSet::new(); - ids.retain(|id| seen.insert(id.clone())); -} - -fn ensure_distinct_fields( - subject: &str, - axes: [(&str, Vec<&str>); N], -) -> Result<()> { - let mut collisions = Vec::new(); - for (axis, values) in axes { - let mut counts = BTreeMap::new(); - for value in values { - *counts.entry(value.trim().to_lowercase()).or_insert(0usize) += 1; - } - for (value, count) in counts { - if count > 1 { - collisions.push(format!("{axis}={value:?} repeated {count} times")); - } - } - } - if collisions.is_empty() { - Ok(()) - } else { - Err(anyhow!( - "{subject} contain duplicate axes: {}", - collisions.join("; ") - )) - } -} - -fn seed_to_campaign(mut seed: CompiledSeed, receipts: &[VaultEvidenceReceipt]) -> Result { - for member in &mut seed.gestalt_members { - member.id = crate::domain::canonical_gestalt_member_local_id(&member.id); - if member.id.is_empty() { - return Err(anyhow!("compiled gestalt member ID is empty")); - } - } - require_unique_ids( - "location", - seed.locations.iter().map(|item| item.id.as_str()), - )?; - require_unique_ids("actor", seed.actors.iter().map(|item| item.id.as_str()))?; - require_unique_ids( - "institution", - seed.institutions.iter().map(|item| item.id.as_str()), - )?; - require_unique_ids("clock", seed.clocks.iter().map(|item| item.id.as_str()))?; - require_unique_ids("fact", seed.facts.iter().map(|item| item.id.as_str()))?; - require_unique_ids("gestalt", seed.gestalts.iter().map(|item| item.id.as_str()))?; - require_unique_ids( - "gestalt member", - seed.gestalt_members.iter().map(|item| item.id.as_str()), - )?; - let player_id_collisions = seed - .actors - .iter() - .filter(|actor| actor.id == seed.player.id) - .map(|actor| actor.id.clone()) - .chain( - seed.gestalt_members - .iter() - .filter(|member| member.id == seed.player.id) - .map(|member| member.id.clone()), - ) - .collect::>(); - if !player_id_collisions.is_empty() { - return Err(anyhow!( - "the singular player subject must not appear in autonomous actors or gestalt_members; remove duplicate player IDs {player_id_collisions:?}" - )); - } - require_unique_ids( - "canonical subject", - std::iter::once(seed.player.id.as_str()) - .chain(seed.actors.iter().map(|item| item.id.as_str())) - .chain(seed.institutions.iter().map(|item| item.id.as_str())) - .chain(seed.gestalts.iter().map(|item| item.id.as_str())), - )?; - require_unique_ids( - "actor or gestalt member", - std::iter::once(seed.player.id.as_str()) - .chain(seed.actors.iter().map(|item| item.id.as_str())) - .chain(seed.gestalt_members.iter().map(|item| item.id.as_str())), - )?; - let id = Uuid::new_v4(); - let player_id = seed.player.id.clone(); - let now = Utc::now(); - let mut actors: BTreeMap<_, _> = seed - .actors - .into_iter() - .map(|actor| { - let actor = actor.into_actor()?; - Ok((actor.id.clone(), actor)) - }) - .collect::>()?; - if actors - .insert(player_id.clone(), seed.player.into_actor()?) - .is_some() - { - return Err(anyhow!("player id duplicates an NPC")); - } - let locations = seed - .locations - .into_iter() - .map(|location| { - let location = location.into_location()?; - Ok((location.id.clone(), location)) - }) - .collect::>()?; - let gestalt_members = seed - .gestalt_members - .into_iter() - .map(|member| { - let member = member.into_member()?; - Ok((member.id.clone(), member)) - }) - .collect::>()?; - let evidence_receipt_ids = receipt_ids(receipts); - let valid_evidence_receipt_ids = evidence_receipt_ids - .iter() - .cloned() - .collect::>(); - let affected_sources: Vec = receipts - .iter() - .flat_map(|r| r.witnesses.iter().map(|w| w.source_id.clone())) - .collect::>() - .into_iter() - .collect(); - let canon_candidates = seed - .gaps - .iter() - .enumerate() - .map(|(index, gap)| { - let gap_text = material_gap_text(gap); - let candidate = crate::domain::CanonCandidate { - schema: "ghostlight.canon_candidate.v1".into(), - id: format!("canon-candidate:{}:{}", id, index + 1), - originating_campaign_id: id, - gap: gap_text.clone(), - evidence_receipt_ids: gap.evidence_receipt_ids.clone(), - conflicts: vec![], - proposed_wording: format!("Clarify the documented answer to: {gap_text}"), - affected_vault_sources: affected_sources.clone(), - status: "review".into(), - }; - (candidate.id.clone(), candidate) - }) - .collect(); - let mut campaign = Campaign { - schema: "ghostlight.campaign.v1".into(), - id, - name: seed.title, - revision: 0, - branch_origin: BranchOrigin { - canon_cutoff: seed.canon_cutoff, - evidence_receipt_ids, - }, - world_time: seed.world_time, - tick_hours: seed.tick_hours, - player_actor_id: player_id, - locations, - actors, - institutions: seed - .institutions - .into_iter() - .map(|x| (x.id.clone(), x)) - .collect(), - clocks: seed.clocks.into_iter().map(|x| (x.id.clone(), x)).collect(), - facts: seed - .facts - .into_iter() - .map(|mut x| { - let supplied_reference_count = x.evidence_receipt_ids.len(); - x.evidence_receipt_ids - .retain(|id| valid_evidence_receipt_ids.contains(id)); - if x.scope == FactScope::CanonBaseline - && (supplied_reference_count == 0 - || x.evidence_receipt_ids.len() != supplied_reference_count) - { - x.scope = FactScope::ProvisionalLocal; - }; - (x.id.clone(), x) - }) - .collect(), - civic_systems: BTreeMap::new(), - transcript: vec![crate::domain::NarrativeTurn { - revision: 0, - at: now, - speaker: "world".into(), - text: seed.opening_narration, - persona_response_actor_ids: BTreeSet::new(), - }], - last_player_activity: now, - pending_ticks: 0, - away_ticks_processed: 0, - events: vec![], - news: vec![], - canon_candidates, - gestalts: seed - .gestalts - .into_iter() - .map(|x| (x.id.clone(), x)) - .collect(), - gestalt_members, - pending_world_proposals: vec![], - agency_profiles: BTreeMap::new(), - agency_relations: BTreeMap::new(), - gestalt_lineages: BTreeMap::new(), - resolution_policy: Default::default(), - resolution_pins: BTreeMap::new(), - resolution_cover: None, - nemesis_attention_history: Vec::new(), - strategic_tick_count: 0, - }; - crate::resolution::ensure_agency_profiles(&mut campaign); - Ok(campaign) -} - -fn compiled_seed_structure(seed: &CompiledSeed) -> serde_json::Value { - serde_json::json!({ - "tick_hours": seed.tick_hours, - "player": {"id": seed.player.id, "location_id": seed.player.location_id}, - "locations": seed.locations.iter().map(|location| serde_json::json!({ - "id": location.id, - "container_id": location.container_id, - "routes": location.routes, - })).collect::>(), - "actors": seed.actors.iter().map(|actor| serde_json::json!({ - "id": actor.id, - "location_id": actor.location_id, - })).collect::>(), - "institution_ids": seed.institutions.iter().map(|institution| institution.id.as_str()).collect::>(), - "gestalts": seed.gestalts.iter().map(|gestalt| serde_json::json!({ - "id": gestalt.id, - "home_location_id": gestalt.home_location_id, - })).collect::>(), - "gestalt_members": seed.gestalt_members.iter().map(|member| serde_json::json!({ - "id": member.id, - "gestalt_id": member.gestalt_id, - "materialized_actor_id": member.materialized_actor_id, - })).collect::>(), - "clocks": seed.clocks.iter().map(|clock| serde_json::json!({ - "id": clock.id, - "progress": clock.progress, - "threshold": clock.threshold, - "consequence_scope": clock.consequence_scope, - })).collect::>(), - "fact_ids": seed.facts.iter().map(|fact| fact.id.as_str()).collect::>(), - }) -} - -fn require_unique_ids<'a>(label: &str, ids: impl IntoIterator) -> Result<()> { - let mut seen = BTreeSet::new(); - let mut duplicates = BTreeSet::new(); - for id in ids { - if id.trim().is_empty() || !seen.insert(id.to_owned()) { - duplicates.insert(id.to_owned()); - } - } - if duplicates.is_empty() { - Ok(()) - } else { - Err(anyhow!( - "{label} IDs must be non-empty and unique; rejected IDs={duplicates:?}" - )) - } -} - -fn agency_subject_briefs( - campaign: &Campaign, - excluded_subject_ids: &BTreeSet, -) -> Vec { - let mut briefs = Vec::new(); - for actor in campaign.actors.values().filter(|actor| { - actor.id != campaign.player_actor_id && !excluded_subject_ids.contains(&actor.id) - }) { - briefs.push(AgencySubjectBrief { - subject_id: actor.id.clone(), - subject_kind: AgencySubjectKind::Actor, - name: actor.name.clone(), - location_ids: BTreeSet::from([actor.location_id.clone()]), - capabilities_or_resources: actor - .capabilities - .iter() - .chain(actor.equipment.iter()) - .cloned() - .collect(), - knowledge_or_posture: actor.knowledge.iter().cloned().collect(), - goals: actor.goals.clone(), - pressures_or_obligations: actor - .obligations - .iter() - .chain(actor.conditions.iter()) - .cloned() - .collect(), - }); - } - for institution in campaign - .institutions - .values() - .filter(|institution| !excluded_subject_ids.contains(&institution.id)) - { - briefs.push(AgencySubjectBrief { - subject_id: institution.id.clone(), - subject_kind: AgencySubjectKind::Institution, - name: institution.name.clone(), - location_ids: BTreeSet::new(), - capabilities_or_resources: institution.resources.clone(), - knowledge_or_posture: vec![institution.posture.clone()], - goals: institution.goals.clone(), - pressures_or_obligations: Vec::new(), - }); - } - for gestalt in campaign - .gestalts - .values() - .filter(|gestalt| !excluded_subject_ids.contains(&gestalt.id)) - { - briefs.push(AgencySubjectBrief { - subject_id: gestalt.id.clone(), - subject_kind: AgencySubjectKind::Gestalt, - name: gestalt.name.clone(), - location_ids: BTreeSet::from([gestalt.home_location_id.clone()]), - capabilities_or_resources: gestalt - .shared_capabilities - .iter() - .chain(gestalt.resources.iter()) - .cloned() - .collect(), - knowledge_or_posture: gestalt.shared_knowledge.iter().cloned().collect(), - goals: gestalt.goals.clone(), - pressures_or_obligations: gestalt.pressures.clone(), - }); - } - briefs.sort_by(|left, right| left.subject_id.cmp(&right.subject_id)); - briefs -} - -fn apply_compiled_agency_skeleton( - campaign: &mut Campaign, - expected: &BTreeSet, - profiles: Vec, - relations: Vec, -) -> Result<()> { - if expected.is_empty() && profiles.is_empty() && relations.is_empty() { - return Ok(()); - } - let supplied: BTreeSet<_> = profiles - .iter() - .map(|profile| profile.subject_id.clone()) - .collect(); - let axes = BTreeSet::from([ - AgencyAxis::Geography, - AgencyAxis::Ideology, - AgencyAxis::Authority, - AgencyAxis::EconomyRole, - AgencyAxis::SpeciesBody, - AgencyAxis::Information, - ]); - if &supplied != expected || supplied.len() != profiles.len() { - let missing = expected.difference(&supplied).cloned().collect::>(); - let unexpected = supplied.difference(expected).cloned().collect::>(); - let duplicate_count = profiles.len().saturating_sub(supplied.len()); - return Err(anyhow!( - "global agency skeleton coverage mismatch: missing={missing:?}; unexpected={unexpected:?}; duplicate_profile_count={duplicate_count}; expected_subject_ids={:?}", - expected - )); - } - for input in profiles { - let authority_known = input - .collective_authority_id - .as_ref() - .is_none_or(|id| expected.contains(id)); - let profile = campaign - .agency_profiles - .get_mut(&input.subject_id) - .ok_or_else(|| anyhow!("agency profile references an unknown subject"))?; - let input_facets = input.facets.into_map(); - let input_axes: BTreeSet<_> = input_facets.keys().cloned().collect(); - let unknown_locations = input - .location_ids - .iter() - .filter(|id| !campaign.locations.contains_key(*id)) - .cloned() - .collect::>(); - let knowledge_channel_overlap = match input.subject_kind { - AgencySubjectKind::Actor => campaign - .actors - .get(&input.subject_id) - .map(|actor| { - input - .information_channels - .intersection(&actor.knowledge) - .cloned() - .collect::>() - }) - .unwrap_or_default(), - AgencySubjectKind::Gestalt => campaign - .gestalts - .get(&input.subject_id) - .map(|gestalt| { - input - .information_channels - .intersection(&gestalt.shared_knowledge) - .cloned() - .collect::>() - }) - .unwrap_or_default(), - AgencySubjectKind::Institution => Vec::new(), - }; - let invalid_information_channels = input - .information_channels - .iter() - .filter(|channel| !crate::resolution::information_channel_is_concrete(channel)) - .cloned() - .collect::>(); - if profile.subject_kind != input.subject_kind - || input_axes != axes - || input.location_ids != profile.location_ids - || !unknown_locations.is_empty() - || !authority_known - || !knowledge_channel_overlap.is_empty() - || !invalid_information_channels.is_empty() - { - let missing_axes = axes.difference(&input_axes).cloned().collect::>(); - let unexpected_axes = input_axes.difference(&axes).cloned().collect::>(); - return Err(anyhow!( - "agency profile {} malformed: expected_kind={:?}; supplied_kind={:?}; expected_location_ids={:?}; supplied_location_ids={:?}; missing_axes={missing_axes:?}; unexpected_axes={unexpected_axes:?}; unknown_locations={unknown_locations:?}; unknown_collective_authority={:?}; knowledge_channel_overlap={knowledge_channel_overlap:?}; invalid_information_channels={invalid_information_channels:?}", - input.subject_id, - profile.subject_kind, - input.subject_kind, - profile.location_ids, - input.location_ids, - input.collective_authority_id.filter(|_| !authority_known) - )); - } - profile.collective_authority_id = input.collective_authority_id; - profile.facets = input_facets; - profile.location_ids = input.location_ids; - profile.information_channels = input.information_channels; - profile.evidence_receipt_ids = campaign.branch_origin.evidence_receipt_ids.clone(); - } - let mut relation_ids = BTreeSet::new(); - for input in relations { - let duplicate_id = !relation_ids.insert(input.id.clone()); - let empty_id = input.id.trim().is_empty(); - let self_edge = input.from_subject_id == input.to_subject_id; - let unknown_from = !expected.contains(&input.from_subject_id); - let unknown_to = !expected.contains(&input.to_subject_id); - let invalid_strength = input.strength == 0 || input.strength > 100; - if duplicate_id || empty_id || self_edge || unknown_from || unknown_to || invalid_strength { - return Err(anyhow!( - "agency relation {:?} malformed: duplicate_id={duplicate_id}; empty_id={empty_id}; self_edge={self_edge}; unknown_from_subject={unknown_from} ({:?}); unknown_to_subject={unknown_to} ({:?}); invalid_strength={invalid_strength} ({}) ; supplied_subject_ids={:?}", - input.id, - input.from_subject_id, - input.to_subject_id, - input.strength, - expected - )); - } - campaign.agency_relations.insert( - input.id.clone(), - AgencyRelation { - schema: AgencyRelation::SCHEMA.into(), - id: input.id, - from_subject_id: input.from_subject_id, - to_subject_id: input.to_subject_id, - kind: input.kind, - strength: input.strength, - active: true, - evidence_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), - }, - ); - } - Ok(()) -} - -pub fn validate_campaign_seed(c: &Campaign) -> Result<()> { - validate_campaign(c, true) -} - -pub fn validate_campaign_runtime(c: &Campaign) -> Result<()> { - validate_campaign(c, false) -} - -fn validate_campaign_public_identity_names(campaign: &Campaign) -> Result<()> { - let mut projected_member_actor_ids = BTreeSet::new(); - for member in campaign.gestalt_members.values() { - let default_actor_id = crate::domain::gestalt_member_subject_id(&member.id); - if campaign.actors.contains_key(&default_actor_id) { - projected_member_actor_ids.insert(default_actor_id); - } - if let Some(actor_id) = &member.materialized_actor_id { - projected_member_actor_ids.insert(actor_id.clone()); - if let Some(actor) = campaign.actors.get(actor_id) - && crate::resolution::public_identity_key(&actor.name) - != crate::resolution::public_identity_key(&member.name) - { - return Err(anyhow!( - "materialized member {} and Actor {} disagree on public identity", - member.id, - actor.id - )); - } - } - } - - let mut person_names = BTreeMap::::new(); - let person_identities = campaign - .actors - .values() - .filter(|actor| !projected_member_actor_ids.contains(&actor.id)) - .map(|actor| (format!("actor:{}", actor.id), actor.name.as_str())) - .chain( - campaign - .gestalt_members - .values() - .map(|member| (format!("member:{}", member.id), member.name.as_str())), - ); - for (subject_id, name) in person_identities { - let key = crate::resolution::public_identity_key(name); - if key.is_empty() { - return Err(anyhow!( - "public person identity {subject_id} has no identity characters" - )); - } - if let Some(existing) = person_names.insert(key, subject_id.clone()) { - return Err(anyhow!( - "public person identities {existing} and {subject_id} collide" - )); - } - } - - let mut population_names = BTreeMap::::new(); - let residual_population_ids = crate::elaboration::residual_gestalt_ids(campaign); - for population in campaign - .gestalts - .values() - .filter(|population| !residual_population_ids.contains(&population.id)) - { - let key = crate::resolution::public_identity_key(&population.name); - if key.is_empty() { - return Err(anyhow!( - "public population identity {} has no identity characters", - population.id - )); - } - if let Some(existing) = population_names.insert(key, population.id.clone()) { - return Err(anyhow!( - "public population identities {existing} and {} collide", - population.id - )); - } - } - Ok(()) -} - -fn validate_campaign(c: &Campaign, fresh_seed: bool) -> Result<()> { - if c.tick_hours == 0 { - return Err(anyhow!("strategic tick duration must be positive")); - } - if !c.actors.contains_key(&c.player_actor_id) - && !c.institutions.contains_key(&c.player_actor_id) - && !c.gestalts.contains_key(&c.player_actor_id) - { - return Err(anyhow!("primary controlled subject is missing")); - } - validate_campaign_public_identity_names(c)?; - crate::resolution::validate_policy(&c.resolution_policy)?; - crate::resolution::validate_pins(c, &c.resolution_pins)?; - if let Some(institution) = c.institutions.values().find(|institution| { - institution.posture.trim().is_empty() - || institution.posture.chars().count() > MAX_POSTURE_CHARS - }) { - return Err(anyhow!( - "institution {} posture must contain one to {MAX_POSTURE_CHARS} characters", - institution.id - )); - } - let canonical_subjects = c - .actors - .keys() - .map(|id| (id, AgencySubjectKind::Actor)) - .chain( - c.institutions - .keys() - .map(|id| (id, AgencySubjectKind::Institution)), - ) - .chain(c.gestalts.keys().map(|id| (id, AgencySubjectKind::Gestalt))); - for (subject_id, expected_kind) in canonical_subjects { - let Some(profile) = c.agency_profiles.get(subject_id) else { - return Err(anyhow!( - "campaign agency skeleton has incomplete subject coverage: {subject_id}" - )); - }; - if profile.subject_id != *subject_id || profile.subject_kind != expected_kind { - return Err(anyhow!( - "campaign agency profile does not match canonical subject {subject_id}" - )); - } - if let Some(channel) = profile - .information_channels - .iter() - .find(|channel| !crate::resolution::information_channel_is_concrete(channel)) - { - return Err(anyhow!( - "campaign agency profile {subject_id} has an invalid information channel {channel:?}" - )); - } - let knowledge_overlap = match expected_kind { - AgencySubjectKind::Actor => c.actors.get(subject_id).and_then(|actor| { - profile - .information_channels - .intersection(&actor.knowledge) - .next() - }), - AgencySubjectKind::Gestalt => c.gestalts.get(subject_id).and_then(|gestalt| { - profile - .information_channels - .intersection(&gestalt.shared_knowledge) - .next() - }), - AgencySubjectKind::Institution => None, - }; - if let Some(channel) = knowledge_overlap { - return Err(anyhow!( - "campaign agency profile {subject_id} cannot use factual knowledge {channel:?} as an information channel" - )); - } - } - if let Some(profile) = c.agency_profiles.values().find(|profile| { - profile.active_leaf - && profile.simulation_eligible - && !c.actors.contains_key(&profile.subject_id) - && !c.institutions.contains_key(&profile.subject_id) - && !c.gestalts.contains_key(&profile.subject_id) - }) { - return Err(anyhow!( - "active agency profile refers to unknown canonical subject {}", - profile.subject_id - )); - } - let relationship_targets = canonical_relationship_subject_ids(c); - for actor in c.actors.values() { - if !c.locations.contains_key(&actor.location_id) { - return Err(anyhow!( - "actor {} occupies unknown location {}", - actor.id, - actor.location_id - )); - } - let invalid_relationships = actor - .relationships - .iter() - .filter(|(target_id, description)| { - !relationship_targets.contains(*target_id) || description.trim().is_empty() - }) - .map(|(target_id, _)| format!("{}->{target_id}", actor.id)) - .collect::>(); - if !invalid_relationships.is_empty() { - return Err(anyhow!( - "actor relationships must use exact declared actor, institution, gestalt, or named-member subject IDs with non-empty descriptions; rejected relationships={invalid_relationships:?}; valid target IDs={relationship_targets:?}" - )); - } - } - for gestalt in c.gestalts.values() { - if !c.locations.contains_key(&gestalt.home_location_id) { - return Err(anyhow!( - "gestalt {} occupies unknown home location {}", - gestalt.id, - gestalt.home_location_id - )); - } - } - for (member_key, member) in &c.gestalt_members { - if member_key != &member.id - || member.id.is_empty() - || crate::domain::canonical_gestalt_member_local_id(&member.id) != member.id - { - return Err(anyhow!( - "gestalt member {} must use one canonical local ID without a member: prefix", - member.id - )); - } - if !c.gestalts.contains_key(&member.gestalt_id) { - return Err(anyhow!( - "gestalt member {} references unknown gestalt {}", - member.id, - member.gestalt_id - )); - } - if fresh_seed && member.materialized_actor_id.is_some() { - return Err(anyhow!( - "compiled gestalt member {} must begin dematerialized", - member.id - )); - } - } - for location in c.locations.values() { - if let Some(parent) = &location.container_id - && (parent == &location.id || !c.locations.contains_key(parent)) - { - return Err(anyhow!( - "location {} has invalid container_id {:?}; it must name a different supplied location or be null", - location.id, - location.container_id - )); - } - for (route_id, route) in &location.routes { - if route.travel_minutes == 0 { - return Err(anyhow!( - "location {} route {} to {} has zero travel_minutes", - location.id, - route_id, - route.destination_id - )); - } - if !c.locations.contains_key(&route.destination_id) { - return Err(anyhow!( - "location {} route {} references missing destination_id {}; supplied location IDs={:?}", - location.id, - route_id, - route.destination_id, - c.locations.keys().collect::>() - )); - } - } - } - let mut fact_statements = BTreeSet::new(); - for fact in c.facts.values() { - if fact.statement.trim().is_empty() || !fact_statements.insert(fact.statement.clone()) { - return Err(anyhow!( - "world facts must have non-empty unique statements; rejected fact {}", - fact.id - )); - } - let invalid_locations = fact - .discoverable_at_location_ids - .iter() - .filter(|id| !c.locations.contains_key(*id)) - .cloned() - .collect::>(); - if !invalid_locations.is_empty() { - return Err(anyhow!( - "fact {} is discoverable at unknown locations {:?}; valid location IDs={:?}", - fact.id, - invalid_locations, - c.locations.keys().collect::>() - )); - } - } - for clock in c.clocks.values() { - if clock.threshold == 0 - || clock.progress > clock.threshold - || (fresh_seed && clock.progress >= clock.threshold) - { - return Err(anyhow!("clock {} is invalid", clock.id)); - } - if clock.consequence_scope.is_unbound() { - if fresh_seed { - return Err(anyhow!("new clock {} has no consequence scope", clock.id)); - } - } else { - crate::clock::validate_clock_consequence_scope(c, &clock.consequence_scope)?; - } - } - validate_campaign_civic_systems(c)?; - Ok(()) -} - -fn validate_campaign_civic_systems(campaign: &Campaign) -> Result<()> { - for (jurisdiction_id, system) in &campaign.civic_systems { - let public_fact_ids = system - .public_authority_fact_ids - .iter() - .chain(system.public_selection_fact_ids.iter()) - .chain(system.public_resource_fact_ids.iter()) - .chain(system.public_redress_fact_ids.iter()) - .collect::>(); - if system.schema != "ghostlight.civic_system_manifest.v1" - || system.jurisdiction_location_id != *jurisdiction_id - || !campaign.locations.contains_key(jurisdiction_id) - || system.semantic_verification_receipt_id.trim().is_empty() - || system.governing_institution_ids.len() < 2 - || system - .governing_institution_ids - .iter() - .any(|id| !campaign.institutions.contains_key(id)) - || system.resident_population_ids.is_empty() - || system - .resident_population_ids - .iter() - .any(|id| !campaign.gestalts.contains_key(id)) - || system.public_authority_fact_ids.is_empty() - || system.public_selection_fact_ids.is_empty() - || system.public_resource_fact_ids.is_empty() - || system.public_redress_fact_ids.is_empty() - || public_fact_ids - .iter() - .any(|id| !campaign.facts.contains_key(*id)) - || system.political_relation_ids.is_empty() - || system.political_relation_ids.iter().any(|id| { - !campaign - .agency_relations - .get(id) - .is_some_and(|edge| edge.active) - }) - { - return Err(anyhow!( - "campaign civic system for {jurisdiction_id} has broken canonical references" - )); - } - for resident_id in &system.resident_population_ids { - let resident = &campaign.gestalts[resident_id]; - if public_fact_ids.iter().any(|fact_id| { - !resident - .shared_knowledge - .contains(&campaign.facts[*fact_id].statement) - }) { - return Err(anyhow!( - "campaign civic resident {resident_id} lost a public civic fact" - )); - } - } - } - Ok(()) -} - -fn validate_opening_playability(campaign: &Campaign) -> Result<()> { - validate_opening_topology(campaign)?; - let player_location = &campaign.actors[&campaign.player_actor_id].location_id; - if campaign.facts.values().any(|fact| { - fact.scope != FactScope::CanonBaseline - && fact.discoverable_at_location_ids.contains(player_location) - }) { - Ok(()) - } else { - Err(anyhow!( - "the opening location must contain at least one branch_local or provisional_local discoverable fact; player location={player_location}" - )) - } -} - -fn validate_opening_topology(campaign: &Campaign) -> Result<()> { - if campaign.locations.len() <= 1 { - return Ok(()); - } - let player_location = campaign.actors[&campaign.player_actor_id] - .location_id - .as_str(); - let reachable = |start: &str, reverse: bool| { - let mut visited = BTreeSet::new(); - let mut pending = vec![start.to_owned()]; - while let Some(current) = pending.pop() { - if !visited.insert(current.clone()) { - continue; - } - if reverse { - for (origin_id, location) in &campaign.locations { - if location - .routes - .values() - .any(|route| route.destination_id == current) - { - pending.push(origin_id.clone()); - } - } - } else if let Some(location) = campaign.locations.get(¤t) { - pending.extend( - location - .routes - .values() - .map(|route| route.destination_id.clone()), - ); - } - } - visited - }; - let outward = reachable(player_location, false); - let unreachable = campaign - .locations - .keys() - .filter(|id| !outward.contains(*id)) - .cloned() - .collect::>(); - if !unreachable.is_empty() { - return Err(anyhow!( - "opening topology has locations unreachable from player location {player_location}: {unreachable:?}; containment does not create implicit movement" - )); - } - let returning = reachable(player_location, true); - let trapping = campaign - .locations - .keys() - .filter(|id| !returning.contains(*id)) - .cloned() - .collect::>(); - if !trapping.is_empty() { - return Err(anyhow!( - "opening topology has locations with no route chain back to player location {player_location}: {trapping:?}" - )); - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn civic_verifier_projects_exact_fact_ids_from_canonical_gestalt_knowledge() { - let population = crate::domain::GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "verge-residents".into(), - name: "Verge residents".into(), - version: 0, - home_location_id: "verge".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::from([ - "The Verge Moot holds current authority.".into(), - "Petitions receive a witnessed hearing.".into(), - ]), - resources: BTreeSet::new(), - goals: vec!["keep civic answers public".into()], - pressures: vec![], - }; - let facts = [ - crate::domain::WorldFact { - id: "fact:authority".into(), - statement: "The Verge Moot holds current authority.".into(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["verge".into()]), - }, - crate::domain::WorldFact { - id: "fact:redress".into(), - statement: "Petitions receive a witnessed hearing.".into(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["verge".into()]), - }, - crate::domain::WorldFact { - id: "fact:private".into(), - statement: "The clerk hides a second ledger.".into(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["verge".into()]), - }, - ]; - - let projection = WorldCompiler::civic_resident_fact_projection(&population, facts.iter()); - - assert_eq!( - projection["shared_fact_ids"], - serde_json::json!(["fact:authority", "fact:redress"]) - ); - assert!(projection.get("shared_knowledge").is_none()); - } - - #[test] - fn civic_context_includes_non_governing_institution_relation_endpoints() { - let mut campaign = harrow_campaign(); - for (id, name) in [ - ("harrow-assembly", "Harrow Assembly"), - ("harrow-gauge-commission", "Harrow Gauge Commission"), - ] { - campaign.institutions.insert( - id.into(), - crate::domain::InstitutionState { - id: id.into(), - name: name.into(), - resources: vec!["public records".into()], - goals: vec!["govern the station".into()], - posture: "openly disputing the current works schedule".into(), - }, - ); - } - campaign.agency_relations.insert( - "relation:commission-assembly".into(), - crate::domain::AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "relation:commission-assembly".into(), - from_subject_id: "harrow-gauge-commission".into(), - to_subject_id: "harrow-assembly".into(), - kind: AgencyRelationKind::Rivalry, - strength: 72, - active: true, - evidence_receipt_ids: vec![], - }, - ); - campaign.civic_systems.insert( - "loc:harrow_station".into(), - CivicSystemManifest { - schema: "ghostlight.civic_system_manifest.v1".into(), - version: 0, - jurisdiction_location_id: "loc:harrow_station".into(), - governing_institution_ids: BTreeSet::from(["harrow-assembly".into()]), - resident_population_ids: BTreeSet::new(), - public_authority_fact_ids: BTreeSet::new(), - public_selection_fact_ids: BTreeSet::new(), - public_resource_fact_ids: BTreeSet::new(), - public_redress_fact_ids: BTreeSet::new(), - political_relation_ids: BTreeSet::from(["relation:commission-assembly".into()]), - semantic_verification_receipt_id: "receipt:test".into(), - }, - ); - - let context = civic_context(&campaign, "loc:harrow_station").unwrap(); - let governing_institution_ids = context["institutions"] - .as_array() - .unwrap() - .iter() - .map(|institution| institution["id"].as_str().unwrap()) - .collect::>(); - let related_institution_ids = context["related_institutions"] - .as_array() - .unwrap() - .iter() - .map(|institution| institution["id"].as_str().unwrap()) - .collect::>(); - - assert_eq!( - governing_institution_ids, - BTreeSet::from(["harrow-assembly"]) - ); - assert_eq!( - related_institution_ids, - BTreeSet::from(["harrow-gauge-commission"]) - ); - } - - #[test] - fn destination_generation_location_context_keeps_the_namespace_and_full_anchor_only() { - let mut campaign = harrow_campaign(); - campaign.locations.insert( - "loc:anchor".into(), - Location { - id: "loc:anchor".into(), - name: "Confluence".into(), - container_id: None, - routes: BTreeMap::from([( - "route:anchor-out".into(), - Route { - destination_id: "loc:remote".into(), - distance: "one witnessed crossing".into(), - travel_minutes: 17, - }, - )]), - persistent_features: vec!["FULL_ANCHOR_FEATURE".into()], - }, - ); - campaign.locations.insert( - "loc:remote".into(), - Location { - id: "loc:remote".into(), - name: "Remote Borough".into(), - container_id: Some("loc:anchor".into()), - routes: BTreeMap::from([( - "REMOTE_ROUTE_PAYLOAD".into(), - Route { - destination_id: "loc:anchor".into(), - distance: "REMOTE_DISTANCE_PAYLOAD".into(), - travel_minutes: 19, - }, - )]), - persistent_features: vec!["REMOTE_FEATURE_PAYLOAD".into()], - }, - ); - - let context = destination_location_generation_context(&campaign, "loc:anchor"); - let serialized = serde_json::to_string(&context).unwrap(); - let indexed_ids = context["location_index"] - .as_array() - .unwrap() - .iter() - .map(|location| location["id"].as_str().unwrap()) - .collect::>(); - - assert_eq!( - indexed_ids, - campaign.locations.keys().map(String::as_str).collect() - ); - assert_eq!(context["expansion_anchor"]["id"], "loc:anchor"); - assert!(serialized.contains("FULL_ANCHOR_FEATURE")); - assert!(serialized.contains("route:anchor-out")); - assert!(!serialized.contains("REMOTE_FEATURE_PAYLOAD")); - assert!(!serialized.contains("REMOTE_ROUTE_PAYLOAD")); - assert!(!serialized.contains("REMOTE_DISTANCE_PAYLOAD")); - } - - #[test] - fn peer_civic_generation_context_is_complete_bounded_and_deterministic() { - let mut campaign = harrow_campaign(); - for ordinal in (0..9).rev() { - let jurisdiction_id = format!("loc:peer-{ordinal:02}"); - campaign.locations.insert( - jurisdiction_id.clone(), - Location { - id: jurisdiction_id.clone(), - name: format!("Peer {ordinal:02}"), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec!["REMOTE_CIVIC_LOCATION_PAYLOAD".into()], - }, - ); - campaign.civic_systems.insert( - jurisdiction_id.clone(), - CivicSystemManifest { - schema: "ghostlight.civic_system_manifest.v1".into(), - version: 0, - jurisdiction_location_id: jurisdiction_id, - governing_institution_ids: BTreeSet::new(), - resident_population_ids: BTreeSet::new(), - public_authority_fact_ids: BTreeSet::new(), - public_selection_fact_ids: BTreeSet::new(), - public_resource_fact_ids: BTreeSet::new(), - public_redress_fact_ids: BTreeSet::new(), - political_relation_ids: BTreeSet::new(), - semantic_verification_receipt_id: "REMOTE_VERIFIER_RECEIPT".into(), - }, - ); - } - let jurisdiction_id = "loc:peer-00"; - campaign.institutions.insert( - "peer-store".into(), - InstitutionState { - id: "peer-store".into(), - name: "Common Store".into(), - resources: vec!["grain custody".into()], - goals: vec!["REMOTE_INSTITUTION_GOAL_PAYLOAD".into()], - posture: "releases grain against witnessed need".into(), - }, - ); - campaign.gestalts.insert( - "peer-residents".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "peer-residents".into(), - name: "Floodplain Neighbors".into(), - version: 0, - home_location_id: jurisdiction_id.into(), - shared_capabilities: BTreeSet::from(["REMOTE_CAPABILITY_PAYLOAD".into()]), - shared_knowledge: BTreeSet::from(["REMOTE_KNOWLEDGE_PAYLOAD".into()]), - resources: BTreeSet::from(["REMOTE_POPULATION_RESOURCE_PAYLOAD".into()]), - goals: vec!["keep the floodplain inhabited".into()], - pressures: vec!["the upper sluice is rationed".into()], - }, - ); - for (id, statement) in [ - ("fact:peer-authority", "The flood moot opens the store."), - ("fact:peer-selection", "Lots rotate the flood witnesses."), - ("fact:peer-resources", "A ferry levy fills the store."), - ("fact:peer-redress", "A ward may refuse a disputed release."), - ] { - campaign.facts.insert( - id.into(), - WorldFact { - id: id.into(), - statement: statement.into(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec!["REMOTE_FACT_RECEIPT".into()], - discoverable_at_location_ids: BTreeSet::from([jurisdiction_id.into()]), - }, - ); - } - campaign.agency_relations.insert( - "relation:peer-store-residents".into(), - AgencyRelation { - schema: AgencyRelation::SCHEMA.into(), - id: "relation:peer-store-residents".into(), - from_subject_id: "peer-store".into(), - to_subject_id: "peer-residents".into(), - kind: AgencyRelationKind::Rivalry, - strength: 61, - active: true, - evidence_receipt_ids: vec!["REMOTE_RELATION_RECEIPT".into()], - }, - ); - let system = campaign.civic_systems.get_mut(jurisdiction_id).unwrap(); - system.governing_institution_ids.insert("peer-store".into()); - system - .resident_population_ids - .insert("peer-residents".into()); - system - .public_authority_fact_ids - .insert("fact:peer-authority".into()); - system - .public_selection_fact_ids - .insert("fact:peer-selection".into()); - system - .public_resource_fact_ids - .insert("fact:peer-resources".into()); - system - .public_redress_fact_ids - .insert("fact:peer-redress".into()); - system - .political_relation_ids - .insert("relation:peer-store-residents".into()); - - let context = peer_civic_generation_contexts(&campaign, "loc:not-a-peer"); - let serialized = serde_json::to_string(&context).unwrap(); - let jurisdiction_ids = context - .iter() - .map(|peer| peer["jurisdiction_location_id"].as_str().unwrap()) - .collect::>(); - - assert_eq!(context.len(), 8); - assert_eq!(jurisdiction_ids.first().copied(), Some("loc:peer-00")); - assert_eq!(jurisdiction_ids.last().copied(), Some("loc:peer-07")); - assert!(serialized.contains("Common Store")); - assert!(serialized.contains("grain custody")); - assert!(serialized.contains("Floodplain Neighbors")); - assert!(serialized.contains("keep the floodplain inhabited")); - assert!(serialized.contains("The flood moot opens the store.")); - assert!(serialized.contains("Lots rotate the flood witnesses.")); - assert!(serialized.contains("A ferry levy fills the store.")); - assert!(serialized.contains("A ward may refuse a disputed release.")); - assert!(serialized.contains("redress_or_appeal")); - assert!(serialized.contains("rivalry")); - assert!(serialized.contains("\"strength\":61")); - assert!(!serialized.contains("REMOTE_CIVIC_LOCATION_PAYLOAD")); - assert!(!serialized.contains("REMOTE_VERIFIER_RECEIPT")); - assert!(!serialized.contains("REMOTE_INSTITUTION_GOAL_PAYLOAD")); - assert!(!serialized.contains("REMOTE_KNOWLEDGE_PAYLOAD")); - assert!(!serialized.contains("REMOTE_FACT_RECEIPT")); - assert!(!serialized.contains("REMOTE_RELATION_RECEIPT")); - - let mut reordered = campaign.clone(); - let civic_systems = reordered.civic_systems.into_iter().rev().collect(); - reordered.civic_systems = civic_systems; - assert_eq!( - context, - peer_civic_generation_contexts(&reordered, "loc:not-a-peer") - ); - } - - #[test] - fn compiler_responses_schemas_preserve_dynamic_semantics_as_records() { - let mut schema = serde_json::to_value(schema_for!(CompiledSeed)).unwrap(); - crate::model_connector::project_strict_responses_schema(&mut schema).unwrap(); - - assert_eq!( - schema["$defs"]["CompiledLocation"]["properties"]["routes"]["type"], - "array" - ); - assert_eq!( - schema["$defs"]["CompiledActorState"]["properties"]["relationships"]["type"], - "array" - ); - assert_eq!( - schema["$defs"]["CompiledGestaltMemberDelta"]["properties"]["relationships"]["type"], - "array" - ); - let serialized = serde_json::to_string(&schema).unwrap(); - assert!(serialized.contains("\"route_id\"")); - assert!(serialized.contains("\"subject_id\"")); - assert!(serialized.contains("Autonomous nonplayer actors only")); - assert_eq!(schema["properties"]["player"].as_object().unwrap().len(), 1); - assert!(schema["properties"]["player"].get("$ref").is_some()); - - let mut agency = serde_json::to_value(schema_for!(CompiledAgencySkeleton)).unwrap(); - crate::model_connector::project_strict_responses_schema(&mut agency).unwrap(); - assert_eq!( - agency["$defs"]["CompiledAgencyFacets"]["properties"]["geography"]["type"], - "array" - ); - assert_eq!( - agency["$defs"]["CompiledAgencyFacets"]["properties"]["information"]["type"], - "array" - ); - - let mut expansion = serde_json::to_value(schema_for!(CompiledExpansionSeed)).unwrap(); - crate::model_connector::project_strict_responses_schema(&mut expansion).unwrap(); - assert_eq!(expansion["properties"]["origin_routes"]["type"], "array"); - assert_eq!(expansion["properties"]["locations"]["type"], "array"); - assert_eq!( - expansion["$defs"]["CivicSystemManifestSchemaV1"]["enum"], - serde_json::json!(["ghostlight.civic_system_manifest.v1"]) - ); - let mut civic_reconciliation = - serde_json::to_value(schema_for!(DestinationReconciliationToolAction)).unwrap(); - crate::model_connector::project_strict_responses_schema(&mut civic_reconciliation).unwrap(); - let civic_reconciliation_schema = serde_json::to_string(&civic_reconciliation).unwrap(); - assert!(civic_reconciliation_schema.contains("validate_current")); - assert!(civic_reconciliation_schema.contains("revise_and_validate")); - assert!(!civic_reconciliation_schema.contains("CompiledDestinationReconciliation")); - - let mut fission = serde_json::to_value(schema_for!(CompiledFissionSeed)).unwrap(); - crate::model_connector::project_strict_responses_schema(&mut fission).unwrap(); - assert_eq!( - fission["properties"]["child_partition_values"]["type"], - "array" - ); - assert!( - fission["properties"]["member_child_assignments"]["anyOf"] - .as_array() - .unwrap() - .iter() - .any(|variant| variant["type"] == "array") - ); - assert_eq!( - fission["properties"]["resource_child_assignments"]["type"], - "array" - ); - } - - #[test] - fn compiler_boundary_rejects_duplicate_route_and_relationship_ids() { - let location = CompiledLocation { - id: "yard".into(), - name: "Yard".into(), - container_id: None, - routes: vec![ - CompiledRoute { - route_id: "gate".into(), - destination_id: "yard".into(), - distance: "near".into(), - travel_minutes: 1, - }, - CompiledRoute { - route_id: "gate".into(), - destination_id: "yard".into(), - distance: "near".into(), - travel_minutes: 1, - }, - ], - persistent_features: vec![], - }; - assert!(location.into_location().is_err()); - assert!( - compiled_relationship_map(vec![ - CompiledRelationship { - subject_id: "workers".into(), - description: "trusts".into(), - }, - CompiledRelationship { - subject_id: "workers".into(), - description: "owes".into(), - }, - ]) - .is_err() - ); - } - - #[test] - fn party_identity_bound_covers_long_approved_names_without_truncation() { - let name = "N".repeat(144); - let premise = "P".repeat(308); - let identity = format!( - "A cooperative party whose public starting identities are: {name} — {premise}. Private histories, secrets, and individual knowledge are deliberately withheld from world generation." - ); - assert_eq!(identity.chars().count(), 616); - assert!(validate_user_text("player identity", &identity, 500).is_err()); - validate_user_text("player identity", &identity, MAX_PARTY_IDENTITY_CHARS).unwrap(); - assert!( - validate_user_text( - "player identity", - &"x".repeat(MAX_PARTY_IDENTITY_CHARS + 1), - MAX_PARTY_IDENTITY_CHARS, - ) - .is_err() - ); - } - - #[test] - fn agency_compiler_cannot_disguise_private_knowledge_as_a_channel() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - campaign - .actors - .get_mut("player") - .unwrap() - .knowledge - .insert("convoy vulnerabilities".into()); - let facets = BTreeMap::from([ - (AgencyAxis::Geography, BTreeSet::from(["center".into()])), - (AgencyAxis::Ideology, BTreeSet::from(["unknown".into()])), - (AgencyAxis::Authority, BTreeSet::from(["unknown".into()])), - (AgencyAxis::EconomyRole, BTreeSet::from(["unknown".into()])), - (AgencyAxis::SpeciesBody, BTreeSet::from(["unknown".into()])), - ( - AgencyAxis::Information, - BTreeSet::from(["convoy vulnerabilities".into()]), - ), - ]); - let error = apply_compiled_agency_skeleton( - &mut campaign, - &BTreeSet::from(["player".into()]), - vec![CompiledAgencyProfile { - subject_id: "player".into(), - subject_kind: AgencySubjectKind::Actor, - collective_authority_id: None, - facets: facets.clone().into(), - location_ids: BTreeSet::from(["center".into()]), - information_channels: BTreeSet::from(["convoy vulnerabilities".into()]), - }], - vec![], - ) - .unwrap_err(); - assert!(error.to_string().contains("knowledge_channel_overlap")); - - campaign.actors.get_mut("player").unwrap().knowledge.clear(); - let error = apply_compiled_agency_skeleton( - &mut campaign, - &BTreeSet::from(["player".into()]), - vec![CompiledAgencyProfile { - subject_id: "player".into(), - subject_kind: AgencySubjectKind::Actor, - collective_authority_id: None, - facets: facets.into(), - location_ids: BTreeSet::from(["center".into()]), - information_channels: BTreeSet::from(["unknown".into()]), - }], - vec![], - ) - .unwrap_err(); - assert!(error.to_string().contains("invalid_information_channels")); - } - - #[test] - fn user_text_admission_rejects_empty_oversized_and_binary_control_input() { - assert!(validate_user_text("field", "", 8).is_err()); - assert!(validate_user_text("field", " ", 8).is_err()); - assert!(validate_user_text("field", "123456789", 8).is_err()); - assert!(validate_user_text("field", "hello\0world", 20).is_err()); - assert!(validate_user_text("field", "hello\nworld", 20).is_ok()); - } - - #[test] - fn fission_text_is_bounded_before_retrieval_or_inference() { - let mut request = GestaltFissionRequest { - parent_gestalt_id: "population".into(), - partition_axis: AgencyAxis::Geography, - requested_partition_values: vec!["harbor".into(), "inland".into()], - reason: "The population is dispersing along established routes.".into(), - }; - assert!(validate_fission_request(&request).is_ok()); - - request.requested_partition_values = (0..17).map(|index| format!("cut-{index}")).collect(); - assert!(validate_fission_request(&request).is_err()); - request.requested_partition_values = vec!["x".repeat(161)]; - assert!(validate_fission_request(&request).is_err()); - request.requested_partition_values = vec!["Harbor".into(), "harbor".into()]; - assert!(validate_fission_request(&request).is_err()); - request.requested_partition_values = vec!["other/unknown".into()]; - assert!(validate_fission_request(&request).is_err()); - request.requested_partition_values = vec!["harbor".into()]; - request.reason = "x".repeat(501); - assert!(validate_fission_request(&request).is_err()); - } - - use crate::{ - domain::SourceWitness, - model::ModelPort, - session_zero::{CampaignContract, CharacterDraft}, - vault::FixtureVault, - }; - use async_trait::async_trait; - use sha2::Digest; - use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; - - struct CompilerModel { - invalid_route: bool, - } - - struct DestinationElaborationModel { - saw_branch_assumption_boundary: AtomicBool, - saw_balanced_civic_reconciliation: AtomicBool, - civic_verification_calls: AtomicUsize, - civic_verification_rejections: usize, - reconciliation_steals_non_civic_fact: bool, - } - - struct CorrectingCivicReconciliationModel { - delegate: DestinationElaborationModel, - reconciliation_calls: AtomicUsize, - saw_reconciliation_correction: AtomicBool, - } - - struct OversizedQueryModel; - - struct CorrectionAwareCompilerModel { - world_calls: AtomicUsize, - saw_previous_structure: AtomicBool, - } - - struct CorrectionAwareOpeningModel { - opening_calls: AtomicUsize, - saw_exact_correction: AtomicBool, - } - - struct CorrectionAwareRoleModel { - role_calls: AtomicUsize, - saw_exact_correction: AtomicBool, - } - - struct CorrectionAwareDoctrineModel { - synthesis_calls: AtomicUsize, - saw_branch_elaboration_boundary: AtomicBool, - saw_verifier_correction: AtomicBool, - stay_incompatible: bool, - } - - struct PrivateBoundaryCompilerModel { - retrieval_stage_received_approved_contract: AtomicBool, - shared_stage_was_private_free: AtomicBool, - shared_stage_received_operational_playability: AtomicBool, - shared_stage_received_approved_contract: AtomicBool, - evidence_stage_received_approved_contract: AtomicBool, - private_stage_was_minimal: AtomicBool, - } - - struct PlayerOwnershipCompilerModel { - world_calls: AtomicUsize, - saw_player_ownership_boundary: AtomicBool, - saw_exact_collision_correction: AtomicBool, - } - - #[async_trait] - impl ModelPort for PlayerOwnershipCompilerModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - let output = CompilerModel { - invalid_route: false, - } - .run(request) - .await?; - if request.stage != "world_compile" { - return Ok(output); - } - self.saw_player_ownership_boundary.store( - request - .lived_stream - .contains("HUMAN-CONTROLLED PLAYER NAMES") - && request.lived_stream.contains("\"Sable\"") - && request - .lived_stream - .contains("Do not emit them in actors or gestalt_members"), - Ordering::SeqCst, - ); - let call = self.world_calls.fetch_add(1, Ordering::SeqCst); - if call == 0 { - let mut candidate: serde_json::Value = serde_json::from_str(&output)?; - candidate["actors"] = serde_json::json!([{ - "id":"actor_sable", - "name":"Sable", - "location_id":"yard", - "capabilities":[], - "knowledge":[], - "equipment":[], - "conditions":[], - "obligations":[], - "relationships":[], - "goals":[], - "memories":[] - }]); - return Ok(candidate.to_string()); - } - self.saw_exact_collision_correction.store( - request - .lived_stream - .contains("LOCAL VALIDATOR REJECTED THE PREVIOUS CANDIDATE") - && request.lived_stream.contains("actor_sable") - && request - .lived_stream - .contains("owned outside world-cast compilation"), - Ordering::SeqCst, - ); - Ok(output) - } - - fn provider(&self) -> &'static str { - "player-ownership-fixture" - } - } - - #[async_trait] - impl ModelPort for PrivateBoundaryCompilerModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - match request.stage.as_str() { - "custom_retrieval_plan" => { - self.retrieval_stage_received_approved_contract.store( - request.lived_stream.contains("approved_contract") - && request - .lived_stream - .contains("A convoy has reached a strained logistics yard") - && request.lived_stream.contains("canon_horizon") - && request.lived_stream.contains("fixture") - && request.lived_stream.contains( - "synthesize a bounded search query instead of copying an overlong paragraph verbatim", - ), - Ordering::SeqCst, - ); - } - "evidence_relevance" => { - self.evidence_stage_received_approved_contract.store( - request.lived_stream.contains("APPROVED CONTRACT") - && request - .lived_stream - .contains("A convoy has reached a strained logistics yard") - && request.lived_stream.contains("canon_horizon") - && request.lived_stream.contains("fixture"), - Ordering::SeqCst, - ); - } - "world_compile" => { - self.shared_stage_was_private_free.store( - !request.lived_stream.contains("convoy quartermaster") - && !request.lived_stream.contains("relationship-anchor:") - && !request.lived_stream.contains("life-debt") - && !request.lived_stream.contains("SECRET_COOLANT_RECORD") - && !request.lived_stream.contains("PRIVATE_ROUTE_CODE"), - Ordering::SeqCst, - ); - self.shared_stage_received_operational_playability.store( - request - .lived_stream - .contains("PRIVATE OPERATIONAL PLAYABILITY INPUT") - && request.lived_stream.contains("route planning") - && request.lived_stream.contains("keep the convoy supplied") - && request.lived_stream.contains( - "A generic restatement of the overall crisis is not sufficient", - ), - Ordering::SeqCst, - ); - self.shared_stage_received_approved_contract.store( - request - .lived_stream - .contains("APPROVED SESSION ZERO CONTRACT") - && request - .lived_stream - .contains("A convoy has reached a strained logistics yard") - && request.lived_stream.contains("The convoy needs supplies"), - Ordering::SeqCst, - ); - } - "private_relationship_actor_compile" => { - self.private_stage_was_minimal.store( - request.lived_stream.contains("convoy quartermaster") - && !request.lived_stream.contains("relationship-anchor:") - && request.lived_stream.contains("life-debt") - && !request.lived_stream.contains("SECRET_COOLANT_RECORD") - && !request.lived_stream.contains("PRIVATE_ROUTE_CODE"), - Ordering::SeqCst, - ); - return Ok(serde_json::json!({ - "actors":[{ - "name":"convoy quartermaster", - "location_id":"yard", - "capabilities":["convoy logistics"], - "knowledge":["current manifest"], - "equipment":["manifest terminal"], - "conditions":[], - "obligations":["account for the convoy"], - "relationships":[{ - "subject_id":"yard-workers", - "description":"convoy clerk coordinating with the yard workers" - }], - "goals":["supply the convoy"], - "memories":[] - }] - }) - .to_string()); - } - "agency_compile" => { - let roster = request - .lived_stream - .split_once("subject roster:\n") - .and_then(|(_, tail)| tail.split_once("\n\nReturn exactly")) - .map(|(json, _)| json) - .ok_or_else(|| anyhow!("agency prompt lost its exact subject roster"))?; - let briefs: Vec = serde_json::from_str(roster)?; - let profiles = briefs - .into_iter() - .map(|brief| { - let subject_id = brief["subject_id"].clone(); - let subject_kind = brief["subject_kind"].clone(); - serde_json::json!({ - "subject_id":subject_id, - "subject_kind":subject_kind, - "collective_authority_id":if subject_kind == "gestalt" { subject_id } else { serde_json::Value::Null }, - "facets":{ - "geography":["unknown"], - "ideology":["unknown"], - "authority":["unknown"], - "economy_role":["unknown"], - "species_body":["unknown"], - "information":["unknown"] - }, - "location_ids":brief["location_ids"], - "information_channels":[] - }) - }) - .collect::>(); - return Ok(serde_json::json!({ - "agency_profiles":profiles, - "agency_relations":[] - }) - .to_string()); - } - _ => {} - } - CompilerModel { - invalid_route: false, - } - .run(request) - .await - } - - fn provider(&self) -> &'static str { - "private-boundary-fixture" - } - } - - #[async_trait] - impl ModelPort for CorrectionAwareOpeningModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - let output = CompilerModel { - invalid_route: false, - } - .run(request) - .await?; - if request.stage != "world_openings" { - return Ok(output); - } - let call = self.opening_calls.fetch_add(1, Ordering::SeqCst); - if call == 0 { - let mut candidate: serde_json::Value = serde_json::from_str(&output)?; - candidate["openings"][1]["era"] = serde_json::json!("early"); - return Ok(candidate.to_string()); - } - self.saw_exact_correction.store( - request - .lived_stream - .contains("LOCAL VALIDATOR REJECTED THE PREVIOUS OPENINGS") - && request - .lived_stream - .contains("era=\"early\" repeated 2 times") - && request.lived_stream.contains("\"era\":\"early\""), - Ordering::SeqCst, - ); - Ok(output) - } - - fn provider(&self) -> &'static str { - "correction-aware-opening-fixture" - } - } - - #[async_trait] - impl ModelPort for CorrectionAwareRoleModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - let output = CompilerModel { - invalid_route: false, - } - .run(request) - .await?; - if request.stage != "world_roles" { - return Ok(output); - } - let call = self.role_calls.fetch_add(1, Ordering::SeqCst); - if call == 0 { - let mut candidate: serde_json::Value = serde_json::from_str(&output)?; - candidate["roles"][1]["name"] = serde_json::json!("Courier"); - return Ok(candidate.to_string()); - } - self.saw_exact_correction.store( - request - .lived_stream - .contains("LOCAL VALIDATOR REJECTED THE PREVIOUS ROLES") - && request - .lived_stream - .contains("name=\"courier\" repeated 2 times") - && request.lived_stream.contains("\"name\":\"Courier\""), - Ordering::SeqCst, - ); - Ok(output) - } - - fn provider(&self) -> &'static str { - "correction-aware-role-fixture" - } - } - - #[async_trait] - impl ModelPort for CorrectionAwareDoctrineModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - match request.stage.as_str() { - "global_agency_doctrine_synthesis" => { - self.saw_branch_elaboration_boundary.store( - request.lived_stream.contains( - "Compatible elaboration is required and may vary between campaigns", - ), - Ordering::SeqCst, - ); - let call = self.synthesis_calls.fetch_add(1, Ordering::SeqCst); - if call == 0 { - return Ok(serde_json::json!({"institutions":[{ - "name":"Fixture Council", - "strategic_doctrine":"Abandon the shared route and destroy every crossing." - }]}).to_string()); - } - self.saw_verifier_correction.store( - request.lived_stream.contains( - "THE COMPATIBILITY VERIFIER REJECTED THE PREVIOUS BRANCH DOCTRINES", - ) && request.lived_stream.contains("Abandon the shared route") - && request - .lived_stream - .contains("retaining useful compatible branch elaboration"), - Ordering::SeqCst, - ); - let doctrine = if self.stay_incompatible { - "Abandon the shared route and destroy every crossing." - } else { - "Maintain the shared route through rotating repair crews, convoy permits, and temporary rationing during breakdowns." - }; - Ok(serde_json::json!({"institutions":[{ - "name":"Fixture Council", - "strategic_doctrine":doctrine - }]}) - .to_string()) - } - "global_agency_doctrine_verification" => { - let rejected = request.lived_stream.contains("Abandon the shared route"); - Ok(serde_json::json!({"verdicts":[{ - "name":"Fixture Council", - "compatible_with_canon":!rejected, - "rationale":if rejected { - "Abandoning the route contradicts the supplied maintenance anchor." - } else { - "The route remains maintained; operational methods are compatible branch elaboration." - } - }]}) - .to_string()) - } - _ => Err(anyhow!("unexpected doctrine correction stage")), - } - } - - fn provider(&self) -> &'static str { - "correction-aware-doctrine-fixture" - } - } - - #[async_trait] - impl ModelPort for CorrectionAwareCompilerModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - let output = CompilerModel { - invalid_route: false, - } - .run(request) - .await?; - if request.stage != "world_compile" { - return Ok(output); - } - let call = self.world_calls.fetch_add(1, Ordering::SeqCst); - if call == 0 { - let mut candidate: serde_json::Value = serde_json::from_str(&output)?; - candidate["locations"][0]["routes"][0]["destination_id"] = - serde_json::Value::String("missing".into()); - return Ok(candidate.to_string()); - } - self.saw_previous_structure.store( - request - .lived_stream - .contains("PREVIOUS_CANDIDATE_STRUCTURE") - && request - .lived_stream - .contains("\"destination_id\":\"missing\"") - && request.lived_stream.contains("\"id\":\"yard\"") - && request - .lived_stream - .contains("explicit bidirectional spanning route tree") - && request - .lived_stream - .contains("container_id is geometry only"), - Ordering::SeqCst, - ); - Ok(output) - } - - fn provider(&self) -> &'static str { - "correction-aware-compiler-fixture" - } - } - - #[async_trait] - impl ModelPort for DestinationElaborationModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - match request.stage.as_str() { - "destination_identity_resolution" => Ok(serde_json::json!({ - "decision":"new", - "existing_location_id":null, - "rationale":"The request asks for a new storm refuge." - }) - .to_string()), - "destination_retrieval_plan" => Ok(serde_json::json!({ - "queries":["fixture storm refuge","fixture relief route"] - }) - .to_string()), - "destination_compile" => { - let malformed_civic_profile = request - .lived_stream - .contains("malformed civic profile fixture"); - let candidate_fact_collision = request - .lived_stream - .contains("candidate fact collision fixture"); - let civic_system = (!request - .lived_stream - .contains("missing civic manifest fixture")) - .then(|| { - serde_json::json!({ - "schema":"ghostlight.civic_system_manifest.v1", - "jurisdiction_location_id":"refuge", - "governing_institution_ids":[ - "refuge-duty-council", - "refuge-stores-office" - ], - "resident_population_ids":["refuge-wardens"], - "public_authority_fact_ids":["fact:refuge_authority"], - "public_selection_fact_ids":["fact:refuge_selection"], - "public_resource_fact_ids":["fact:refuge_resources"], - "public_redress_fact_ids":["fact:refuge_redress"], - "political_relation_ids":["relation:refuge-council-stores"] - }) - }); - self.saw_branch_assumption_boundary.store( - request - .lived_stream - .contains("Use evidence as canon constraints, not as an exhaustive game map") - && request.lived_stream.contains( - "Never put a compatible elaboration in gaps merely because the Vault is silent", - ) - && request - .lived_stream - .contains("if a detail must not vary, it belongs in the Vault"), - Ordering::SeqCst, - ); - Ok(serde_json::json!({ - "origin_routes":[{ - "route_id":"route:yard_to_refuge", - "destination_id":"refuge", - "distance":"up the marked storm path", - "travel_minutes":15 - }], - "locations":[{ - "id":"refuge", - "name":"Storm Refuge", - "container_id":null, - "routes":[{ - "route_id":"route:refuge_to_yard", - "destination_id":"convoy-staging", - "distance":"down the marked storm path", - "travel_minutes":15 - }], - "persistent_features":["braced roof","witnessed stores ledger"] - }], - "facts":[ - { - "id":"fact:refuge_authority", - "statement":"The refuge duty council currently authorizes admissions and storm closure.", - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["refuge"] - }, - { - "id":"fact:refuge_selection", - "statement":if candidate_fact_collision { - "The refuge duty council currently authorizes admissions and storm closure." - } else { - "Wardens select two duty councillors by witnessed lot after each storm season." - }, - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["refuge"] - }, - { - "id":"fact:refuge_resources", - "statement":"The stores office receives repair boards through disclosed convoy levies.", - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["refuge"] - }, - { - "id":"fact:refuge_redress", - "statement":"A warden may appeal a duty ruling before the next witnessed stores count.", - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["refuge"] - }, - { - "id":"fact:refuge_private_route", - "statement":"A concealed maintenance crawl reaches the closure seal from below.", - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["refuge"] - } - ], - "populations":[{ - "id":"refuge-wardens", - "name":"Refuge wardens", - "home_location_id":"refuge", - "shared_capabilities":["brace ordinary storm damage"], - "shared_fact_ids":["fact:refuge_authority","fact:refuge_selection","fact:refuge_resources","fact:refuge_redress"], - "resources":["repair boards"], - "goals":["keep the refuge usable"], - "pressures":["capacity is finite"], - "collective_authority_id":"refuge-wardens", - "facets":{ - "geography":["storm path"], - "ideology":["preserve consent"], - "authority":["witnessed duty"], - "economy_role":["repair labor"], - "species_body":["mixed households"], - "information":["operating leaf"] - }, - "information_channels":["witnessed operating leaf"] - }], - "institutions":[ - { - "id":"refuge-duty-council", - "name":"Refuge Duty Council", - "resources":["closure seal"], - "goals":["keep admissions within storm capacity"], - "posture":"admit by witnessed capacity ruling", - "location_ids":["refuge"], - "facets":{ - "geography":["storm refuge"], - "ideology":["witnessed duty"], - "authority":["admission rulings"], - "economy_role":["capacity allocation"], - "species_body":["mixed households"], - "information":["public duty leaf"] - }, - "information_channels":if malformed_civic_profile { serde_json::json!(["unknown"]) } else { serde_json::json!(["public duty leaf"]) } - }, - { - "id":"refuge-stores-office", - "name":"Refuge Stores Office", - "resources":["stores ledger"], - "goals":["preserve disclosed emergency stores"], - "posture":"publish every levy and count", - "location_ids":["refuge"], - "facets":{ - "geography":["storm refuge"], - "ideology":["disclosed accounting"], - "authority":["stores custody"], - "economy_role":["repair supply"], - "species_body":["mixed households"], - "information":["witnessed stores count"] - }, - "information_channels":["witnessed stores count"] - } - ], - "local_relations":[{ - "id":"relation:refuge-council-stores", - "from_subject_id":"refuge-duty-council", - "to_subject_id":"refuge-stores-office", - "kind":"command", - "strength":60 - }], - "civic_system":civic_system, - "migration_relations":[], - "branch_assumptions":[ - "The storm-path geometry and witnessed repair procedure are compatible campaign-local elaboration." - ], - "gaps":[] - }) - .to_string()) - } - "destination_reconciliation_agent_action" => { - let reconciliation_schema = request - .output_schema - .as_ref() - .ok_or_else(|| anyhow!("civic reconciliation lost its schema"))?; - let reconciliation_schema_text = serde_json::to_string(reconciliation_schema)?; - assert!( - !reconciliation_schema_text.contains("CompiledDestinationReconciliation") - ); - assert!(reconciliation_schema_text.contains("validate_current")); - assert!(reconciliation_schema_text.contains("revise_and_validate")); - assert!(reconciliation_schema_text.contains("refuge-duty-council")); - assert!(reconciliation_schema_text.contains("refuge-stores-office")); - if request - .lived_stream - .contains("\"kind\":\"civic_verifier_rejection\"") - { - assert!(request.lived_stream.contains("authority_legible")); - assert!( - request - .lived_stream - .contains("selection_or_succession_legible") - ); - assert!(request.lived_stream.contains("public_resources_legible")); - assert!(request.lived_stream.contains("redress_legible")); - assert!( - request - .lived_stream - .contains("institutional_relations_coherent") - ); - assert!(request.lived_stream.contains("resident_answer_grounded")); - } - self.saw_balanced_civic_reconciliation.store( - request.model == MODEL_BALANCED - && request - .lived_stream - .contains("World invention has already happened") - && request.lived_stream.contains("private candidate workbench") - && request.lived_stream.contains("refuge-duty-council") - && request.lived_stream.contains("INITIAL TYPED FINDING"), - Ordering::SeqCst, - ); - let frozen_projection_tail = request - .lived_stream - .split_once("FROZEN DESTINATION PROJECTION AND READ-ONLY NAMESPACE:\n") - .map(|(_, projection)| projection) - .ok_or_else(|| { - anyhow!("civic reconciliation lost its frozen projection") - })?; - let frozen_projection_end = frozen_projection_tail - .find("\n\nTOOL OBSERVATION") - .or_else(|| frozen_projection_tail.find("\n\nAGENT STEP:")) - .ok_or_else(|| anyhow!("civic reconciliation lost its agent step"))?; - let frozen_projection_text = &frozen_projection_tail[..frozen_projection_end]; - let frozen_projection: serde_json::Value = - serde_json::from_str(frozen_projection_text)?; - if self.reconciliation_steals_non_civic_fact { - let mut fact = frozen_projection["candidate_facts"][0].clone(); - fact["id"] = frozen_projection["campaign_fact_namespace"][0]["id"].clone(); - return Ok(serde_json::json!({ - "tool":"revise_and_validate", - "edits":[{ - "edit":"replace_fact", - "fact_index":0, - "fact":fact, - }] - }) - .to_string()); - } - if request - .lived_stream - .contains("non-concrete information channels") - && request.lived_stream.contains("unknown") - { - let institution = &frozen_projection["institutions"][0]; - return Ok(serde_json::json!({ - "tool":"revise_and_validate", - "edits":[{ - "edit":"update_institution", - "update":{ - "institution_id":institution["id"], - "resources":institution["resources"], - "posture":institution["posture"], - "facets":institution["facets"], - "information_channels":["public duty leaf"], - } - }] - }) - .to_string()); - } - if request.lived_stream.contains("duplicate statement") - || request.lived_stream.contains("duplicate_statement") - { - let mut fact = frozen_projection["candidate_facts"][1].clone(); - fact["statement"] = serde_json::json!( - "Wardens select two duty councillors by witnessed lot after each storm season." - ); - return Ok(serde_json::json!({ - "tool":"revise_and_validate", - "edits":[{ - "edit":"replace_fact", - "fact_index":1, - "fact":fact, - }] - }) - .to_string()); - } - Ok(serde_json::json!({"tool":"validate_current"}).to_string()) - } - "destination_civic_verification" => { - let call = self.civic_verification_calls.fetch_add(1, Ordering::SeqCst); - let accepted = call >= self.civic_verification_rejections; - Ok(serde_json::json!({ - "authority_legible":accepted, - "selection_or_succession_legible":accepted, - "public_resources_legible":accepted, - "redress_legible":accepted, - "institutional_relations_coherent":accepted, - "resident_answer_grounded":accepted, - "political_form_distinct_or_deliberately_shared":accepted, - "opposed_interests_have_distinct_means":accepted, - "constituencies_cross_boundaries_or_local_homogeneity_justified":accepted, - "explicit_request_constraints_satisfied":accepted, - "public_names_do_not_repeat_an_overused_template":accepted, - "candidate_text_intact":accepted, - "rationale":if accepted { - "The refuge facts and institutions form a legible civic apparatus grounded in every resident population." - } else { - "The candidate's labels do not form a meaningful civic apparatus." - } - }) - .to_string()) - } - _ => Err(anyhow!("unexpected destination elaboration stage")), - } - } - - fn provider(&self) -> &'static str { - "destination-elaboration-fixture" - } - } - - #[async_trait] - impl ModelPort for CorrectingCivicReconciliationModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - let output = self.delegate.run(request).await?; - if request.stage != "destination_reconciliation_agent_action" { - return Ok(output); - } - - let call = self.reconciliation_calls.fetch_add(1, Ordering::SeqCst); - let frozen_projection_tail = request - .lived_stream - .split_once("FROZEN DESTINATION PROJECTION AND READ-ONLY NAMESPACE:\n") - .map(|(_, projection)| projection) - .ok_or_else(|| anyhow!("civic reconciliation lost its frozen projection"))?; - let frozen_projection_end = frozen_projection_tail - .find("\n\nTOOL OBSERVATION") - .or_else(|| frozen_projection_tail.find("\n\nAGENT STEP:")) - .ok_or_else(|| anyhow!("civic reconciliation lost its agent step"))?; - let frozen_projection: serde_json::Value = - serde_json::from_str(&frozen_projection_tail[..frozen_projection_end])?; - if call == 0 { - let mut reconciliation: serde_json::Value = serde_json::from_str(&output)?; - let mut second_collision = frozen_projection["candidate_facts"][2].clone(); - second_collision["statement"] = - frozen_projection["candidate_facts"][0]["statement"].clone(); - reconciliation["edits"] - .as_array_mut() - .ok_or_else(|| anyhow!("first reconciliation action lost its edit batch"))? - .push(serde_json::json!({ - "edit":"replace_fact", - "fact_index":2, - "fact":second_collision, - })); - Ok(reconciliation.to_string()) - } else { - self.saw_reconciliation_correction.store( - request.lived_stream.contains("fact_namespace_rejection") - && request.lived_stream.contains("duplicate_statement") - && request.lived_stream.contains("fact:refuge_authority") - && request.lived_stream.contains("fact:refuge_resources") - && request.lived_stream.contains("ASSISTANT:"), - Ordering::SeqCst, - ); - Ok(serde_json::json!({ - "tool":"revise_and_validate", - "edits":[{ - "edit":"replace_fact", - "fact_index":2, - "fact":frozen_projection["candidate_facts"][2], - }] - }) - .to_string()) - } - } - - fn provider(&self) -> &'static str { - self.delegate.provider() - } - } - - struct ExistingDestinationModel { - calls: AtomicUsize, - saw_current_civic_context: AtomicBool, - } - - #[async_trait] - impl ModelPort for ExistingDestinationModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.calls.fetch_add(1, Ordering::SeqCst); - match request.stage.as_str() { - "destination_identity_resolution" => { - assert!(request.lived_stream.contains("Harrow Station")); - assert!(request.lived_stream.contains("loc:harrow_station")); - Ok(serde_json::json!({ - "decision":"existing", - "existing_location_id":"loc:harrow_station", - "rationale":"The request's primary destination is the supplied Harrow Station." - }) - .to_string()) - } - "destination_retrieval_plan" => Ok(serde_json::json!({ - "queries":["Harrow Station civic institutions","Harrow Station public offices"] - }) - .to_string()), - "destination_compile" => { - assert!( - request - .lived_stream - .contains("Elaborate it in place. Never emit that location again") - ); - assert!( - request - .lived_stream - .contains("The question selects the missing domain, not its answer") - ); - if !request - .lived_stream - .contains("CURRENT CIVIC APPARATUS:\nnull") - { - self.saw_current_civic_context.store(true, Ordering::SeqCst); - return Ok(serde_json::json!({ - "origin_routes":[{ - "route_id":"route:station_to_audit_chamber", - "destination_id":"loc:harrow_audit_chamber", - "distance":"behind the petitions bench", - "travel_minutes":4 - }], - "locations":[{ - "id":"loc:harrow_audit_chamber", - "name":"Harrow Audit Chamber", - "container_id":"loc:harrow_station", - "routes":[{ - "route_id":"route:audit_chamber_to_station", - "destination_id":"loc:harrow_station", - "distance":"back through the petitions bench", - "travel_minutes":4 - }], - "persistent_features":["sealed berth-dues duplicate ledger"] - }], - "facts":[{ - "id":"fact:harrow_hidden_levy", - "statement":"The audit chamber found that Mayor Selka Vey diverted one season of published berth dues into an unvoted emergency courier fund.", - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["loc:harrow_station","loc:harrow_audit_chamber"] - }], - "populations":[], - "institutions":[{ - "id":"harrow-audit-chamber", - "name":"Harrow Audit Chamber", - "resources":["duplicate berth-dues ledger"], - "goals":["force a public vote on the diverted dues"], - "posture":"prepare contempt findings against the mayoral office", - "location_ids":["loc:harrow_audit_chamber"], - "facets":{ - "geography":["Harrow civic quarter"], - "ideology":["adversarial public accounting"], - "authority":["compulsory civic audit"], - "economy_role":["treasury inspection"], - "species_body":["mixed civil service"], - "information":["open audit findings"] - }, - "information_channels":["open audit findings"] - }], - "local_relations":[{ - "id":"relation:harrow-audit-mayor", - "from_subject_id":"harrow-audit-chamber", - "to_subject_id":"harrow-mayoral-office", - "kind":"rivalry", - "strength":81 - }], - "civic_system":{ - "schema":"ghostlight.civic_system_manifest.v1", - "jurisdiction_location_id":"loc:harrow_station", - "governing_institution_ids":["harrow-mayoral-office","harrow-ward-assembly","harrow-audit-chamber"], - "resident_population_ids":["harrow-residents"], - "public_authority_fact_ids":["fact:harrow_authority"], - "public_selection_fact_ids":["fact:harrow_selection"], - "public_resource_fact_ids":["fact:harrow_resources","fact:harrow_hidden_levy"], - "public_redress_fact_ids":["fact:harrow_redress"], - "political_relation_ids":["relation:harrow-mayor-assembly","relation:harrow-audit-mayor"] - }, - "migration_relations":[], - "branch_assumptions":["The audit chamber and diverted-dues finding are a second bounded campaign-local elaboration of Harrow's persisted civic apparatus."], - "gaps":[] - }) - .to_string()); - } - Ok(serde_json::json!({ - "origin_routes":[{ - "route_id":"route:station_to_civic_quarter", - "destination_id":"loc:harrow_civic_quarter", - "distance":"through the public arcade", - "travel_minutes":6 - }], - "locations":[{ - "id":"loc:harrow_civic_quarter", - "name":"Harrow Civic Quarter", - "container_id":"loc:harrow_station", - "routes":[{ - "route_id":"route:civic_quarter_to_station", - "destination_id":"loc:harrow_station", - "distance":"back through the public arcade", - "travel_minutes":6 - }], - "persistent_features":["ward notice boards","sealed ballot archive"] - }], - "facts":[ - { - "id":"fact:harrow_authority", - "statement":"Mayor Selka Vey currently holds Harrow Station's civic seal while the ward assembly controls appropriations.", - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["loc:harrow_station","loc:harrow_civic_quarter"] - }, - { - "id":"fact:harrow_selection", - "statement":"Harrow residents elected Selka Vey over Oren Vale at the last five-year mayoral ballot.", - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["loc:harrow_station","loc:harrow_civic_quarter"] - }, - { - "id":"fact:harrow_resources", - "statement":"The civic treasury is funded by berth dues published before each ward appropriation session.", - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["loc:harrow_station","loc:harrow_civic_quarter"] - }, - { - "id":"fact:harrow_redress", - "statement":"Residents may contest a mayoral order before the ward assembly's open petitions bench.", - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["loc:harrow_station","loc:harrow_civic_quarter"] - } - ], - "populations":[{ - "id":"harrow-residents", - "name":"Harrow residents", - "home_location_id":"loc:harrow_civic_quarter", - "shared_capabilities":["participate in ward ballots"], - "shared_fact_ids":["fact:harrow_authority","fact:harrow_selection","fact:harrow_resources","fact:harrow_redress"], - "resources":["ward meeting rooms"], - "goals":["keep berth dues answerable to residents"], - "pressures":["the mayor and assembly dispute emergency appropriations"], - "collective_authority_id":"harrow-residents", - "facets":{ - "geography":["Harrow Station"], - "ideology":["ward representation"], - "authority":["resident franchise"], - "economy_role":["station households and berth workers"], - "species_body":["mixed residents"], - "information":["ward notice boards"] - }, - "information_channels":["ward notice boards"] - }], - "institutions":[ - { - "id":"harrow-mayoral-office", - "name":"Harrow Mayoral Office", - "resources":["civic seal","emergency clerks"], - "goals":["retain emergency spending discretion"], - "posture":"press the ward assembly for immediate appropriation", - "location_ids":["loc:harrow_station"], - "facets":{ - "geography":["Harrow Station"], - "ideology":["executive dispatch"], - "authority":["mayoral orders"], - "economy_role":["emergency administration"], - "species_body":["mixed civil service"], - "information":["sealed civic notices"] - }, - "information_channels":["sealed civic notices"] - }, - { - "id":"harrow-ward-assembly", - "name":"Harrow Ward Assembly", - "resources":["appropriations ledger","petitions bench"], - "goals":["bind emergency spending to public accounts"], - "posture":"withhold appropriation pending an open audit", - "location_ids":["loc:harrow_civic_quarter"], - "facets":{ - "geography":["Harrow wards"], - "ideology":["public accounting"], - "authority":["appropriations and petitions"], - "economy_role":["budget oversight"], - "species_body":["mixed ward delegates"], - "information":["open session record"] - }, - "information_channels":["open session record"] - } - ], - "local_relations":[{ - "id":"relation:harrow-mayor-assembly", - "from_subject_id":"harrow-mayoral-office", - "to_subject_id":"harrow-ward-assembly", - "kind":"rivalry", - "strength":72 - }], - "civic_system":{ - "schema":"ghostlight.civic_system_manifest.v1", - "jurisdiction_location_id":"loc:harrow_station", - "governing_institution_ids":["harrow-mayoral-office","harrow-ward-assembly"], - "resident_population_ids":["harrow-residents"], - "public_authority_fact_ids":["fact:harrow_authority"], - "public_selection_fact_ids":["fact:harrow_selection"], - "public_resource_fact_ids":["fact:harrow_resources"], - "public_redress_fact_ids":["fact:harrow_redress"], - "political_relation_ids":["relation:harrow-mayor-assembly"] - }, - "migration_relations":[], - "branch_assumptions":["Harrow's mayoral ballot, ward appropriations split, officeholders, and current dispute are bounded campaign-local elaboration."], - "gaps":[] - }) - .to_string()) - } - "destination_civic_verification" => Ok(serde_json::json!({ - "authority_legible":true, - "selection_or_succession_legible":true, - "public_resources_legible":true, - "redress_legible":true, - "institutional_relations_coherent":true, - "resident_answer_grounded":true, - "political_form_distinct_or_deliberately_shared":true, - "opposed_interests_have_distinct_means":true, - "constituencies_cross_boundaries_or_local_homogeneity_justified":true, - "explicit_request_constraints_satisfied":true, - "public_names_do_not_repeat_an_overused_template":true, - "candidate_text_intact":true, - "rationale":"Harrow's exact public facts explain its divided authority, ballot, revenue, and appeal path to every resident population." - }) - .to_string()), - _ => Err(anyhow!( - "unexpected existing destination stage {}", - request.stage - )), - } - } - - fn provider(&self) -> &'static str { - "existing-destination-fixture" - } - } - - #[async_trait] - impl ModelPort for OversizedQueryModel { - async fn run(&self, _: &ModelStageRequest) -> Result { - Ok(serde_json::json!({"queries":["x".repeat(241)]}).to_string()) - } - fn provider(&self) -> &'static str { - "oversized-query-fixture" - } - } - #[async_trait] - impl ModelPort for CompilerModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - Ok(match request.stage.as_str() { - "opening_retrieval_plan" => serde_json::json!({ - "early_frame_query":"fixture earliest period ring strike", - "transition_frame_query":"fixture transition period moon siege", - "late_frame_query":"fixture latest period station election" - }).to_string(), - "destination_identity_resolution" => serde_json::json!({ - "decision":"new", - "existing_location_id":null, - "rationale":"The requested destination is not one of the supplied locations." - }).to_string(), - stage if stage.ends_with("_retrieval_plan") => { - let count = if stage == "role_retrieval_plan" - || stage == "destination_retrieval_plan" - { - 2 - } else { - 3 - }; - serde_json::json!({"queries":(1..=count).map(|index|format!("fixture grounded query {index}")).collect::>()}).to_string() - } - "evidence_relevance" => serde_json::json!({ - "coverage":[{ - "source_id":"AetheriaLore:test.md", - "lane":"direct_seed", - "rationale":"The fixture source directly grounds the requested place." - }] - }).to_string(), - "global_agency_compile" => serde_json::json!({ - "institutions":[{ - "name":"Fixture Council", - "supporting_claims":["The Fixture Council maintains the shared route."] - }], - "gaps":[] - }).to_string(), - "global_agency_doctrine_synthesis" => serde_json::json!({ - "institutions":[{ - "name":"Fixture Council", - "strategic_doctrine":"Maintain the shared route as a durable civic responsibility." - }] - }).to_string(), - "global_agency_doctrine_verification" => serde_json::json!({ - "verdicts":[{ - "name":"Fixture Council", - "compatible_with_canon":true, - "rationale":"The doctrine preserves the maintenance anchor." - }] - }).to_string(), - "world_openings" => serde_json::json!({"openings":[ - {"id":"a","title":"Ash","era":"early","place":"ring","pressure":"strike","player_hook":"work","evidence_receipt_ids":[]}, - {"id":"b","title":"Glass","era":"middle","place":"moon","pressure":"siege","player_hook":"survive","evidence_receipt_ids":[]}, - {"id":"c","title":"Rain","era":"late","place":"station","pressure":"election","player_hook":"choose","evidence_receipt_ids":[]} - ]}).to_string(), - "world_roles" => serde_json::json!({"roles":[ - {"id":"courier","name":"Courier","premise":"Carry a disputed manifest through the blockade.","capabilities":["route knowledge"],"obligations":["deliver the manifest"],"evidence_receipt_ids":[]}, - {"id":"organizer","name":"Dock Organizer","premise":"Keep the strike coalition together under pressure.","capabilities":["labor trust"],"obligations":["protect the picket"],"evidence_receipt_ids":[]}, - {"id":"auditor","name":"Contract Auditor","premise":"Trace the institution hiding the missing supplies.","capabilities":["ledger access"],"obligations":["report material fraud"],"evidence_receipt_ids":[]} - ]}).to_string(), - "world_compile" => { - let destination = if self.invalid_route { "missing" } else { "yard" }; - serde_json::json!({ - "title":"Grounded test", "canon_cutoff":"fixture", "world_time":"2026-01-01T00:00:00Z", "tick_hours":6, - "player":{"id":"player","name":"Tester","location_id":"yard","capabilities":[],"knowledge":[],"equipment":[],"conditions":[],"obligations":[],"relationships":[],"goals":["learn"]}, - "locations":[{"id":"yard","name":"Yard","container_id":null,"routes":[{"route_id":"out","destination_id":destination,"distance":"near","travel_minutes":5}],"persistent_features":["same yard"]}], - "actors":[], - "gestalts":[{"schema":"ghostlight.gestalt_persona_state.v1","id":"yard-workers","name":"Yard workers","version":0,"home_location_id":"yard","shared_capabilities":["maintain machinery"],"shared_knowledge":["yard routines"],"resources":["tool shed"],"goals":["finish the shift"],"pressures":["the gate is failing"]}], - "gestalt_members":[{"schema":"ghostlight.gestalt_member_delta.v1","id":"member:john","gestalt_id":"yard-workers","version":0,"name":"John the smith","capability_additions":["forge hinges"],"capability_removals":[],"knowledge_additions":[],"knowledge_removals":[],"equipment":["hammer"],"conditions":[],"obligations":[],"relationships":[],"goals":[],"memories":[],"last_location_id":"yard","materialized_actor_id":null}], - "institutions":[],"clocks":[{"id":"shift","label":"Shift ends","progress":0,"threshold":4,"consequence":"night","consequence_scope":{"actor_ids":[],"institution_ids":[],"gestalt_ids":["yard-workers"],"location_ids":["yard"],"public_channels":[]}}], - "facts":[ - {"id":"f","statement":"A witnessed fact","scope":"canon_baseline","evidence_receipt_ids":["fixture"]}, - {"id":"local","statement":"The outer gate indicator is dark.","scope":"branch_local","evidence_receipt_ids":[],"discoverable_at_location_ids":["yard"]} - ], - "gaps":[{ - "kind":"unanchored_requested_baseline", - "summary":"The approved premise requires a canon owner for the outer gate, but no compatible baseline is anchored.", - "premise_clause":"The outer gate must be owned by a canon institution.", - "blocked_choice":"Choose which institution canonically owns the outer gate or remove that canon-specific requirement.", - "evidence_receipt_ids":[] - }],"branch_assumptions":[],"opening_narration":"The yard persists." - }).to_string() - } - "agency_compile" => serde_json::json!({ - "agency_profiles":[{"subject_id":"yard-workers","subject_kind":"gestalt","collective_authority_id":"yard-workers","facets":{"geography":["yard"],"ideology":["mutual aid"],"authority":["yard-workers"],"economy_role":["maintenance"],"species_body":["human"],"information":["yard routines"]},"location_ids":["yard"],"information_channels":["yard bulletin"]}], - "agency_relations":[] - }).to_string(), - _ => return Err(anyhow!("unexpected stage")), - }) - } - fn provider(&self) -> &'static str { - "compiler-fixture" - } - } - - fn vault() -> Arc { - Arc::new(FixtureVault { - witnesses: vec![SourceWitness { - source_id: "AetheriaLore:test.md".into(), - exact_locator: "test.md:1-2".into(), - content_hash: "sha256:test".into(), - excerpt: - "A stable witnessed place. The Fixture Council maintains the shared route." - .into(), - authority_lane: "AetheriaLore".into(), - temporal_scope: "fixture".into(), - }], - }) - } - - struct ExactWitnessVault; - #[async_trait] - impl VaultProvider for ExactWitnessVault { - async fn search(&self, query: &VaultQuery) -> Result { - Ok(VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: "search-receipt".into(), - provider: "fixture".into(), - query_hash: "sha256:query".into(), - witnesses: vec![SourceWitness { - source_id: "AetheriaLore:route.md".into(), - exact_locator: "route.md:2-2".into(), - content_hash: "sha256:excerpt-only".into(), - excerpt: "The route takes six hours.".into(), - authority_lane: query.authority_lanes.join(","), - temporal_scope: query.temporal_scope.clone(), - }], - retrieved_at: Utc::now(), - }) - } - - async fn surrounding_context(&self, _: &str, _: u32) -> Result { - unreachable!() - } - - async fn exact_document(&self, source_id: &str) -> Result { - let content = - "The forge opens at dawn.\nThe route takes six hours.\nThe gate closes at dusk."; - Ok(SourceWitness { - source_id: source_id.into(), - exact_locator: "route.md".into(), - content_hash: format!("sha256:{:x}", sha2::Sha256::digest(content.as_bytes())), - excerpt: content.into(), - authority_lane: "AetheriaLore".into(), - temporal_scope: "fixture".into(), - }) - } - - fn provider_id(&self) -> &'static str { - "fixture" - } - } - - #[test] - fn campaign_relationships_bind_to_canonical_subject_ids() { - let mut campaign = crate::resolution::tests::campaign(2, 1); - campaign.gestalts.insert( - "clinic-staff".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "clinic-staff".into(), - name: "Clinic staff".into(), - version: 0, - home_location_id: "center".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - crate::resolution::ensure_agency_profiles(&mut campaign); - campaign - .actors - .get_mut("player") - .unwrap() - .relationships - .insert("faction-0000".into(), "cautious contact".into()); - campaign - .actors - .get_mut("player") - .unwrap() - .relationships - .insert( - "clinic-staff".into(), - "trusted by the clinic collective".into(), - ); - validate_campaign_seed(&campaign).unwrap(); - - campaign - .actors - .get_mut("player") - .unwrap() - .relationships - .insert("Faction Zero".into(), "display name, not identity".into()); - let error = validate_campaign_seed(&campaign).unwrap_err().to_string(); - assert!(error.contains("player->Faction Zero")); - assert!(error.contains("faction-0000")); - } - - #[test] - fn campaign_seed_rejects_an_oversized_institution_posture() { - let mut campaign = crate::resolution::tests::campaign(2, 1); - let institution = campaign.institutions.values_mut().next().unwrap(); - institution.posture = "x".repeat(MAX_POSTURE_CHARS + 1); - - let error = validate_campaign_seed(&campaign).unwrap_err(); - assert!(error.to_string().contains("one to 460 characters")); - } - - #[test] - fn fresh_seed_rejects_due_clock_while_runtime_accepts_legacy_checkpoint() { - let mut campaign = crate::resolution::tests::campaign(2, 1); - campaign.clocks.insert( - "due".into(), - WorldClock { - id: "due".into(), - label: "Due".into(), - progress: 1, - threshold: 1, - consequence: "Faction Zero occupies the counting hall.".into(), - consequence_scope: crate::domain::WorldEventScope { - actor_ids: Vec::new(), - institution_ids: vec!["faction-0000".into()], - gestalt_ids: Vec::new(), - location_ids: vec!["center".into()], - public_channels: Vec::new(), - }, - }, - ); - - assert!(validate_campaign_seed(&campaign).is_err()); - validate_campaign_runtime(&campaign).unwrap(); - } - - #[test] - fn campaign_seed_rejects_invalid_channels_and_knowledge_disguised_as_channels() { - let mut campaign = crate::resolution::tests::campaign(2, 1); - campaign - .agency_profiles - .get_mut("player") - .unwrap() - .information_channels - .insert("unknown".into()); - let error = validate_campaign_seed(&campaign).unwrap_err(); - assert!(error.to_string().contains("invalid information channel")); - - campaign - .agency_profiles - .get_mut("player") - .unwrap() - .information_channels - .remove("unknown"); - campaign - .agency_profiles - .get_mut("player") - .unwrap() - .information_channels - .insert("root-wire broadsheet".into()); - campaign - .actors - .get_mut("player") - .unwrap() - .knowledge - .insert("root-wire broadsheet".into()); - let error = validate_campaign_seed(&campaign).unwrap_err(); - assert!(error.to_string().contains("cannot use factual knowledge")); - } - - #[test] - fn approved_relationships_resolve_party_members_and_materialize_stable_private_anchors() { - let mut sable = CharacterDraft { - member_id: "member-sable".into(), - actor_id: "actor-sable".into(), - name: "Sable".into(), - ..Default::default() - }; - sable.relationships.insert( - "convoy quartermaster".into(), - "Sable owes them a life-debt".into(), - ); - let mut mara = CharacterDraft { - member_id: "member-mara".into(), - actor_id: "actor-mara".into(), - name: "Mara".into(), - ..Default::default() - }; - mara.relationships - .insert("Sable".into(), "trusted under pressure".into()); - let brief = ApprovedCampaignBrief { - schema: "ghostlight.approved_campaign_brief.v1".into(), - session_zero_id: Uuid::new_v4(), - host_member_id: "member-sable".into(), - contract: CampaignContract::default(), - aggregate_boundaries: vec![], - characters: vec![sable, mara], - member_actor_ids: BTreeMap::from([ - ("member-sable".into(), "actor-sable".into()), - ("member-mara".into(), "actor-mara".into()), - ]), - shared_digest: "sha256:shared".into(), - character_digests: BTreeMap::new(), - }; - - let first = approved_relationship_plan(&brief).unwrap(); - let second = approved_relationship_plan(&brief).unwrap(); - assert_eq!(first, second); - assert_eq!(first.anchors.len(), 1); - assert_eq!(first.anchors[0].name, "convoy quartermaster"); - assert!(first.anchors[0].id.starts_with("relationship-anchor:")); - assert_eq!( - first.targets[&("member-mara".into(), "Sable".into())], - "actor-sable" - ); - assert_eq!( - first.targets[&("member-sable".into(), "convoy quartermaster".into())], - first.anchors[0].id - ); - assert_eq!( - first.anchors[0].approved_relationship_descriptions, - vec!["Sable owes them a life-debt"] - ); - } - - #[test] - fn relationship_anchor_validation_requires_the_exact_actor_identity() { - let mut campaign = crate::resolution::tests::campaign(2, 1); - let anchor = RequiredRelationshipActor { - id: "relationship-anchor:quartermaster".into(), - name: "convoy quartermaster".into(), - approved_relationship_descriptions: vec!["trusted convoy contact".into()], - }; - let mut actor = campaign.actors["player"].clone(); - actor.id = anchor.id.clone(); - actor.name = anchor.name.clone(); - campaign.actors.insert(actor.id.clone(), actor); - validate_required_relationship_actors(&campaign, std::slice::from_ref(&anchor)).unwrap(); - - campaign.actors.get_mut(&anchor.id).unwrap().name = "Somebody else".into(); - assert!( - validate_required_relationship_actors(&campaign, &[anchor]) - .unwrap_err() - .to_string() - .contains("failed private relationship actor binding") - ); - } - - #[tokio::test] - async fn approved_private_relationship_identity_never_enters_shared_world_compilation() { - let model = Arc::new(PrivateBoundaryCompilerModel { - retrieval_stage_received_approved_contract: AtomicBool::new(false), - shared_stage_was_private_free: AtomicBool::new(false), - shared_stage_received_operational_playability: AtomicBool::new(false), - shared_stage_received_approved_contract: AtomicBool::new(false), - evidence_stage_received_approved_contract: AtomicBool::new(false), - private_stage_was_minimal: AtomicBool::new(false), - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let mut character = CharacterDraft { - schema: "ghostlight.character_draft.v1".into(), - member_id: "member-sable".into(), - actor_id: "actor-sable".into(), - name: "Sable".into(), - public_premise: "A logistics mediator".into(), - capabilities: vec!["route planning".into()], - secrets: vec!["SECRET_COOLANT_RECORD".into()], - knowledge: vec!["PRIVATE_ROUTE_CODE".into()], - goals: vec!["keep the convoy supplied".into()], - ..CharacterDraft::default() - }; - character.relationships.insert( - "convoy quartermaster".into(), - "Sable owes them a life-debt; they are the current convoy quartermaster and can explain the manifest but cannot allocate cargo alone".into(), - ); - let brief = ApprovedCampaignBrief { - schema: "ghostlight.approved_campaign_brief.v1".into(), - session_zero_id: Uuid::new_v4(), - host_member_id: "member-sable".into(), - contract: CampaignContract { - campaign_name: "Private boundary".into(), - premise: format!( - "A convoy has reached a strained logistics yard. {}", - "Public table-approved opening detail. ".repeat(40) - ), - canon_horizon: "fixture".into(), - starting_where: "yard".into(), - starting_when: "now".into(), - starting_pressure: "The convoy needs supplies.".into(), - desired_goal: "Keep the convoy supplied.".into(), - ..CampaignContract::default() - }, - aggregate_boundaries: vec![], - characters: vec![character], - member_actor_ids: BTreeMap::from([("member-sable".into(), "actor-sable".into())]), - shared_digest: "sha256:shared".into(), - character_digests: BTreeMap::new(), - }; - - let (preview, _) = compiler.compile_approved_brief(&brief).await.unwrap(); - - assert!( - model - .retrieval_stage_received_approved_contract - .load(Ordering::SeqCst) - ); - assert!(model.shared_stage_was_private_free.load(Ordering::SeqCst)); - assert!( - model - .shared_stage_received_operational_playability - .load(Ordering::SeqCst) - ); - assert!( - model - .shared_stage_received_approved_contract - .load(Ordering::SeqCst) - ); - assert!( - model - .evidence_stage_received_approved_contract - .load(Ordering::SeqCst) - ); - assert!(model.private_stage_was_minimal.load(Ordering::SeqCst)); - assert!( - !preview.campaign.transcript[0] - .text - .contains("convoy quartermaster") - ); - assert!( - !preview - .branch_assumptions - .iter() - .any(|assumption| assumption.contains("convoy quartermaster")) - ); - let anchor = preview - .campaign - .actors - .values() - .find(|actor| actor.id.starts_with("relationship-anchor:")) - .unwrap(); - assert_eq!(anchor.name, "convoy quartermaster"); - assert_eq!(anchor.location_id, "yard"); - assert!(anchor.capabilities.contains("convoy logistics")); - assert!(anchor.knowledge.contains("current manifest")); - assert_eq!( - anchor.relationships.get("yard-workers"), - Some(&"convoy clerk coordinating with the yard workers".into()) - ); - assert_eq!( - preview.campaign.actors["actor-sable"] - .relationships - .get(&anchor.id), - Some(&"Sable owes them a life-debt; they are the current convoy quartermaster and can explain the manifest but cannot allocate cargo alone".into()) - ); - } - - #[tokio::test] - async fn approved_player_identity_cannot_be_materialized_as_world_cast() { - let model = Arc::new(PlayerOwnershipCompilerModel { - world_calls: AtomicUsize::new(0), - saw_player_ownership_boundary: AtomicBool::new(false), - saw_exact_collision_correction: AtomicBool::new(false), - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let brief = ApprovedCampaignBrief { - schema: "ghostlight.approved_campaign_brief.v1".into(), - session_zero_id: Uuid::new_v4(), - host_member_id: "member-sable".into(), - contract: CampaignContract { - campaign_name: "Player ownership".into(), - premise: "A convoy has reached a strained logistics yard.".into(), - canon_horizon: "fixture".into(), - starting_where: "yard".into(), - starting_when: "now".into(), - starting_pressure: "The convoy needs supplies.".into(), - desired_goal: "Keep the convoy supplied.".into(), - ..CampaignContract::default() - }, - aggregate_boundaries: vec![], - characters: vec![CharacterDraft { - schema: "ghostlight.character_draft.v1".into(), - member_id: "member-sable".into(), - actor_id: "actor-sable".into(), - name: "Sable".into(), - public_premise: "A logistics mediator".into(), - capabilities: vec!["route planning".into()], - goals: vec!["keep the convoy supplied".into()], - ..CharacterDraft::default() - }], - member_actor_ids: BTreeMap::from([("member-sable".into(), "actor-sable".into())]), - shared_digest: "sha256:shared".into(), - character_digests: BTreeMap::new(), - }; - - let (preview, _) = compiler.compile_approved_brief(&brief).await.unwrap(); - - assert_eq!(model.world_calls.load(Ordering::SeqCst), 2); - assert!(model.saw_player_ownership_boundary.load(Ordering::SeqCst)); - assert!(model.saw_exact_collision_correction.load(Ordering::SeqCst)); - assert_eq!( - preview - .campaign - .actors - .values() - .filter(|actor| normalized_identity(&actor.name) == "sable") - .count(), - 1 - ); - assert_eq!(preview.campaign.player_actor_id, "actor-sable"); - } - - #[test] - fn approved_player_identity_cannot_be_materialized_as_a_gestalt_member() { - let mut seed = private_actor_test_seed(); - seed.gestalts.push(GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "corvid-collective".into(), - name: "Corvid collective".into(), - version: 0, - home_location_id: "convoy-staging".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }); - seed.gestalt_members.push(CompiledGestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "member-corvid-sable".into(), - gestalt_id: "corvid-collective".into(), - version: 0, - name: "Sable".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: vec![], - goals: vec![], - memories: vec![], - last_location_id: Some("convoy-staging".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }); - - let error = - validate_shared_seed_excludes_locally_owned_subjects(&seed, &[], &["Sable".into()]) - .unwrap_err() - .to_string(); - assert!(error.contains("member:member-corvid-sable")); - } - - fn private_actor_test_actor(id: &str, name: &str) -> ActorState { - ActorState { - id: id.into(), - name: name.into(), - location_id: "yard".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - } - } - - fn private_actor_test_seed() -> CompiledSeed { - CompiledSeed { - title: "Private actor compilation".into(), - canon_cutoff: "fixture".into(), - world_time: Utc::now(), - tick_hours: 6, - player: private_actor_test_actor("player", "Sable").into(), - locations: vec![CompiledLocation { - id: "convoy-staging".into(), - name: "Convoy Staging".into(), - container_id: None, - routes: vec![], - persistent_features: vec!["temporary shelters".into()], - }], - actors: vec![], - gestalts: vec![], - gestalt_members: vec![], - institutions: vec![], - clocks: vec![], - facts: vec![], - gaps: vec![], - branch_assumptions: vec![], - opening_narration: String::new(), - } - } - - fn private_actor_candidate(name: &str, location_id: &str) -> PrivateRelationshipActorCandidate { - PrivateRelationshipActorCandidate { - name: name.into(), - location_id: location_id.into(), - capabilities: BTreeSet::from(["convoy logistics".into()]), - knowledge: BTreeSet::from(["current convoy manifest".into()]), - equipment: BTreeSet::from(["manifest terminal".into()]), - conditions: BTreeSet::new(), - obligations: BTreeSet::from(["account for the convoy".into()]), - relationships: vec![], - goals: vec!["get the convoy supplied".into()], - memories: vec![], - } - } - - #[test] - fn private_actor_schema_projects_exact_current_binding_authority() { - let seed = private_actor_test_seed(); - let anchors = vec![RequiredRelationshipActor { - id: "relationship-anchor:quartermaster".into(), - name: "convoy quartermaster".into(), - approved_relationship_descriptions: vec!["trusted convoy contact".into()], - }]; - let mut schema = serde_json::to_value(schema_for!(PrivateRelationshipActorSet)).unwrap(); - constrain_private_relationship_actor_schema(&mut schema, &anchors, &seed).unwrap(); - let validator = jsonschema::validator_for(&schema).unwrap(); - let candidate = |name: &str, location_id: &str, relationships: serde_json::Value| { - serde_json::json!({ - "actors":[{ - "name":name, - "location_id":location_id, - "capabilities":[], - "knowledge":[], - "equipment":[], - "conditions":[], - "obligations":[], - "relationships":relationships, - "goals":[], - "memories":[] - }] - }) - }; - - assert!(validator.is_valid(&candidate( - "convoy quartermaster", - "convoy-staging", - serde_json::json!([]) - ))); - assert!(!validator.is_valid(&candidate( - "renamed quartermaster", - "convoy-staging", - serde_json::json!([]) - ))); - assert!(!validator.is_valid(&candidate( - "convoy quartermaster", - "invented-location", - serde_json::json!([]) - ))); - assert!(!validator.is_valid(&candidate( - "convoy quartermaster", - "convoy-staging", - serde_json::json!([{ - "subject_id":"invented-office", - "description":"invented affiliation" - }]) - ))); - } - - #[test] - fn private_actor_materialization_attaches_server_identity() { - let anchor = RequiredRelationshipActor { - id: "relationship-anchor:quartermaster".into(), - name: "convoy quartermaster".into(), - approved_relationship_descriptions: vec!["trusted convoy contact".into()], - }; - let actors = materialize_private_relationship_actors( - &private_actor_test_seed(), - std::slice::from_ref(&anchor), - PrivateRelationshipActorSet { - actors: vec![private_actor_candidate( - "Convoy Quartermaster", - "convoy-staging", - )], - }, - ) - .unwrap(); - - assert_eq!(actors.len(), 1); - assert_eq!(actors[0].id, anchor.id); - assert_eq!(actors[0].name, anchor.name); - assert_eq!(actors[0].location_id, "convoy-staging"); - assert!(actors[0].capabilities.contains("convoy logistics")); - assert!(actors[0].relationships.is_empty()); - } - - #[test] - fn private_actor_materialization_rejects_missing_ambiguous_unknown_and_colliding_state() { - let anchor = RequiredRelationshipActor { - id: "relationship-anchor:quartermaster".into(), - name: "convoy quartermaster".into(), - approved_relationship_descriptions: vec!["trusted convoy contact".into()], - }; - let seed = private_actor_test_seed(); - assert!( - materialize_private_relationship_actors( - &seed, - std::slice::from_ref(&anchor), - PrivateRelationshipActorSet { actors: vec![] } - ) - .unwrap_err() - .to_string() - .contains("returned 0 candidates") - ); - - assert!( - materialize_private_relationship_actors( - &seed, - std::slice::from_ref(&anchor), - PrivateRelationshipActorSet { - actors: vec![ - private_actor_candidate("Convoy Quartermaster", "convoy-staging"), - private_actor_candidate("convoy-quartermaster", "convoy-staging"), - ] - } - ) - .unwrap_err() - .to_string() - .contains("returned 2 candidates") - ); - - let medic = RequiredRelationshipActor { - id: "relationship-anchor:medic".into(), - name: "convoy medic".into(), - approved_relationship_descriptions: vec!["known convoy medic".into()], - }; - assert!( - materialize_private_relationship_actors( - &seed, - &[anchor.clone(), medic], - PrivateRelationshipActorSet { - actors: vec![ - private_actor_candidate("Convoy Quartermaster", "convoy-staging"), - private_actor_candidate("convoy-quartermaster", "convoy-staging"), - ] - } - ) - .unwrap_err() - .to_string() - .contains("ambiguous candidates") - ); - - let mut unknown = private_actor_candidate("convoy quartermaster", "missing"); - assert!( - materialize_private_relationship_actors( - &seed, - std::slice::from_ref(&anchor), - PrivateRelationshipActorSet { - actors: vec![unknown.clone()] - } - ) - .unwrap_err() - .to_string() - .contains("occupies unknown location") - ); - - unknown.location_id = "convoy-staging".into(); - unknown.relationships = vec![CompiledRelationship { - subject_id: "player".into(), - description: "guessed player relationship".into(), - }]; - assert!( - materialize_private_relationship_actors( - &seed, - std::slice::from_ref(&anchor), - PrivateRelationshipActorSet { - actors: vec![unknown.clone()] - } - ) - .unwrap_err() - .to_string() - .contains("outside the exact public actor, institution, and population allowlist") - ); - - unknown.relationships.clear(); - let mut collision = seed; - collision.player.id.clone_from(&anchor.id); - assert!( - materialize_private_relationship_actors( - &collision, - &[anchor], - PrivateRelationshipActorSet { - actors: vec![unknown] - } - ) - .unwrap_err() - .to_string() - .contains("collides with an existing canonical subject") - ); - } - - #[tokio::test] - async fn opening_stage_requires_three_distinct_axes() { - let compiler = WorldCompiler::new( - vault(), - Arc::new(CompilerModel { - invalid_route: false, - }), - "flash", - "pro", - ); - let output = compiler - .suggest_openings(OpeningRequest { - setting: "Aetheria".into(), - constraints: vec![], - }) - .await - .unwrap(); - assert_eq!(output.openings.len(), 3); - assert_eq!(output.evidence_receipts.len(), 3); - assert_eq!(output.model_receipts.len(), 1); - } - - #[tokio::test] - async fn opening_stage_corrects_a_semantically_duplicate_axis_once() { - let model = Arc::new(CorrectionAwareOpeningModel { - opening_calls: AtomicUsize::new(0), - saw_exact_correction: AtomicBool::new(false), - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - - let output = compiler - .suggest_openings(OpeningRequest { - setting: "Aetheria".into(), - constraints: vec![], - }) - .await - .unwrap(); - - assert_eq!(output.openings.len(), 3); - assert_eq!(output.model_receipts.len(), 2); - assert!(output.model_receipts[0].local_validation_error.is_some()); - assert!(output.model_receipts[1].local_validation_error.is_none()); - assert!(model.saw_exact_correction.load(Ordering::SeqCst)); - } - - #[tokio::test] - async fn role_stage_corrects_a_semantically_duplicate_axis_once() { - let model = Arc::new(CorrectionAwareRoleModel { - role_calls: AtomicUsize::new(0), - saw_exact_correction: AtomicBool::new(false), - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - - let output = compiler - .suggest_roles(&OpeningSuggestion { - id: "blockade".into(), - title: "The Blockade".into(), - era: "late".into(), - place: "ring".into(), - pressure: "blockade".into(), - player_hook: "choose a route".into(), - evidence_receipt_ids: vec![], - }) - .await - .unwrap(); - - assert_eq!(output.roles.len(), 3); - assert_eq!(output.model_receipts.len(), 2); - assert!(output.model_receipts[0].local_validation_error.is_some()); - assert!(output.model_receipts[1].local_validation_error.is_none()); - assert!(model.saw_exact_correction.load(Ordering::SeqCst)); - } - - #[test] - fn suggestion_evidence_uses_set_semantics_and_rejects_unknown_receipts_precisely() { - let mut ids = vec![ - "receipt:one".into(), - "receipt:one".into(), - "receipt:two".into(), - ]; - deduplicate_ids(&mut ids); - assert_eq!(ids, ["receipt:one", "receipt:two"]); - validate_suggestion_evidence( - "opening", - &ids, - &["receipt:one".into(), "receipt:two".into()], - ) - .unwrap(); - - let error = validate_suggestion_evidence( - "opening", - &["receipt:invented".into()], - &["receipt:one".into()], - ) - .unwrap_err() - .to_string(); - assert!(error.contains("absent from the supplied Vault evidence")); - assert!(error.contains("receipt:invented")); - } - - #[tokio::test] - async fn doctrine_stage_rewrites_canon_contradiction_but_keeps_branch_elaboration() { - let model = Arc::new(CorrectionAwareDoctrineModel { - synthesis_calls: AtomicUsize::new(0), - saw_branch_elaboration_boundary: AtomicBool::new(false), - saw_verifier_correction: AtomicBool::new(false), - stay_incompatible: false, - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let start = CustomStart { - campaign_name: "Doctrine correction".into(), - who: "worker".into(), - where_: "yard".into(), - when: "fixture".into(), - goal: "keep the route open".into(), - }; - let grounded = GroundedGlobalAgencyCatalog { - institutions: vec![GroundedRemoteInstitution { - name: "Fixture Council".into(), - supporting_claims: vec!["The Fixture Council maintains the shared route.".into()], - evidence_receipt_ids: vec!["receipt:fixture".into()], - }], - gaps: vec![], - }; - - let (catalog, receipts) = compiler - .synthesize_global_agency_doctrine(&start, grounded) - .await - .unwrap(); - - assert_eq!(catalog.institutions.len(), 1); - assert_eq!( - catalog.institutions[0].strategic_doctrine, - "Maintain the shared route through rotating repair crews, convoy permits, and temporary rationing during breakdowns." - ); - assert_eq!( - receipts - .iter() - .map(|receipt| receipt.stage.as_str()) - .collect::>(), - vec![ - "global_agency_doctrine_synthesis", - "global_agency_doctrine_verification", - "global_agency_doctrine_synthesis", - "global_agency_doctrine_verification" - ] - ); - assert!(receipts[1].local_validation_error.is_some()); - assert!(receipts[3].local_validation_error.is_none()); - assert!(model.saw_branch_elaboration_boundary.load(Ordering::SeqCst)); - assert!(model.saw_verifier_correction.load(Ordering::SeqCst)); - } - - #[tokio::test] - async fn doctrine_stage_aborts_instead_of_omitting_an_incompatible_institution() { - let model = Arc::new(CorrectionAwareDoctrineModel { - synthesis_calls: AtomicUsize::new(0), - saw_branch_elaboration_boundary: AtomicBool::new(false), - saw_verifier_correction: AtomicBool::new(false), - stay_incompatible: true, - }); - let compiler = WorldCompiler::new(vault(), model, "flash", "pro"); - let start = CustomStart { - campaign_name: "Doctrine refusal".into(), - who: "worker".into(), - where_: "yard".into(), - when: "fixture".into(), - goal: "keep the route open".into(), - }; - let grounded = GroundedGlobalAgencyCatalog { - institutions: vec![GroundedRemoteInstitution { - name: "Fixture Council".into(), - supporting_claims: vec!["The Fixture Council maintains the shared route.".into()], - evidence_receipt_ids: vec!["receipt:fixture".into()], - }], - gaps: vec![], - }; - - let error = compiler - .synthesize_global_agency_doctrine(&start, grounded) - .await - .unwrap_err(); - assert!( - error - .to_string() - .contains("contradicted canon after one correction") - ); - } - - #[tokio::test] - async fn retrieval_planner_refuses_provider_oversized_queries() { - let compiler = WorldCompiler::new(vault(), Arc::new(OversizedQueryModel), "flash", "pro"); - let error = compiler - .plan_queries("custom_retrieval_plan", "test", "subject", 1) - .await - .unwrap_err(); - assert!(error.to_string().contains("1 to 240")); - } - - #[tokio::test] - async fn retrieval_receipts_bind_excerpts_to_exact_archive_hashes() { - let compiler = WorldCompiler::new( - Arc::new(ExactWitnessVault), - Arc::new(CompilerModel { - invalid_route: false, - }), - "flash", - "pro", - ); - let receipts = compiler - .retrieve_all(&["route".into()], "fixture", 3) - .await - .unwrap(); - let witness = &receipts[0].witnesses[0]; - assert_ne!(witness.content_hash, "sha256:excerpt-only"); - assert_eq!(witness.exact_locator, "route.md:2-2"); - } - - #[tokio::test] - async fn compile_returns_approval_preview_without_committing() { - let compiler = WorldCompiler::new( - vault(), - Arc::new(CompilerModel { - invalid_route: false, - }), - "flash", - "pro", - ); - let (preview, receipts) = compiler - .compile_custom(CustomStart { - campaign_name: "Test".into(), - who: "worker".into(), - where_: "yard".into(), - when: "fixture".into(), - goal: "learn".into(), - }) - .await - .unwrap(); - assert_eq!( - receipts - .iter() - .map(|receipt| receipt.stage.as_str()) - .collect::>(), - vec![ - "custom_retrieval_plan", - "evidence_relevance", - "global_agency_compile", - "global_agency_doctrine_synthesis", - "global_agency_doctrine_verification", - "world_compile", - "agency_compile" - ] - ); - assert!(preview.requires_approval); - assert_eq!(preview.evidence_coverage.len(), 1); - assert_eq!( - preview.evidence_coverage[0].lane, - EvidenceUseLane::DirectSeed - ); - assert_eq!(preview.campaign.revision, 0); - assert_eq!(preview.campaign.locations.len(), 1); - assert_eq!(preview.campaign.canon_candidates.len(), 1); - assert_eq!(preview.campaign.gestalts.len(), 1); - assert_eq!(preview.campaign.institutions.len(), 1); - assert_eq!(preview.campaign.agency_profiles.len(), 3); - let remote = preview - .campaign - .agency_profiles - .values() - .find(|profile| profile.subject_id.starts_with("remote-institution:")) - .unwrap(); - assert_eq!(remote.facets.len(), 6); - assert!(!remote.evidence_receipt_ids.is_empty()); - assert_eq!( - remote.facets[&AgencyAxis::Authority], - BTreeSet::from([remote.subject_id.clone()]) - ); - assert!(remote.information_channels.is_empty()); - assert_eq!( - preview.campaign.facts["f"].scope, - FactScope::ProvisionalLocal - ); - assert!(preview.campaign.facts["f"].evidence_receipt_ids.is_empty()); - assert_eq!( - preview.campaign.agency_profiles["yard-workers"].facets[&AgencyAxis::Ideology], - BTreeSet::from(["mutual aid".into()]) - ); - assert_eq!( - preview.campaign.gestalt_members["john"].name, - "John the smith" - ); - assert!( - preview.campaign.gestalt_members["john"] - .materialized_actor_id - .is_none() - ); - } - - #[tokio::test] - async fn destination_compiler_surfaces_compatible_playability_inventions_as_branch_assumptions() - { - let model = Arc::new(DestinationElaborationModel { - saw_branch_assumption_boundary: AtomicBool::new(false), - saw_balanced_civic_reconciliation: AtomicBool::new(false), - civic_verification_calls: AtomicUsize::new(0), - civic_verification_rejections: 0, - reconciliation_steals_non_civic_fact: false, - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let mut seed = private_actor_test_seed(); - seed.player.location_id = "convoy-staging".into(); - seed.opening_narration = "The convoy waits in the rain.".into(); - let campaign = seed_to_campaign(seed, &[]).unwrap(); - - let (preview, receipts) = compiler - .compile_destination( - &campaign, - "convoy-staging", - "a playable storm refuge with ordinary repair and admission procedure", - ) - .await - .unwrap(); - let DestinationCompilationPreview::RegionExpansion(preview) = preview else { - panic!("new destination must produce a region expansion preview") - }; - - assert!(model.saw_branch_assumption_boundary.load(Ordering::SeqCst)); - assert!(preview.requires_approval); - assert!(preview.gaps.is_empty()); - assert!(preview.canon_candidates.is_empty()); - assert_eq!(preview.branch_assumptions.len(), 1); - assert!(preview.branch_assumptions[0].contains("campaign-local elaboration")); - assert_eq!(preview.expansion.locations[0].id, "refuge"); - assert_eq!(preview.expansion.populations[0].id, "refuge-wardens"); - assert_eq!(preview.expansion.facts[0].scope, FactScope::BranchLocal); - assert_eq!( - receipts - .iter() - .map(|receipt| receipt.stage.as_str()) - .collect::>(), - vec![ - "destination_identity_resolution", - "destination_retrieval_plan", - "destination_compile", - "destination_civic_verification" - ] - ); - assert_eq!( - receipts - .iter() - .find(|receipt| receipt.stage == "destination_compile") - .unwrap() - .model, - MODEL_BALANCED - ); - assert_eq!( - receipts - .iter() - .find(|receipt| receipt.stage == "destination_civic_verification") - .unwrap() - .model, - "pro" - ); - } - - #[test] - fn destination_population_names_are_unique_in_the_public_population_namespace() { - let mut campaign = seed_to_campaign(private_actor_test_seed(), &[]).unwrap(); - campaign.gestalts.insert( - "ledger-keepers".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "ledger-keepers".into(), - name: "Ledger-Keepers".into(), - version: 0, - home_location_id: "convoy-staging".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: Vec::new(), - pressures: Vec::new(), - }, - ); - let population = |id: &str, name: &str| CompiledDestinationPopulation { - id: id.into(), - name: name.into(), - home_location_id: "refuge".into(), - shared_capabilities: BTreeSet::new(), - shared_fact_ids: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec!["keep the crossing usable".into()], - pressures: Vec::new(), - collective_authority_id: None, - facets: BTreeMap::>::new().into(), - information_channels: BTreeSet::new(), - }; - - assert!( - validate_compiled_destination_population_names( - &campaign, - &[population("new", "ledger keepers")] - ) - .unwrap_err() - .to_string() - .contains("distinct public population identity") - ); - assert!( - validate_compiled_destination_population_names( - &campaign, - &[ - population("one", "River Hands"), - population("two", "river-hands"), - ] - ) - .is_err() - ); - validate_compiled_destination_population_names( - &campaign, - &[ - population("one", "River Hands"), - population("two", "Stone Sounders"), - ], - ) - .unwrap(); - } - - #[tokio::test] - async fn destination_full_owner_regenerates_after_one_rejected_civic_verdict() { - let model = Arc::new(DestinationElaborationModel { - saw_branch_assumption_boundary: AtomicBool::new(false), - saw_balanced_civic_reconciliation: AtomicBool::new(false), - civic_verification_calls: AtomicUsize::new(0), - civic_verification_rejections: 1, - reconciliation_steals_non_civic_fact: false, - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let mut seed = private_actor_test_seed(); - seed.player.location_id = "convoy-staging".into(); - seed.opening_narration = "The convoy waits in the rain.".into(); - let campaign = seed_to_campaign(seed, &[]).unwrap(); - - let (preview, receipts) = compiler - .compile_destination( - &campaign, - "convoy-staging", - "a playable storm refuge with ordinary repair and admission procedure", - ) - .await - .unwrap(); - let DestinationCompilationPreview::RegionExpansion(preview) = preview else { - panic!("new destination must produce a region expansion preview") - }; - let verification_receipts = receipts - .iter() - .filter(|receipt| receipt.stage == "destination_civic_verification") - .collect::>(); - let reconciliation_receipts = receipts - .iter() - .filter(|receipt| receipt.stage == "destination_reconciliation_agent_action") - .collect::>(); - let compile_receipts = receipts - .iter() - .filter(|receipt| receipt.stage == "destination_compile") - .collect::>(); - - assert_eq!(model.civic_verification_calls.load(Ordering::SeqCst), 2); - assert_eq!(verification_receipts.len(), 2); - assert_eq!(compile_receipts.len(), 2); - assert!(reconciliation_receipts.is_empty()); - assert_eq!( - verification_receipts[0].validation_result, - "semantic_invalid" - ); - assert_eq!(verification_receipts[1].validation_result, "valid"); - assert!( - verification_receipts[1] - .source_receipt_ids - .iter() - .any(|source| source == compile_receipts[1].storage_key()) - ); - assert_eq!( - preview - .expansion - .civic_system - .as_ref() - .unwrap() - .semantic_verification_receipt_id, - verification_receipts[1].storage_key() - ); - } - - fn civic_reconciliation_seed( - institutions: Vec, - ) -> CompiledExpansionSeed { - CompiledExpansionSeed { - origin_routes: vec![], - locations: vec![], - facts: vec![], - populations: vec![], - institutions, - local_relations: vec![], - civic_system: Some(CivicSystemManifest { - schema: "ghostlight.civic_system_manifest.v1".into(), - version: 0, - jurisdiction_location_id: "refuge".into(), - governing_institution_ids: BTreeSet::new(), - resident_population_ids: BTreeSet::new(), - public_authority_fact_ids: BTreeSet::new(), - public_selection_fact_ids: BTreeSet::new(), - public_resource_fact_ids: BTreeSet::new(), - public_redress_fact_ids: BTreeSet::new(), - political_relation_ids: BTreeSet::new(), - semantic_verification_receipt_id: String::new(), - }), - migration_relations: vec![], - branch_assumptions: vec![], - gaps: vec![], - } - } - - fn empty_civic_reconciliation( - institution_updates: Vec, - ) -> CompiledDestinationReconciliation { - CompiledDestinationReconciliation { - facts: vec![], - resident_fact_knowledge: vec![], - institution_updates, - local_relations: vec![], - civic_system: CompiledCivicSystemReconciliation { - schema: "ghostlight.civic_system_manifest.v1".into(), - jurisdiction_location_id: "refuge".into(), - governing_institution_ids: BTreeSet::new(), - resident_population_ids: BTreeSet::new(), - public_authority_fact_ids: BTreeSet::new(), - public_selection_fact_ids: BTreeSet::new(), - public_resource_fact_ids: BTreeSet::new(), - public_redress_fact_ids: BTreeSet::new(), - political_relation_ids: BTreeSet::new(), - }, - } - } - - #[test] - fn civic_verifier_schema_declares_its_deterministic_rationale_bounds() { - let schema = serde_json::to_value(schema_for!(CivicSystemVerification)).unwrap(); - let rationale = &schema["properties"]["rationale"]; - - assert_eq!(rationale["minLength"], 1); - assert_eq!(rationale["maxLength"], 1_000); - } - - #[test] - fn civic_repair_diagnostic_leads_with_every_failed_dimension() { - let verdict = CivicSystemVerification { - authority_legible: true, - selection_or_succession_legible: true, - public_resources_legible: true, - redress_legible: true, - institutional_relations_coherent: true, - resident_answer_grounded: true, - political_form_distinct_or_deliberately_shared: true, - opposed_interests_have_distinct_means: true, - constituencies_cross_boundaries_or_local_homogeneity_justified: false, - explicit_request_constraints_satisfied: true, - public_names_do_not_repeat_an_overused_template: true, - candidate_text_intact: false, - rationale: "The late civic dimensions failed despite an otherwise legible apparatus." - .into(), - }; - - let diagnostic = civic_verification_semantic_diagnostic(&verdict); - - assert!(diagnostic.starts_with("{\"failed_checks\":[")); - assert!( - diagnostic.contains("constituencies_cross_boundaries_or_local_homogeneity_justified") - ); - assert!(diagnostic.contains("candidate_text_intact")); - assert!(!diagnostic.contains("authority_legible")); - } - - #[test] - fn destination_reconciliation_edit_batch_is_transactional() { - let mut seed = civic_reconciliation_seed(vec![]); - seed.facts.push(WorldFact { - id: "fact:original".into(), - statement: "The original fact remains intact.".into(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["refuge".into()]), - }); - let mut draft = civic_reconciliation_draft(&seed).unwrap(); - let original = draft.clone(); - let error = apply_destination_reconciliation_edits( - &mut draft, - vec![ - DestinationReconciliationEdit::ReplaceFact { - fact_index: 0, - fact: WorldFact { - id: "fact:changed".into(), - statement: "This edit must roll back with its batch.".into(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["refuge".into()]), - }, - }, - DestinationReconciliationEdit::SetResidentFactKnowledge { - population_id: "invented-population".into(), - fact_ids: BTreeSet::new(), - }, - ], - ) - .unwrap_err(); - - assert!(error.to_string().contains("unknown frozen population")); - assert_eq!(draft, original); - } - - #[test] - fn destination_reconciliation_action_cannot_smuggle_frozen_location_edits() { - let error = - serde_json::from_value::(serde_json::json!({ - "tool":"revise_and_validate", - "edits":[{ - "edit":"update_institution", - "update":{ - "institution_id":"refuge-duty-council", - "resources":[], - "posture":"wait", - "location_ids":["elsewhere"], - "facets":{ - "geography":[], - "ideology":[], - "authority":[], - "economy_role":[], - "species_body":[], - "information":[] - }, - "information_channels":[] - } - }] - })) - .unwrap_err(); - - assert!(error.to_string().contains("unknown field `location_ids`")); - } - - #[test] - fn one_reconciliation_edit_stays_small_against_a_large_private_workbench() { - let mut seed = civic_reconciliation_seed(vec![]); - seed.facts = (0..32) - .map(|index| WorldFact { - id: format!("fact:large:{index}"), - statement: format!("Fact {index}: {}", "weathered civic texture ".repeat(20)), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["refuge".into()]), - }) - .collect(); - let draft = civic_reconciliation_draft(&seed).unwrap(); - let action = DestinationReconciliationToolAction { - tool: DestinationReconciliationTool::ReviseAndValidate, - edits: Some(vec![DestinationReconciliationEdit::ReplaceFact { - fact_index: 31, - fact: WorldFact { - id: "fact:large:31".into(), - statement: "A corrected compact fact.".into(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["refuge".into()]), - }, - }]), - }; - let draft_bytes = serde_json::to_vec(&draft).unwrap(); - let action_bytes = serde_json::to_vec(&action).unwrap(); - let mut schema = - serde_json::to_value(schema_for!(DestinationReconciliationToolAction)).unwrap(); - constrain_civic_reconciliation_action_schema(&mut schema, &seed).unwrap(); - - assert!(draft_bytes.len() > 15_000); - assert!(action_bytes.len() * 10 < draft_bytes.len()); - assert!( - !serde_json::to_string(&schema) - .unwrap() - .contains("CompiledDestinationReconciliation") - ); - } - - #[test] - fn civic_reconciliation_cannot_substitute_a_frozen_institution() { - let campaign = seed_to_campaign(private_actor_test_seed(), &[]).unwrap(); - let seed = civic_reconciliation_seed(vec![CompiledDestinationInstitution { - id: "refuge-duty-council".into(), - name: "Refuge Duty Council".into(), - resources: vec!["closure seal".into()], - goals: vec!["keep admissions within storm capacity".into()], - posture: "admit by witnessed capacity ruling".into(), - location_ids: BTreeSet::from(["refuge".into()]), - facets: CompiledAgencyFacets { - geography: BTreeSet::new(), - ideology: BTreeSet::new(), - authority: BTreeSet::new(), - economy_role: BTreeSet::new(), - species_body: BTreeSet::new(), - information: BTreeSet::new(), - }, - information_channels: BTreeSet::new(), - }]); - let reconciliation = empty_civic_reconciliation(vec![CompiledCivicInstitutionUpdate { - institution_id: "invented-council".into(), - resources: vec![], - posture: "claims the refuge".into(), - facets: CompiledAgencyFacets { - geography: BTreeSet::new(), - ideology: BTreeSet::new(), - authority: BTreeSet::new(), - economy_role: BTreeSet::new(), - species_body: BTreeSet::new(), - information: BTreeSet::new(), - }, - information_channels: BTreeSet::new(), - }]); - - let error = apply_civic_reconciliation(&campaign, &seed, reconciliation).unwrap_err(); - assert!( - error - .to_string() - .contains("must update every frozen candidate institution exactly once") - ); - } - - #[test] - fn civic_reconciliation_action_schema_never_exposes_the_complete_workbench() { - let campaign = seed_to_campaign(private_actor_test_seed(), &[]).unwrap(); - let seed = civic_reconciliation_seed(vec![]); - let mut schema = - serde_json::to_value(schema_for!(DestinationReconciliationToolAction)).unwrap(); - - constrain_civic_reconciliation_action_schema(&mut schema, &seed).unwrap(); - crate::model_connector::project_strict_responses_schema(&mut schema).unwrap(); - - let schema_text = serde_json::to_string(&schema).unwrap(); - assert_eq!(schema["type"], "object"); - assert!(!schema_text.contains("CompiledDestinationReconciliation")); - assert!(schema_text.contains("validate_current")); - assert!(schema_text.contains("revise_and_validate")); - assert!(schema["$defs"]["CompiledCivicInstitutionUpdate"]["properties"] - ["institution_id"]["enum"] - .is_null()); - let corrected = - apply_civic_reconciliation(&campaign, &seed, empty_civic_reconciliation(vec![])) - .unwrap(); - assert!(corrected.institutions.is_empty()); - } - - #[tokio::test] - async fn repeated_broad_civic_rejection_never_enters_the_narrow_reconciler() { - let model = Arc::new(DestinationElaborationModel { - saw_branch_assumption_boundary: AtomicBool::new(false), - saw_balanced_civic_reconciliation: AtomicBool::new(false), - civic_verification_calls: AtomicUsize::new(0), - civic_verification_rejections: 2, - reconciliation_steals_non_civic_fact: false, - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let mut seed = private_actor_test_seed(); - seed.player.location_id = "convoy-staging".into(); - seed.opening_narration = "The convoy waits in the rain.".into(); - let campaign = seed_to_campaign(seed, &[]).unwrap(); - - let error = compiler - .compile_destination( - &campaign, - "convoy-staging", - "a playable storm refuge with ordinary repair and admission procedure", - ) - .await - .unwrap_err(); - let failure = error - .downcast_ref::() - .expect("terminal destination failure preserves model receipts"); - let civic_receipts = failure - .model_receipts - .iter() - .filter(|receipt| receipt.stage == "destination_civic_verification") - .collect::>(); - let compile_receipts = failure - .model_receipts - .iter() - .filter(|receipt| receipt.stage == "destination_compile") - .collect::>(); - let reconciliation_receipts = failure - .model_receipts - .iter() - .filter(|receipt| receipt.stage == "destination_reconciliation_agent_action") - .collect::>(); - - assert!( - !model - .saw_balanced_civic_reconciliation - .load(Ordering::SeqCst) - ); - assert_eq!(compile_receipts.len(), 2); - assert!(reconciliation_receipts.is_empty()); - assert_eq!(civic_receipts.len(), 2); - assert_eq!(civic_receipts[0].validation_result, "semantic_invalid"); - assert_eq!(civic_receipts[1].validation_result, "semantic_invalid"); - assert!( - error - .to_string() - .contains("destination civic verifier rejected the regenerated candidate") - ); - } - - #[tokio::test] - async fn destination_local_civic_profile_validation_uses_one_balanced_reconciliation() { - let model = Arc::new(DestinationElaborationModel { - saw_branch_assumption_boundary: AtomicBool::new(false), - saw_balanced_civic_reconciliation: AtomicBool::new(false), - civic_verification_calls: AtomicUsize::new(0), - civic_verification_rejections: 0, - reconciliation_steals_non_civic_fact: false, - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let mut seed = private_actor_test_seed(); - seed.player.location_id = "convoy-staging".into(); - seed.opening_narration = "The convoy waits in the rain.".into(); - let campaign = seed_to_campaign(seed, &[]).unwrap(); - - let (preview, receipts) = compiler - .compile_destination( - &campaign, - "convoy-staging", - "a malformed civic profile fixture requiring a bounded channel repair", - ) - .await - .unwrap(); - let DestinationCompilationPreview::RegionExpansion(preview) = preview else { - panic!("new destination must produce a region expansion preview") - }; - let compile_receipts = receipts - .iter() - .filter(|receipt| receipt.stage == "destination_compile") - .collect::>(); - let reconciliation_receipts = receipts - .iter() - .filter(|receipt| receipt.stage == "destination_reconciliation_agent_action") - .collect::>(); - let verification_receipts = receipts - .iter() - .filter(|receipt| receipt.stage == "destination_civic_verification") - .collect::>(); - - assert!( - model - .saw_balanced_civic_reconciliation - .load(Ordering::SeqCst) - ); - assert_eq!(compile_receipts.len(), 1); - assert_eq!(compile_receipts[0].validation_result, "semantic_invalid"); - assert_eq!(reconciliation_receipts.len(), 1); - assert_eq!(reconciliation_receipts[0].model, MODEL_BALANCED); - assert!( - reconciliation_receipts[0] - .source_receipt_ids - .iter() - .any(|source| source == compile_receipts[0].storage_key()) - ); - assert_eq!(verification_receipts.len(), 1); - assert_eq!(verification_receipts[0].validation_result, "valid"); - assert!( - verification_receipts[0] - .source_receipt_ids - .iter() - .any(|source| source == reconciliation_receipts[0].storage_key()) - ); - let duty_profile = preview - .expansion - .institution_profiles - .iter() - .find(|profile| profile.subject_id == "refuge-duty-council") - .expect("reconciled duty council keeps its agency profile"); - assert_eq!( - duty_profile.information_channels, - BTreeSet::from(["public duty leaf".into()]) - ); - let duty = preview - .expansion - .institutions - .iter() - .find(|institution| institution.id == "refuge-duty-council") - .expect("reconciled duty council keeps its frozen identity"); - assert_eq!(duty.name, "Refuge Duty Council"); - assert_eq!( - duty.goals, - ["keep admissions within storm capacity".to_owned()] - ); - assert!(preview.expansion.facts.iter().any(|fact| { - fact.id == "fact:refuge_selection" - && fact.statement - == "Wardens select two duty councillors by witnessed lot after each storm season." - })); - assert!(preview.expansion.facts.iter().any(|fact| { - fact.id == "fact:refuge_resources" - && fact.statement - == "The stores office receives repair boards through disclosed convoy levies." - })); - } - - #[tokio::test] - async fn destination_reconciliation_agent_repairs_a_second_exact_fact_collision() { - let model = Arc::new(CorrectingCivicReconciliationModel { - delegate: DestinationElaborationModel { - saw_branch_assumption_boundary: AtomicBool::new(false), - saw_balanced_civic_reconciliation: AtomicBool::new(false), - civic_verification_calls: AtomicUsize::new(0), - civic_verification_rejections: 0, - reconciliation_steals_non_civic_fact: false, - }, - reconciliation_calls: AtomicUsize::new(0), - saw_reconciliation_correction: AtomicBool::new(false), - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let mut seed = private_actor_test_seed(); - seed.player.location_id = "convoy-staging".into(); - seed.opening_narration = "The convoy waits in the rain.".into(); - let campaign = seed_to_campaign(seed, &[]).unwrap(); - - let (preview, receipts) = compiler - .compile_destination( - &campaign, - "convoy-staging", - "a candidate fact collision fixture with ordinary repair and admission procedure", - ) - .await - .unwrap(); - let compile_receipts = receipts - .iter() - .filter(|receipt| receipt.stage == "destination_compile") - .collect::>(); - let reconciliation_receipts = receipts - .iter() - .filter(|receipt| receipt.stage == "destination_reconciliation_agent_action") - .collect::>(); - let verification_receipts = receipts - .iter() - .filter(|receipt| receipt.stage == "destination_civic_verification") - .collect::>(); - let preparation_receipt_ids = receipts - .iter() - .filter(|receipt| { - matches!( - receipt.stage.as_str(), - "destination_identity_resolution" | "destination_retrieval_plan" - ) - }) - .map(|receipt| receipt.storage_key()) - .collect::>(); - - assert_eq!(model.reconciliation_calls.load(Ordering::SeqCst), 2); - assert!(model.saw_reconciliation_correction.load(Ordering::SeqCst)); - assert_eq!(preparation_receipt_ids.len(), 2); - assert_eq!(compile_receipts.len(), 1); - assert!(preparation_receipt_ids.iter().all(|receipt_id| { - compile_receipts[0] - .source_receipt_ids - .iter() - .any(|source| source == *receipt_id) - })); - assert_eq!(reconciliation_receipts.len(), 2); - assert!(preparation_receipt_ids.iter().all(|receipt_id| { - reconciliation_receipts[0] - .source_receipt_ids - .iter() - .any(|source| source == *receipt_id) - })); - assert_eq!(reconciliation_receipts[0].validation_result, "valid"); - assert_eq!(reconciliation_receipts[1].validation_result, "valid"); - assert!(reconciliation_receipts.windows(2).all(|pair| { - pair[1] - .source_receipt_ids - .iter() - .any(|source| source == pair[0].storage_key()) - })); - assert_eq!(verification_receipts.len(), 1); - assert_eq!(verification_receipts[0].validation_result, "valid"); - assert!( - verification_receipts[0] - .source_receipt_ids - .iter() - .any(|source| source == reconciliation_receipts[1].storage_key()) - ); - let DestinationCompilationPreview::RegionExpansion(preview) = preview else { - panic!("new destination must produce a region expansion preview") - }; - let admission_evidence_ids = preview - .evidence_receipts - .iter() - .map(|receipt| receipt.id.as_str()) - .collect::>(); - assert!(!admission_evidence_ids.is_empty()); - let reconciliation_receipt_ids = reconciliation_receipts - .iter() - .map(|receipt| receipt.storage_key()) - .collect::>(); - for evidence_receipt_id in preview - .expansion - .population_profiles - .iter() - .chain(preview.expansion.institution_profiles.iter()) - .flat_map(|profile| profile.evidence_receipt_ids.iter()) - .chain( - preview - .expansion - .migration_relations - .iter() - .chain(preview.expansion.local_relations.iter()) - .flat_map(|relation| relation.evidence_receipt_ids.iter()), - ) - { - assert!(admission_evidence_ids.contains(evidence_receipt_id.as_str())); - assert!(!reconciliation_receipt_ids.contains(evidence_receipt_id.as_str())); - } - let duty = preview - .expansion - .institutions - .iter() - .find(|institution| institution.id == "refuge-duty-council") - .expect("reconciliation preserves the frozen duty council"); - assert_eq!(duty.name, "Refuge Duty Council"); - assert_eq!( - duty.goals, - ["keep admissions within storm capacity".to_owned()] - ); - } - - #[tokio::test] - async fn inhabited_destination_missing_civic_manifest_never_recompiles() { - let model = Arc::new(DestinationElaborationModel { - saw_branch_assumption_boundary: AtomicBool::new(false), - saw_balanced_civic_reconciliation: AtomicBool::new(false), - civic_verification_calls: AtomicUsize::new(0), - civic_verification_rejections: 0, - reconciliation_steals_non_civic_fact: false, - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let mut seed = private_actor_test_seed(); - seed.player.location_id = "convoy-staging".into(); - seed.opening_narration = "The convoy waits in the rain.".into(); - let campaign = seed_to_campaign(seed, &[]).unwrap(); - - let error = compiler - .compile_destination( - &campaign, - "convoy-staging", - "a missing civic manifest fixture that must fail after one expensive candidate", - ) - .await - .unwrap_err(); - let failure = error - .downcast_ref::() - .expect("missing civic manifest must preserve the sole compiler receipt"); - let compile_receipts = failure - .model_receipts - .iter() - .filter(|receipt| receipt.stage == "destination_compile") - .collect::>(); - let reconciliation_receipts = failure - .model_receipts - .iter() - .filter(|receipt| receipt.stage == "destination_reconciliation_agent_action") - .collect::>(); - - assert!( - error.to_string().contains( - "inhabited destination cannot be reconciled without a frozen civic manifest" - ), - "{error:#}" - ); - assert_eq!(compile_receipts.len(), 1); - assert_eq!(compile_receipts[0].validation_result, "semantic_invalid"); - assert!(reconciliation_receipts.is_empty()); - assert_eq!(model.civic_verification_calls.load(Ordering::SeqCst), 0); - } - - #[tokio::test] - async fn destination_reconciliation_agent_cannot_rewrite_a_canonical_fact() { - let model = Arc::new(DestinationElaborationModel { - saw_branch_assumption_boundary: AtomicBool::new(false), - saw_balanced_civic_reconciliation: AtomicBool::new(false), - civic_verification_calls: AtomicUsize::new(0), - civic_verification_rejections: 0, - reconciliation_steals_non_civic_fact: true, - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let mut seed = private_actor_test_seed(); - seed.player.location_id = "convoy-staging".into(); - seed.opening_narration = "The convoy waits in the rain.".into(); - let mut campaign = seed_to_campaign(seed, &[]).unwrap(); - campaign.facts.insert( - "fact:canonical-storm-law".into(), - WorldFact { - id: "fact:canonical-storm-law".into(), - statement: "The storm law predates the refuge.".into(), - scope: FactScope::CanonBaseline, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["convoy-staging".into()]), - }, - ); - - let error = compiler - .compile_destination( - &campaign, - "convoy-staging", - "a candidate fact collision fixture with ordinary repair and admission procedure", - ) - .await - .unwrap_err(); - let failure = error - .downcast_ref::() - .expect("reconciliation failure must preserve its receipt"); - let reconciliation_receipts = failure - .model_receipts - .iter() - .filter(|receipt| receipt.stage == "destination_reconciliation_agent_action") - .collect::>(); - - assert!( - error.to_string().contains("fact_namespace_rejection") - && error.to_string().contains("existing_id") - && error.to_string().contains("fact:canonical-storm-law"), - "{error:#}" - ); - assert_eq!(reconciliation_receipts.len(), 4); - assert!( - reconciliation_receipts - .iter() - .all(|receipt| receipt.validation_result == "valid") - ); - assert!(reconciliation_receipts.windows(2).all(|pair| { - pair[1] - .source_receipt_ids - .iter() - .any(|source| source == pair[0].storage_key()) - })); - assert_eq!(model.civic_verification_calls.load(Ordering::SeqCst), 0); - } - - #[tokio::test] - async fn destination_compiler_rejects_semantically_empty_civic_machinery() { - let model = Arc::new(DestinationElaborationModel { - saw_branch_assumption_boundary: AtomicBool::new(false), - saw_balanced_civic_reconciliation: AtomicBool::new(false), - civic_verification_calls: AtomicUsize::new(0), - civic_verification_rejections: usize::MAX, - reconciliation_steals_non_civic_fact: false, - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let mut seed = private_actor_test_seed(); - seed.player.location_id = "convoy-staging".into(); - seed.opening_narration = "The convoy waits in the rain.".into(); - let campaign = seed_to_campaign(seed, &[]).unwrap(); - - let error = compiler - .compile_destination( - &campaign, - "convoy-staging", - "a playable storm refuge with ordinary repair and admission procedure", - ) - .await - .unwrap_err(); - - assert!( - error - .to_string() - .contains("destination civic verifier rejected the regenerated candidate"), - "{error:#}" - ); - let failure = error - .downcast_ref::() - .expect("terminal destination failure must preserve completed model receipts"); - let compile_receipts = failure - .model_receipts - .iter() - .filter(|receipt| receipt.stage == "destination_compile") - .collect::>(); - let civic_receipts = failure - .model_receipts - .iter() - .filter(|receipt| receipt.stage == "destination_civic_verification") - .collect::>(); - let reconciliation_receipts = failure - .model_receipts - .iter() - .filter(|receipt| receipt.stage == "destination_reconciliation_agent_action") - .collect::>(); - assert_eq!(compile_receipts.len(), 2); - assert!(reconciliation_receipts.is_empty()); - assert_eq!(civic_receipts.len(), 2); - assert!( - civic_receipts - .iter() - .all(|receipt| receipt.validation_result == "semantic_invalid") - ); - assert_eq!(model.civic_verification_calls.load(Ordering::SeqCst), 2); - assert!( - !model - .saw_balanced_civic_reconciliation - .load(Ordering::SeqCst) - ); - } - - fn harrow_campaign() -> Campaign { - let mut seed = private_actor_test_seed(); - seed.player.location_id = "convoy-staging".into(); - seed.locations[0].routes.push(CompiledRoute { - route_id: "route:staging_to_run".into(), - destination_id: "loc:veyr_run".into(), - distance: "down the drainage bypass".into(), - travel_minutes: 35, - }); - seed.locations.push(CompiledLocation { - id: "loc:veyr_run".into(), - name: "Lower Veyr Run".into(), - container_id: None, - routes: vec![ - CompiledRoute { - route_id: "route:run_to_staging".into(), - destination_id: "convoy-staging".into(), - distance: "up the drainage bypass".into(), - travel_minutes: 35, - }, - CompiledRoute { - route_id: "route:run_to_station".into(), - destination_id: "loc:harrow_station".into(), - distance: "along the anchored ascent".into(), - travel_minutes: 75, - }, - ], - persistent_features: vec!["disturbed iron anchors".into()], - }); - seed.locations.push(CompiledLocation { - id: "loc:harrow_station".into(), - name: "Harrow Station".into(), - container_id: None, - routes: vec![CompiledRoute { - route_id: "route:station_to_run".into(), - destination_id: "loc:veyr_run".into(), - distance: "back down the anchored ascent".into(), - travel_minutes: 75, - }], - persistent_features: vec!["abandoned road office".into()], - }); - seed_to_campaign(seed, &[]).unwrap() - } - - #[tokio::test] - async fn destination_compiler_elaborates_a_reachable_canonical_city_in_place() { - let model = Arc::new(ExistingDestinationModel { - calls: AtomicUsize::new(0), - saw_current_civic_context: AtomicBool::new(false), - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let campaign = harrow_campaign(); - - let (preview, receipts) = compiler - .compile_destination( - &campaign, - "convoy-staging", - "Visit Harrow Station and ask a local who they voted for Mayor.", - ) - .await - .unwrap(); - let DestinationCompilationPreview::LocalityElaboration(preview) = preview else { - panic!("existing destination must produce a locality elaboration preview") - }; - let expansion = &preview.elaboration.expansion; - assert_eq!(preview.elaboration.target_location_id, "loc:harrow_station"); - assert_eq!(expansion.origin_location_id, "loc:harrow_station"); - assert!( - expansion - .locations - .iter() - .all(|location| location.id != "loc:harrow_station") - ); - assert_eq!(expansion.institutions.len(), 2); - assert_eq!(expansion.civic_system.as_ref().unwrap().version, 0); - assert!( - !expansion - .civic_system - .as_ref() - .unwrap() - .semantic_verification_receipt_id - .is_empty() - ); - assert_eq!( - expansion.local_relations[0].kind, - AgencyRelationKind::Rivalry - ); - let selection = &expansion - .facts - .iter() - .find(|fact| fact.id == "fact:harrow_selection") - .unwrap() - .statement; - assert!(selection.contains("Selka Vey")); - assert!(selection.contains("Oren Vale")); - assert!( - expansion.populations[0] - .shared_knowledge - .contains(selection) - ); - assert_eq!( - receipts - .iter() - .map(|receipt| receipt.stage.as_str()) - .collect::>(), - vec![ - "destination_identity_resolution", - "destination_retrieval_plan", - "destination_compile", - "destination_civic_verification" - ] - ); - assert_eq!(model.calls.load(Ordering::SeqCst), 4); - } - - #[tokio::test] - async fn locality_elaboration_reuses_and_deepens_its_persisted_civic_apparatus() { - let model = Arc::new(ExistingDestinationModel { - calls: AtomicUsize::new(0), - saw_current_civic_context: AtomicBool::new(false), - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let initial = harrow_campaign(); - let (first, first_receipts) = compiler - .compile_destination( - &initial, - "convoy-staging", - "Visit Harrow Station and ask a local who they voted for Mayor.", - ) - .await - .unwrap(); - let DestinationCompilationPreview::LocalityElaboration(first) = first else { - panic!("first pass must elaborate Harrow in place") - }; - let first_evidence_queries = first - .evidence_receipts - .iter() - .map(|receipt| receipt.query_hash.clone()) - .collect::>(); - let dir = tempfile::tempdir().unwrap(); - let store = - crate::persistence::CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = crate::kernel::WorldKernel::start(store); - kernel - .command(crate::domain::WorldCommand::CreateCampaign { - campaign: initial, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let first_commit = kernel - .command(crate::domain::WorldCommand::ElaborateLocality { - expected_revision: first.expected_revision, - elaboration: first.elaboration, - evidence_receipts: first.evidence_receipts, - canon_candidates: first.canon_candidates, - model_stage_receipts: first_receipts, - }) - .await - .unwrap(); - let crate::kernel::CommandResult::Committed { - campaign: first_campaign, - .. - } = first_commit - else { - panic!("first civic pass must commit") - }; - - let (second, second_receipts) = compiler - .compile_destination( - &first_campaign, - "convoy-staging", - "Investigate the fight over Harrow's berth dues and who is hiding the ledger.", - ) - .await - .unwrap(); - let DestinationCompilationPreview::LocalityElaboration(second) = second else { - panic!("second pass must deepen Harrow in place") - }; - assert!( - second - .evidence_receipts - .iter() - .any(|receipt| first_evidence_queries.contains(&receipt.query_hash)) - ); - assert_eq!(second.elaboration.expansion.populations.len(), 0); - assert_eq!(second.elaboration.expansion.institutions.len(), 1); - let manifest = second.elaboration.expansion.civic_system.as_ref().unwrap(); - assert_eq!(manifest.version, 1); - assert!( - manifest - .governing_institution_ids - .contains("harrow-mayoral-office") - ); - assert!( - manifest - .governing_institution_ids - .contains("harrow-audit-chamber") - ); - assert!( - manifest - .public_resource_fact_ids - .contains("fact:harrow_resources") - ); - assert!( - manifest - .public_resource_fact_ids - .contains("fact:harrow_hidden_levy") - ); - - let second_commit = kernel - .command(crate::domain::WorldCommand::ElaborateLocality { - expected_revision: second.expected_revision, - elaboration: second.elaboration, - evidence_receipts: second.evidence_receipts, - canon_candidates: second.canon_candidates, - model_stage_receipts: second_receipts, - }) - .await - .unwrap(); - let crate::kernel::CommandResult::Committed { - campaign: second_campaign, - .. - } = second_commit - else { - panic!("second civic pass must commit") - }; - assert_eq!( - second_campaign.civic_systems["loc:harrow_station"].version, - 1 - ); - assert_eq!(second_campaign.institutions.len(), 3); - assert!( - second_campaign.gestalts["harrow-residents"] - .shared_knowledge - .iter() - .any(|fact| fact.contains("unvoted emergency courier fund")) - ); - assert!(model.saw_current_civic_context.load(Ordering::SeqCst)); - assert_eq!(model.calls.load(Ordering::SeqCst), 8); - } - - #[tokio::test] - async fn selected_role_capabilities_and_obligations_survive_world_compilation() { - let compiler = WorldCompiler::new( - vault(), - Arc::new(CompilerModel { - invalid_route: false, - }), - "flash", - "pro", - ); - let (preview, _) = compiler - .compile_selected(SelectedStart { - campaign_name: "Selected role".into(), - opening: OpeningSuggestion { - id: "opening".into(), - title: "Opening".into(), - era: "fixture".into(), - place: "yard".into(), - pressure: "A gate is closed".into(), - player_hook: "Learn why".into(), - evidence_receipt_ids: vec![], - }, - role: RoleSuggestion { - id: "courier".into(), - name: "Courier".into(), - premise: "Carry a disputed manifest.".into(), - capabilities: vec!["route knowledge".into()], - obligations: vec!["deliver the manifest".into()], - evidence_receipt_ids: vec![], - }, - }) - .await - .unwrap(); - let player = &preview.campaign.actors[&preview.campaign.player_actor_id]; - assert!(player.capabilities.contains("route knowledge")); - assert!(player.obligations.contains("deliver the manifest")); - assert!( - preview - .branch_assumptions - .iter() - .any(|assumption| assumption.contains("Courier")) - ); - } - - #[test] - fn evidence_projection_carries_exact_receipt_ids_and_deduplicates_witnesses() { - let witness = SourceWitness { - source_id: "AetheriaLore:test.md".into(), - exact_locator: "test.md:1-2".into(), - content_hash: "sha256:test".into(), - excerpt: "A stable witnessed place.".into(), - authority_lane: "AetheriaLore".into(), - temporal_scope: "fixture".into(), - }; - let text = evidence_text(&[ - VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: "vault:receipt-one".into(), - provider: "fixture".into(), - query_hash: "sha256:one".into(), - witnesses: vec![witness.clone()], - retrieved_at: Utc::now(), - }, - VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: "vault:receipt-two".into(), - provider: "fixture".into(), - query_hash: "sha256:two".into(), - witnesses: vec![witness], - retrieved_at: Utc::now(), - }, - ]); - assert_eq!(text.matches("A stable witnessed place.").count(), 1); - assert!(text.contains("receipt_id=vault:receipt-one")); - assert!(!text.contains("receipt_id=vault:receipt-two")); - } - - #[test] - fn world_seed_context_contains_only_direct_evidence() { - let direct = VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: "vault:direct".into(), - provider: "fixture".into(), - query_hash: "sha256:direct".into(), - witnesses: vec![SourceWitness { - source_id: "AetheriaLore:place.md".into(), - exact_locator: "place.md:1".into(), - content_hash: "sha256:place".into(), - excerpt: "The requested station exists.".into(), - authority_lane: "AetheriaLore".into(), - temporal_scope: "fixture".into(), - }], - retrieved_at: Utc::now(), - }; - let nearby_story = VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: "vault:story".into(), - provider: "fixture".into(), - query_hash: "sha256:story".into(), - witnesses: vec![SourceWitness { - source_id: "AetheriaLore:unrelated-story.md".into(), - exact_locator: "unrelated-story.md:1".into(), - content_hash: "sha256:story".into(), - excerpt: "An unrelated named cast has a crisis nearby.".into(), - authority_lane: "AetheriaLore".into(), - temporal_scope: "fixture".into(), - }], - retrieved_at: Utc::now(), - }; - let receipts = vec![direct, nearby_story]; - let coverage = vec![ - EvidenceCoverage { - source_id: "AetheriaLore:place.md".into(), - lane: EvidenceUseLane::DirectSeed, - rationale: "Directly grounds the requested station.".into(), - }, - EvidenceCoverage { - source_id: "AetheriaLore:unrelated-story.md".into(), - lane: EvidenceUseLane::SettingBackground, - rationale: "The incident offers setting color but is not current.".into(), - }, - ]; - let text = direct_seed_evidence_text(&receipts, &coverage); - assert!(text.contains("The requested station exists.")); - assert!(!text.contains("unrelated named cast")); - assert_eq!( - receipt_ids_for_coverage(&receipts, &coverage), - vec!["vault:direct"] - ); - } - - #[test] - fn narrative_and_fixture_documents_cannot_seed_a_new_branch() { - let make_receipt = |id: &str, lane: &str, excerpt: &str| VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: format!("vault:{id}"), - provider: "fixture".into(), - query_hash: format!("sha256:{id}"), - witnesses: vec![SourceWitness { - source_id: format!("AetheriaLore:{id}"), - exact_locator: id.into(), - content_hash: format!("sha256:{id}"), - excerpt: excerpt.into(), - authority_lane: lane.into(), - temporal_scope: "fixture".into(), - }], - retrieved_at: Utc::now(), - }; - let receipts = vec![ - make_receipt( - "mars.md", - "aetheria.canon_worldbuilding", - "Zhestokost holds fortified nodes on Mars.", - ), - make_receipt( - "first-exodus.md", - "aetheria.legacy_story", - "Blackbox Aviary 3C contains Kesh and Dr. Maela Voss.", - ), - make_receipt( - "corvid.branch.json", - "aetheria.fixture_artifact", - "The interactive fixture repeats Blackbox Aviary 3C.", - ), - ]; - let coverage = receipts - .iter() - .map(|receipt| EvidenceCoverage { - source_id: receipt.witnesses[0].source_id.clone(), - lane: EvidenceUseLane::DirectSeed, - rationale: "classifier proposed direct use".into(), - }) - .collect::>(); - - let text = direct_seed_evidence_text(&receipts, &coverage); - assert!(text.contains("Zhestokost holds fortified nodes on Mars")); - assert!(!text.contains("Blackbox Aviary 3C")); - assert_eq!( - receipt_ids_for_coverage(&receipts, &coverage), - vec!["vault:mars.md"] - ); - - let global = canonical_worldbuilding_receipts(&receipts); - assert_eq!(global.len(), 1); - assert_eq!(global[0].id, "vault:mars.md"); - } - - #[test] - fn agency_compile_schema_exposes_relation_strength_domain() { - let schema = serde_json::to_value(schema_for!(CompiledAgencySkeleton)).unwrap(); - let serialized = serde_json::to_string(&schema).unwrap(); - assert!(serialized.contains("\"minimum\":1")); - assert!(serialized.contains("\"maximum\":100")); - } - - #[test] - fn global_agency_claims_must_be_short_exact_source_witnesses() { - let receipts = vec![VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: "vault:power".into(), - provider: "fixture".into(), - query_hash: "sha256:power".into(), - witnesses: vec![SourceWitness { - source_id: "AetheriaLore:powers.md".into(), - exact_locator: "powers.md:1".into(), - content_hash: "sha256:power".into(), - excerpt: "Pan-Solar Consortium coordinates interplanetary logistics.".into(), - authority_lane: "AetheriaLore".into(), - temporal_scope: "fixture".into(), - }], - retrieved_at: Utc::now(), - }]; - let valid = ExtractedGlobalAgencyCatalog { - institutions: vec![ExtractedRemoteInstitution { - name: "Pan-Solar Consortium".into(), - supporting_claims: vec![ - "Pan-Solar Consortium coordinates interplanetary logistics.".into(), - ], - }], - gaps: vec![], - }; - let (valid, gaps) = ground_global_agency_catalog(valid, &receipts).unwrap(); - assert_eq!(valid.institutions.len(), 1); - assert_eq!( - valid.institutions[0].evidence_receipt_ids, - vec!["vault:power"] - ); - assert!(gaps.is_empty()); - - let invented = ExtractedGlobalAgencyCatalog { - institutions: vec![ExtractedRemoteInstitution { - name: "Pan-Solar Consortium".into(), - supporting_claims: vec![ - "Pan-Solar Consortium secretly controls every government.".into(), - ], - }], - gaps: vec![], - }; - let (grounded, gaps) = ground_global_agency_catalog(invented, &receipts).unwrap(); - assert!(grounded.institutions.is_empty()); - assert_eq!(gaps.len(), 1); - assert!(grounded.gaps[0].contains("1 remote agency candidates")); - } - - #[test] - fn global_agency_capacity_applies_after_grounding() { - let excerpt = (0..33) - .map(|index| format!("Institution {index} protects route {index}.")) - .collect::>() - .join("\n"); - let receipts = vec![VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: "vault:many-powers".into(), - provider: "fixture".into(), - query_hash: "sha256:many-powers".into(), - witnesses: vec![SourceWitness { - source_id: "AetheriaLore:many-powers.md".into(), - exact_locator: "many-powers.md:1-33".into(), - content_hash: "sha256:many-powers".into(), - excerpt, - authority_lane: "aetheria.canon_worldbuilding".into(), - temporal_scope: "fixture".into(), - }], - retrieved_at: Utc::now(), - }]; - let catalog = ExtractedGlobalAgencyCatalog { - institutions: (0..33) - .map(|index| ExtractedRemoteInstitution { - name: format!("Institution {index}"), - supporting_claims: vec![format!("Institution {index} protects route {index}.")], - }) - .collect(), - gaps: vec![], - }; - - let (grounded, private_gaps) = ground_global_agency_catalog(catalog, &receipts).unwrap(); - assert_eq!(grounded.institutions.len(), 32); - assert_eq!(grounded.institutions[0].name, "Institution 0"); - assert_eq!(grounded.institutions[31].name, "Institution 31"); - assert!(grounded.gaps.iter().any(|gap| gap.contains("capped at 32"))); - assert!( - private_gaps - .iter() - .any(|gap| gap.contains("exceeded the 32-institution")) - ); - } - - #[test] - fn global_agency_schema_allows_bounded_pre_grounding_candidates() { - let schema = serde_json::to_value(schema_for!(ExtractedGlobalAgencyCatalog)).unwrap(); - assert_eq!(schema["properties"]["institutions"]["maxItems"], 64); - } - - #[test] - fn strategic_doctrine_requires_exact_coverage_and_classifies_canon_compatibility() { - let grounded = vec![GroundedRemoteInstitution { - name: "Fixture Council".into(), - supporting_claims: vec!["The Fixture Council maintains the route.".into()], - evidence_receipt_ids: vec!["vault:council".into()], - }]; - let doctrine = StrategicDoctrineCatalog { - institutions: vec![SynthesizedRemoteInstitution { - name: "Fixture Council".into(), - strategic_doctrine: "Maintain the route as a durable responsibility.".into(), - }], - }; - validate_doctrine_catalog(&grounded, &doctrine).unwrap(); - let incompatible = StrategicDoctrineVerification { - verdicts: vec![StrategicDoctrineVerdict { - name: "Fixture Council".into(), - compatible_with_canon: false, - rationale: "Abandoning the route contradicts its maintenance anchor.".into(), - }], - }; - let incompatible = validate_doctrine_verification(&grounded, &incompatible).unwrap(); - assert_eq!(incompatible.len(), 1); - assert_eq!(incompatible[0].name, "Fixture Council"); - - let compatible = StrategicDoctrineVerification { - verdicts: vec![StrategicDoctrineVerdict { - name: "Fixture Council".into(), - compatible_with_canon: true, - rationale: "Convoy permits are compatible branch-local operating detail.".into(), - }], - }; - assert!( - validate_doctrine_verification(&grounded, &compatible) - .unwrap() - .is_empty() - ); - } - - #[test] - fn compatible_remote_doctrines_retain_every_institution_and_surface_branch_assumptions() { - let grounded = GroundedGlobalAgencyCatalog { - institutions: vec![ - GroundedRemoteInstitution { - name: "Fixture Council".into(), - supporting_claims: vec!["The Fixture Council maintains the route.".into()], - evidence_receipt_ids: vec!["vault:council".into()], - }, - GroundedRemoteInstitution { - name: "Witness Guild".into(), - supporting_claims: vec!["The Witness Guild records public crossings.".into()], - evidence_receipt_ids: vec!["vault:guild".into()], - }, - ], - gaps: vec!["The exact horizon remains uncertain.".into()], - }; - let synthesized = StrategicDoctrineCatalog { - institutions: vec![ - SynthesizedRemoteInstitution { - name: "Fixture Council".into(), - strategic_doctrine: - "Maintain the route through repair crews and convoy permits.".into(), - }, - SynthesizedRemoteInstitution { - name: "Witness Guild".into(), - strategic_doctrine: "Record public crossings.".into(), - }, - ], - }; - let compiled = lower_compatible_doctrine_catalog(grounded, synthesized); - assert_eq!(compiled.institutions.len(), 2); - assert_eq!(compiled.institutions[0].name, "Fixture Council"); - assert_eq!( - compiled.institutions[0].evidence_receipt_ids, - vec!["vault:council"] - ); - let mut seed = private_actor_test_seed(); - let (evidence, assumptions) = merge_global_agency_catalog(&mut seed, compiled).unwrap(); - assert_eq!(evidence.len(), 2); - assert_eq!(assumptions.len(), 3); - assert!(assumptions.iter().any(|assumption| { - assumption.contains("Campaign-local operational doctrine for Fixture Council") - && assumption.contains("convoy permits") - })); - assert!(assumptions.iter().any(|assumption| { - assumption == "Global agency coverage limit: The exact horizon remains uncertain." - })); - assert_eq!(seed.institutions.len(), 2); - } - - #[test] - fn material_gap_contract_requires_an_exact_blocked_premise_and_evidence_ownership() { - let mut gap = CompiledMaterialGap { - kind: CompiledMaterialGapKind::UnanchoredRequestedBaseline, - summary: "The requested canon office has no anchored identity.".into(), - premise_clause: "The opening must use the canonical Winter Office.".into(), - blocked_choice: "Name the intended canon office or admit a branch-local office.".into(), - evidence_receipt_ids: vec![], - }; - validate_compiled_material_gaps(&[gap.clone()], &[]).unwrap(); - - gap.kind = CompiledMaterialGapKind::ContradictoryCanonBaselines; - assert!( - validate_compiled_material_gaps(&[gap.clone()], &[]) - .unwrap_err() - .to_string() - .contains("must cite supplied evidence") - ); - - gap.evidence_receipt_ids = vec!["unknown-receipt".into()]; - assert!( - validate_compiled_material_gaps(&[gap], &[]) - .unwrap_err() - .to_string() - .contains("unknown evidence receipt") - ); - } - - #[test] - fn shared_index_language_cannot_masquerade_as_an_institution_mandate() { - let receipts = vec![VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: "vault:movement-index".into(), - provider: "fixture".into(), - query_hash: "sha256:movement-index".into(), - witnesses: vec![SourceWitness { - source_id: "AetheriaLore:Aetheria/Worldbuilding/Movements/index.md".into(), - exact_locator: "Movements/index.md:1-4".into(), - content_hash: "sha256:movement-index".into(), - excerpt: - "Characteristic movements: Disciplinists, Pragmatists, selected Bio-Purists." - .into(), - authority_lane: "aetheria.canon_worldbuilding".into(), - temporal_scope: "fixture".into(), - }], - retrieved_at: Utc::now(), - }]; - let catalog = ExtractedGlobalAgencyCatalog { - institutions: ["Disciplinists", "Pragmatists", "Bio-Purists"] - .into_iter() - .map(|name| ExtractedRemoteInstitution { - name: name.into(), - supporting_claims: vec!["Characteristic movements: Disciplinists, Pragmatists, selected Bio-Purists." - .into()], - }) - .collect(), - gaps: vec![], - }; - - let (grounded, private_gaps) = ground_global_agency_catalog(catalog, &receipts).unwrap(); - assert!(grounded.institutions.is_empty()); - assert!(private_gaps.iter().any(|gap| gap.contains("Pragmatists"))); - } - - #[test] - fn dedicated_institution_document_may_supply_a_non_self_naming_tagline() { - assert!(source_document_names_institution( - "AetheriaLore:Aetheria/Worldbuilding/Factions/Powers/Major/Sol Dominion.md", - "Sol Dominion" - )); - assert!(!source_document_names_institution( - "AetheriaLore:Aetheria/Worldbuilding/Factions/Powers/Major/index.md", - "Sol Dominion" - )); - } - - #[test] - fn global_evidence_never_demotes_direct_local_authority() { - let global = vec![VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: "vault:global".into(), - provider: "fixture".into(), - query_hash: "sha256:global".into(), - witnesses: vec![SourceWitness { - source_id: "AetheriaLore:shared.md".into(), - exact_locator: "shared.md:1".into(), - content_hash: "sha256:shared".into(), - excerpt: "Shared source.".into(), - authority_lane: "AetheriaLore".into(), - temporal_scope: "fixture".into(), - }], - retrieved_at: Utc::now(), - }]; - let merged = merge_global_evidence_coverage( - vec![EvidenceCoverage { - source_id: "AetheriaLore:shared.md".into(), - lane: EvidenceUseLane::DirectSeed, - rationale: "Directly establishes the requested place.".into(), - }], - &global, - ); - assert_eq!(merged.len(), 1); - assert_eq!(merged[0].lane, EvidenceUseLane::DirectSeed); - } - - #[test] - fn opening_topology_requires_explicit_outbound_and_return_routes() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - let player_location = campaign.actors[&campaign.player_actor_id] - .location_id - .clone(); - campaign.locations.insert( - "annex".into(), - Location { - id: "annex".into(), - name: "Annex".into(), - container_id: Some(player_location.clone()), - routes: BTreeMap::new(), - persistent_features: vec!["A visible annex".into()], - }, - ); - - let disconnected = validate_opening_topology(&campaign).unwrap_err(); - assert!(disconnected.to_string().contains("unreachable")); - assert!( - disconnected - .to_string() - .contains("containment does not create implicit movement") - ); - - campaign - .locations - .get_mut(&player_location) - .unwrap() - .routes - .insert( - "route:annex".into(), - crate::domain::Route { - destination_id: "annex".into(), - distance: "near".into(), - travel_minutes: 5, - }, - ); - assert!( - validate_opening_topology(&campaign) - .unwrap_err() - .to_string() - .contains("no route chain back") - ); - - campaign.locations.get_mut("annex").unwrap().routes.insert( - "route:return".into(), - crate::domain::Route { - destination_id: player_location, - distance: "near".into(), - travel_minutes: 5, - }, - ); - validate_opening_topology(&campaign).unwrap(); - } - - #[tokio::test] - async fn compiler_refuses_dream_route_to_unknown_location() { - let compiler = WorldCompiler::new( - vault(), - Arc::new(CompilerModel { - invalid_route: true, - }), - "flash", - "pro", - ); - let result = compiler - .compile_custom(CustomStart { - campaign_name: "Test".into(), - who: "worker".into(), - where_: "yard".into(), - when: "fixture".into(), - goal: "learn".into(), - }) - .await; - assert!( - result - .unwrap_err() - .to_string() - .contains("references missing destination_id missing") - ); - } - - #[tokio::test] - async fn semantic_retry_receives_the_previous_candidates_structural_ids() { - let model = Arc::new(CorrectionAwareCompilerModel { - world_calls: AtomicUsize::new(0), - saw_previous_structure: AtomicBool::new(false), - }); - let compiler = WorldCompiler::new(vault(), model.clone(), "flash", "pro"); - let (_, receipts) = compiler - .compile_custom(CustomStart { - campaign_name: "Correction context".into(), - who: "worker".into(), - where_: "yard".into(), - when: "fixture".into(), - goal: "learn".into(), - }) - .await - .unwrap(); - assert!(model.saw_previous_structure.load(Ordering::SeqCst)); - let world_receipts = receipts - .iter() - .filter(|receipt| receipt.stage == "world_compile") - .collect::>(); - assert_eq!(world_receipts.len(), 2); - assert_eq!(world_receipts[0].validation_result, "semantic_invalid"); - assert_eq!(world_receipts[1].validation_result, "valid"); - } - - fn valid_region_expansion() -> crate::domain::RegionExpansion { - crate::domain::RegionExpansion { - origin_location_id: "center".into(), - origin_routes: BTreeMap::from([( - "route:center-annex".into(), - crate::domain::Route { - destination_id: "annex".into(), - distance: "near".into(), - travel_minutes: 10, - }, - )]), - locations: vec![Location { - id: "annex".into(), - name: "Annex".into(), - container_id: None, - routes: BTreeMap::from([( - "route:annex-center".into(), - crate::domain::Route { - destination_id: "center".into(), - distance: "near".into(), - travel_minutes: 10, - }, - )]), - persistent_features: vec!["sealed gate".into()], - }], - facts: vec![], - populations: vec![], - population_profiles: vec![], - migration_relations: vec![], - institutions: vec![], - institution_profiles: vec![], - local_relations: vec![], - civic_system: None, - } - } - - #[test] - fn civic_closure_correction_names_every_structural_defect() { - let campaign = crate::resolution::tests::campaign(0, 1); - let mut expansion = valid_region_expansion(); - expansion.civic_system = Some(CivicSystemManifest { - schema: "wrong.civic.schema".into(), - version: 7, - jurisdiction_location_id: "missing-jurisdiction".into(), - governing_institution_ids: BTreeSet::new(), - resident_population_ids: BTreeSet::new(), - public_authority_fact_ids: BTreeSet::new(), - public_selection_fact_ids: BTreeSet::new(), - public_resource_fact_ids: BTreeSet::new(), - public_redress_fact_ids: BTreeSet::new(), - political_relation_ids: BTreeSet::new(), - semantic_verification_receipt_id: String::new(), - }); - - let error = validate_region_expansion(&campaign, &expansion) - .unwrap_err() - .to_string(); - - assert!(error.contains("schema must be ghostlight.civic_system_manifest.v1")); - assert!(error.contains("version must be 0")); - assert!(error.contains("jurisdiction_location_id must name a known location")); - assert!(error.contains("candidate needs at least two governing institutions")); - assert!(error.contains("candidate needs at least one resident population")); - assert!(error.contains("public_authority_fact_ids must not be empty")); - assert!(error.contains("public_selection_fact_ids must not be empty")); - assert!(error.contains("public_resource_fact_ids must not be empty")); - assert!(error.contains("public_redress_fact_ids must not be empty")); - assert!(error.contains("political_relation_ids must not be empty")); - } - - #[test] - fn civic_closure_counts_declared_governors_not_available_institutions() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - campaign.civic_systems.insert( - "center".into(), - CivicSystemManifest { - schema: "ghostlight.civic_system_manifest.v1".into(), - version: 0, - jurisdiction_location_id: "center".into(), - governing_institution_ids: BTreeSet::from([ - "first-council".into(), - "second-council".into(), - ]), - resident_population_ids: BTreeSet::new(), - public_authority_fact_ids: BTreeSet::new(), - public_selection_fact_ids: BTreeSet::new(), - public_resource_fact_ids: BTreeSet::new(), - public_redress_fact_ids: BTreeSet::new(), - political_relation_ids: BTreeSet::new(), - semantic_verification_receipt_id: "receipt:previous".into(), - }, - ); - let mut expansion = valid_region_expansion(); - expansion.civic_system = Some(CivicSystemManifest { - schema: "ghostlight.civic_system_manifest.v1".into(), - version: 1, - jurisdiction_location_id: "center".into(), - governing_institution_ids: BTreeSet::from(["first-council".into()]), - resident_population_ids: BTreeSet::new(), - public_authority_fact_ids: BTreeSet::new(), - public_selection_fact_ids: BTreeSet::new(), - public_resource_fact_ids: BTreeSet::new(), - public_redress_fact_ids: BTreeSet::new(), - political_relation_ids: BTreeSet::new(), - semantic_verification_receipt_id: String::new(), - }); - - let error = validate_region_expansion(&campaign, &expansion) - .unwrap_err() - .to_string(); - - assert!(error.contains("candidate needs at least two governing institutions")); - } - - #[test] - fn region_expansion_requires_an_approved_round_trip() { - let campaign = crate::resolution::tests::campaign(0, 1); - let mut expansion = valid_region_expansion(); - validate_region_expansion(&campaign, &expansion).unwrap(); - expansion.origin_routes.clear(); - assert!( - validate_region_expansion(&campaign, &expansion) - .unwrap_err() - .to_string() - .contains("explicit route from the origin") - ); - } - - #[test] - fn region_expansion_route_keys_are_local_to_their_origin() { - let campaign = crate::resolution::tests::campaign(0, 1); - let mut expansion = valid_region_expansion(); - let outward = expansion - .origin_routes - .remove("route:center-annex") - .unwrap(); - expansion.origin_routes.insert("road".into(), outward); - let returning = expansion.locations[0] - .routes - .remove("route:annex-center") - .unwrap(); - expansion.locations[0] - .routes - .insert("road".into(), returning); - - validate_region_expansion(&campaign, &expansion).unwrap(); - } - - #[test] - fn region_expansion_rejects_a_disconnected_contained_location() { - let campaign = crate::resolution::tests::campaign(0, 1); - let mut expansion = valid_region_expansion(); - expansion.locations.push(Location { - id: "sealed-gallery".into(), - name: "Sealed Gallery".into(), - container_id: Some("annex".into()), - routes: BTreeMap::new(), - persistent_features: vec!["a locked internal gallery".into()], - }); - - let error = validate_region_expansion(&campaign, &expansion) - .unwrap_err() - .to_string(); - - assert!(error.contains("directed origin reachability")); - assert!(error.contains("sealed-gallery")); - } - - #[test] - fn inhabited_expansion_requires_connected_population_migration_topology() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - 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!["find voluntary settlement".into()], - pressures: vec![], - }, - ); - crate::resolution::ensure_agency_profiles(&mut campaign); - let mut expansion = valid_region_expansion(); - expansion.locations[0].id = "pass".into(); - expansion.locations[0].name = "Ridge Pass".into(); - expansion.locations[0].routes = BTreeMap::from([ - ( - "back".into(), - Route { - destination_id: "center".into(), - distance: "near".into(), - travel_minutes: 10, - }, - ), - ( - "onward".into(), - Route { - destination_id: "village".into(), - distance: "near".into(), - travel_minutes: 10, - }, - ), - ]); - expansion - .origin_routes - .values_mut() - .next() - .unwrap() - .destination_id = "pass".into(); - expansion.locations.push(Location { - id: "village".into(), - name: "Ridge Village".into(), - container_id: None, - routes: BTreeMap::from([( - "return".into(), - Route { - destination_id: "pass".into(), - distance: "near".into(), - travel_minutes: 10, - }, - )]), - persistent_features: vec!["assembly hall".into()], - }); - let statement = "The ridge assembly governs voluntary admission.".to_owned(); - expansion.facts.push(WorldFact { - id: "ridge-admission".into(), - statement: statement.clone(), - scope: FactScope::ProvisionalLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["village".into()]), - }); - expansion.populations.push(GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "ridge-households".into(), - name: "Ridge Households".into(), - version: 0, - home_location_id: "village".into(), - shared_capabilities: BTreeSet::from(["communal agriculture".into()]), - shared_knowledge: BTreeSet::from([statement]), - resources: BTreeSet::from(["shared kitchen".into()]), - goals: vec!["admit newcomers without surrendering local consent".into()], - pressures: vec!["winter capacity is finite".into()], - }); - expansion.population_profiles.push(AgencyProfile { - schema: "ghostlight.agency_profile.v1".into(), - id: "agency:ridge-households".into(), - subject_id: "ridge-households".into(), - subject_kind: AgencySubjectKind::Gestalt, - profile_version: 0, - collective_authority_id: Some("ridge-households".into()), - parent_subject_id: None, - active_leaf: true, - simulation_eligible: true, - facets: BTreeMap::from([ - (AgencyAxis::Geography, BTreeSet::from(["ridge".into()])), - (AgencyAxis::Ideology, BTreeSet::from(["consent".into()])), - (AgencyAxis::Authority, BTreeSet::from(["assembly".into()])), - ( - AgencyAxis::EconomyRole, - BTreeSet::from(["agriculture".into()]), - ), - (AgencyAxis::SpeciesBody, BTreeSet::from(["mixed".into()])), - (AgencyAxis::Information, BTreeSet::from(["local".into()])), - ]), - location_ids: BTreeSet::from(["village".into()]), - information_channels: BTreeSet::from(["village assembly bulletin".into()]), - detail_debt: 0, - last_detail_tick: 0, - evidence_receipt_ids: vec![], - }); - expansion.migration_relations.push(AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "migration:refugees:ridge".into(), - from_subject_id: "refugees".into(), - to_subject_id: "ridge-households".into(), - kind: AgencyRelationKind::Migration, - strength: 50, - active: true, - evidence_receipt_ids: vec![], - }); - - validate_region_expansion(&campaign, &expansion).unwrap(); - expansion.locations[0].routes.remove("onward"); - assert!( - validate_region_expansion(&campaign, &expansion) - .unwrap_err() - .to_string() - .contains("directed origin reachability") - ); - } - - #[test] - fn region_expansion_rejects_containment_cycles() { - let campaign = crate::resolution::tests::campaign(0, 1); - let mut expansion = valid_region_expansion(); - expansion.locations[0].container_id = Some("service-ring".into()); - expansion.locations.push(Location { - id: "service-ring".into(), - name: "Service Ring".into(), - container_id: Some("annex".into()), - routes: BTreeMap::new(), - persistent_features: vec!["fixed conduits".into()], - }); - assert!( - validate_region_expansion(&campaign, &expansion) - .unwrap_err() - .to_string() - .contains("containment contains a cycle") - ); - } -} diff --git a/crates/ghostlight-dungeon/src/consumer.rs b/crates/ghostlight-dungeon/src/consumer.rs deleted file mode 100644 index fc07417..0000000 --- a/crates/ghostlight-dungeon/src/consumer.rs +++ /dev/null @@ -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, - 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, - pub actors: BTreeMap, - pub institutions: BTreeMap, - pub clocks: BTreeMap, - pub facts: BTreeMap, - #[serde(default)] - pub canon_candidates: BTreeMap, - #[serde(default)] - pub gestalts: BTreeMap, - #[serde(default)] - pub gestalt_members: BTreeMap, - #[serde(default)] - pub agency_profiles: BTreeMap, - #[serde(default)] - pub agency_relations: BTreeMap, - #[serde(default)] - pub gestalt_lineages: BTreeMap, - #[serde(default)] - pub resolution_policy: ResolutionPolicy, -} - -impl WorldSeed { - pub fn from_campaign(campaign: &Campaign) -> Result { - 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 { - 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, - #[serde(default)] - pub last_payload_digest: Option, -} - -#[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, -} - -#[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, - pub admitted_at: DateTime, -} - -#[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, -} - -#[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, - pub state_references: Vec, - pub status: ExternalProposalStatus, - pub created_at: DateTime, -} - -#[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, -} - -#[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, -} - -#[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, -} - -#[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 { - 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 { - 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::new(), - }) - .collect() -} diff --git a/crates/ghostlight-dungeon/src/d20.rs b/crates/ghostlight-dungeon/src/d20.rs deleted file mode 100644 index cc9dc5a..0000000 --- a/crates/ghostlight-dungeon/src/d20.rs +++ /dev/null @@ -1,76 +0,0 @@ -use crate::domain::{OutcomeBand, RollReceipt}; - -pub fn capped_modifier(values: impl IntoIterator) -> i8 { - values - .into_iter() - .map(i16::from) - .sum::() - .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); - } -} diff --git a/crates/ghostlight-dungeon/src/domain.rs b/crates/ghostlight-dungeon/src/domain.rs deleted file mode 100644 index 97729ac..0000000 --- a/crates/ghostlight-dungeon/src/domain.rs +++ /dev/null @@ -1,1602 +0,0 @@ -use chrono::{DateTime, Utc}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; -use std::collections::{BTreeMap, BTreeSet}; -use uuid::Uuid; - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct Campaign { - pub schema: String, - pub id: Uuid, - pub name: String, - pub revision: u64, - pub branch_origin: BranchOrigin, - pub world_time: DateTime, - pub tick_hours: u32, - pub player_actor_id: String, - pub locations: BTreeMap, - pub actors: BTreeMap, - pub institutions: BTreeMap, - pub clocks: BTreeMap, - pub facts: BTreeMap, - #[serde(default)] - pub civic_systems: BTreeMap, - pub transcript: Vec, - pub last_player_activity: DateTime, - pub pending_ticks: u8, - #[serde(default)] - pub away_ticks_processed: u8, - #[serde(default)] - pub events: Vec, - #[serde(default)] - pub news: Vec, - #[serde(default)] - pub canon_candidates: BTreeMap, - #[serde(default)] - pub gestalts: BTreeMap, - #[serde(default)] - pub gestalt_members: BTreeMap, - #[serde(default)] - pub pending_world_proposals: Vec, - #[serde(default)] - pub agency_profiles: BTreeMap, - #[serde(default)] - pub agency_relations: BTreeMap, - #[serde(default)] - pub gestalt_lineages: BTreeMap, - #[serde(default)] - pub resolution_policy: ResolutionPolicy, - #[serde(default)] - pub resolution_pins: BTreeMap, - #[serde(default)] - pub resolution_cover: Option, - /// Durable record of exact causal attention windows already served by - /// Nemesis. WorldKernel is the sole writer; the scheduler reads it only to - /// avoid repeatedly assigning the same anchor to the same responder. - #[serde(default)] - pub nemesis_attention_history: Vec, - #[serde(default)] - pub strategic_tick_count: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct BranchOrigin { - pub canon_cutoff: String, - pub evidence_receipt_ids: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct VaultManifest { - pub schema: String, - pub provider: String, - pub source_ids: BTreeSet, - pub authority_lanes: BTreeSet, - pub temporal_scopes: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct Location { - pub id: String, - pub name: String, - #[schemars( - description = "Geometric containment only. This does not create an implicit movement edge." - )] - pub container_id: Option, - #[schemars( - description = "Explicit directed movement edges keyed by stable route ID. Containment never substitutes for a route; a playable opening must provide route chains from the player location to every supplied location and back." - )] - pub routes: BTreeMap, - pub persistent_features: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct Route { - #[schemars( - description = "Exact ID of another supplied location reached by this directed route." - )] - pub destination_id: String, - pub distance: String, - #[schemars(range(min = 1))] - pub travel_minutes: u32, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ActorState { - pub id: String, - pub name: String, - pub location_id: String, - pub capabilities: BTreeSet, - pub knowledge: BTreeSet, - pub equipment: BTreeSet, - pub conditions: BTreeSet, - pub obligations: BTreeSet, - pub relationships: BTreeMap, - pub goals: Vec, - #[serde(default)] - pub memories: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct RelationshipState { - pub schema: String, - pub actor_id: String, - #[serde(alias = "other_actor_id")] - pub other_subject_id: String, - pub description: String, - pub source_revision: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct GestaltPersonaState { - pub schema: String, - pub id: String, - pub name: String, - pub version: u64, - pub home_location_id: String, - pub shared_capabilities: BTreeSet, - pub shared_knowledge: BTreeSet, - pub resources: BTreeSet, - pub goals: Vec, - pub pressures: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct GestaltMemberDelta { - pub schema: String, - pub id: String, - pub gestalt_id: String, - pub version: u64, - pub name: String, - pub capability_additions: BTreeSet, - pub capability_removals: BTreeSet, - pub knowledge_additions: BTreeSet, - pub knowledge_removals: BTreeSet, - pub equipment: BTreeSet, - pub conditions: BTreeSet, - pub obligations: BTreeSet, - pub relationships: BTreeMap, - pub goals: Vec, - pub memories: Vec, - pub last_location_id: Option, - pub materialized_actor_id: Option, - #[serde(default)] - pub last_relevant_revision: u64, - #[serde(default)] - pub relevance_lease_until_revision: u64, -} - -/// Gestalt member records own a local identity. The `member:` namespace is a -/// world-subject projection and must never become part of that stored local ID. -/// Repeated prefixes are accepted only at model and legacy-state boundaries so -/// every downstream organ converges on one canonical person. -pub fn canonical_gestalt_member_local_id(value: &str) -> String { - let mut value = value.trim(); - while let Some(unprefixed) = value.strip_prefix("member:") { - value = unprefixed; - } - value.to_owned() -} - -pub fn gestalt_member_subject_id(member_id: &str) -> String { - format!("member:{}", canonical_gestalt_member_local_id(member_id)) -} - -/// State-reference namespaces wrap a canonical world ID exactly once. World -/// compilers may choose already-qualified IDs (for example -/// `gestalt:raincross_households`), while older fixtures use local IDs. Both -/// must project to the same evidence handle rather than accumulating prefixes. -pub fn gestalt_state_reference(gestalt_id: &str) -> String { - let gestalt_id = gestalt_id.trim(); - if gestalt_id.starts_with("gestalt:") { - gestalt_id.to_owned() - } else { - format!("gestalt:{gestalt_id}") - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct GestaltPromotion { - pub gestalt_id: String, - pub expected_gestalt_version: u64, - pub member_id: String, - pub expected_member_version: u64, - pub location_id: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct GestaltIndividuation { - pub gestalt_id: String, - pub expected_gestalt_version: u64, - pub member: GestaltMemberDelta, - pub location_id: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct StrategicGestaltIndividuation { - pub schema: String, - /// Digest of the selected Gestalt-owned action whose pressure made this - /// individual strategically consequential. - pub action_digest: String, - pub rationale: String, - pub individuation: GestaltIndividuation, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct GestaltDemotion { - pub actor_id: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] -pub struct GestaltPresencePlan { - #[serde(default)] - pub individuations: Vec, - pub promotions: Vec, - pub demotions: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct GestaltMaterializationReceipt { - pub schema: String, - pub campaign_id: Uuid, - pub previous_revision: u64, - pub revision: u64, - #[serde(default)] - pub previous_resolution_epoch: u64, - #[serde(default)] - pub resolution_epoch: u64, - pub reason: String, - pub changes: Vec, - pub committed_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct GestaltPresenceChange { - pub operation: String, - pub gestalt_id: String, - pub member_id: String, - pub actor_id: String, - pub gestalt_version: u64, - pub member_version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)] -#[serde(rename_all = "snake_case")] -pub enum AgencySubjectKind { - Actor, - Institution, - Gestalt, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)] -#[serde(rename_all = "snake_case")] -pub enum AgencyAxis { - Geography, - Ideology, - Authority, - EconomyRole, - SpeciesBody, - Information, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct AgencyProfile { - pub schema: String, - pub id: String, - pub subject_id: String, - pub subject_kind: AgencySubjectKind, - pub profile_version: u64, - pub collective_authority_id: Option, - pub parent_subject_id: Option, - pub active_leaf: bool, - #[serde(default = "default_true")] - pub simulation_eligible: bool, - pub facets: BTreeMap>, - pub location_ids: BTreeSet, - pub information_channels: BTreeSet, - pub detail_debt: u64, - pub last_detail_tick: u64, - pub evidence_receipt_ids: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum AgencyRelationKind { - Containment, - Command, - Membership, - Alliance, - Rivalry, - Trade, - Migration, - Communication, - Coercion, - SharedLocation, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct AgencyRelation { - pub schema: String, - pub id: String, - pub from_subject_id: String, - pub to_subject_id: String, - pub kind: AgencyRelationKind, - #[schemars(range(min = 1, max = 100))] - pub strength: u8, - pub active: bool, - pub evidence_receipt_ids: Vec, -} - -impl AgencyRelation { - pub const SCHEMA: &'static str = "ghostlight.agency_relation.v1"; -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct GestaltLineage { - pub schema: String, - pub parent_gestalt_id: String, - pub child_gestalt_ids: Vec, - pub partition_axis: AgencyAxis, - pub partition_values: BTreeMap, - pub residual_child_id: String, - pub source_revision: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ResolutionPolicy { - pub schema: String, - pub resolution_epoch: u64, - #[serde(default)] - pub provider_configuration_epoch: u64, - pub active_cell_budget: u8, - pub pending_active_cell_budget: Option, - pub provider_parallelism: u8, -} - -impl Default for ResolutionPolicy { - fn default() -> Self { - Self { - schema: "ghostlight.resolution_policy.v1".into(), - resolution_epoch: 0, - provider_configuration_epoch: 0, - active_cell_budget: 8, - pending_active_cell_budget: None, - provider_parallelism: 8, - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ResolutionPinKind { - KeepTogether, - KeepSeparate, - MinimumIndividualDetail, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ResolutionPin { - pub schema: String, - pub id: String, - pub kind: ResolutionPinKind, - pub subject_ids: BTreeSet, - pub reason: String, - pub created_world_revision: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ResolutionDemand { - pub schema: String, - pub campaign_id: Uuid, - pub world_revision: u64, - pub resolution_epoch: u64, - pub axis_weights: BTreeMap, - pub focal_subject_ids: BTreeSet, - pub horizon_minutes: u32, - pub rationale: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum SimulationCellMode { - Cohesive, - Arena, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] -pub struct MergeLoss { - pub facet_divergence: f32, - pub hidden_boundary_mass: f32, - pub information_divergence: f32, - pub spatial_divergence: f32, - pub clock_obligation_divergence: f32, - pub salience_burial: f32, - pub partition_churn: f32, - pub total: f32, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct SimulationCell { - pub schema: String, - pub id: String, - pub mode: SimulationCellMode, - pub subject_ids: BTreeSet, - pub merge_loss: MergeLoss, - pub rationale: String, - pub lease_until_world_revision: u64, - pub lease_until_strategic_tick: u64, - pub detail_focus_subject_id: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ResolutionCover { - pub schema: String, - pub campaign_id: Uuid, - pub world_revision: u64, - pub resolution_epoch: u64, - pub configured_budget: u8, - pub effective_budget: u8, - pub mandatory_overage: u8, - pub cells: Vec, - pub demand: ResolutionDemand, - /// Scheduler-owned reaction windows for already committed world pressure. - /// These bindings decide who must receive a decision slot, never what that - /// subject decides or which consequence the kernel commits. - #[serde(default)] - pub causal_follow_through: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct CausalFollowThroughAssignment { - /// Exact opaque handle from the scheduler's frozen anchor catalog. - pub anchor_reference: String, - /// One exact autonomous actor, institution, population, or dormant member - /// that owns a decision window for this anchor in the current cover. - pub responder_subject_id: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct NemesisAttentionRecord { - pub anchor_reference: String, - pub responder_subject_id: String, - pub served_world_revision: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ResolutionPlanReceipt { - pub schema: String, - pub campaign_id: Uuid, - pub world_revision: u64, - pub resolution_epoch: u64, - pub configured_budget: u8, - pub effective_budget: u8, - pub cell_ids: Vec, - pub mandatory_overage: u8, - pub preserved_cell_ids: Vec, - pub collapsed_boundaries: Vec, - pub merge_losses: BTreeMap, - pub rationale: String, - pub created_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ResolutionControlReceipt { - pub schema: String, - pub campaign_id: Uuid, - pub world_revision: u64, - pub previous_resolution_epoch: u64, - pub resolution_epoch: u64, - #[serde(default)] - pub provider_configuration_epoch: u64, - pub operation: String, - pub active_cell_budget: u8, - pub pin_ids: Vec, - pub committed_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(tag = "type", rename_all = "snake_case")] -pub enum StrategicCellEffect { - Institution { - institution_id: String, - posture: String, - location_ids: Vec, - }, - Gestalt { - gestalt_id: String, - #[serde(default)] - pressure_additions: Vec, - #[serde(default)] - pressure_resolutions: Vec, - }, - GestaltActivity { - gestalt_id: String, - activity: StrategicActivityKind, - #[serde(default)] - target_subject_ids: Vec, - #[serde(default)] - location_ids: Vec, - }, - GestaltMigration { - destination_gestalt_id: String, - }, - ActorMove { - actor_id: String, - destination_id: String, - }, - ActorActivity { - actor_id: String, - activity: StrategicActivityKind, - #[serde(default)] - target_subject_ids: Vec, - #[serde(default)] - location_ids: Vec, - }, - MemberActivity { - member_id: String, - activity: StrategicActivityKind, - #[serde(default)] - target_subject_ids: Vec, - #[serde(default)] - location_ids: Vec, - }, - MemberMigration { - destination_gestalt_id: String, - }, -} - -impl StrategicCellEffect { - pub(crate) fn lane(&self) -> &'static str { - match self { - Self::Institution { .. } => "institution", - Self::Gestalt { .. } => "gestalt_pressure", - Self::GestaltActivity { .. } => "gestalt_activity", - Self::GestaltMigration { .. } => "gestalt_migration", - Self::ActorMove { .. } => "actor_move", - Self::ActorActivity { .. } => "actor_activity", - Self::MemberActivity { .. } => "member_activity", - Self::MemberMigration { .. } => "member_migration", - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum StrategicActivityKind { - Prepare, - Coordinate, - Investigate, - Recruit, - Obstruct, - Trade, - Communicate, -} - -impl StrategicActivityKind { - pub fn allows_targetless_local_attempt(&self) -> bool { - matches!( - self, - Self::Prepare | Self::Investigate | Self::Obstruct | Self::Communicate - ) - } - - pub fn requires_explicit_target_for_gestalt(&self) -> bool { - !self.allows_targetless_local_attempt() && !matches!(self, Self::Coordinate) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct CellActionProposal { - pub subject_id: String, - #[schemars(length(min = 1, max = 460))] - pub intent: String, - #[schemars(length(min = 1, max = 460))] - pub intended_effect: String, - pub priority: i16, - pub state_references: Vec, - pub public_channels: Vec, - #[serde(default)] - #[schemars(length(min = 1, max = 4))] - pub effects: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -pub struct CellInaction { - pub subject_id: String, - #[schemars(length(min = 1, max = 240))] - pub reason: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct CellAppraisal { - pub schema: String, - pub cell_id: String, - pub world_revision: u64, - pub resolution_epoch: u64, - /// Exact projected decision owners for this wave. The resolution cover - /// separately proves representation of every canonical cell constituent; - /// each ID here must own exactly one action or explicit inaction. - pub considered_subject_ids: BTreeSet, - pub actions: Vec, - pub inactions: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ResolutionWaveCommit { - pub schema: String, - pub world_revision: u64, - pub resolution_epoch: u64, - pub cover: ResolutionCover, - pub plan_receipt: ResolutionPlanReceipt, - pub appraisals: Vec, - #[serde(default)] - pub activity_outcomes: Vec, - #[serde(default)] - pub strategic_individuations: Vec, - pub model_receipt_hashes: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum StrategicOutcomeBand { - Success, - Mixed, - Failure, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct StrategicActivityOutcome { - pub schema: String, - pub action_digest: String, - pub source_subject_id: String, - pub band: StrategicOutcomeBand, - #[schemars(length(min = 1, max = 240))] - pub summary: String, - #[serde(default)] - pub supporting_state_references: Vec, - pub effect: StrategicOutcomeEffect, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(tag = "type", rename_all = "snake_case")] -pub enum StrategicOutcomeEffect { - NoMaterialChange { - reason: String, - }, - ResourceCreated { - owner_subject_id: String, - resource: String, - }, - ResourceConsumed { - owner_subject_id: String, - resource: String, - }, - ResourceTransferred { - from_subject_id: String, - to_subject_id: String, - resource: String, - }, - GestaltPressure { - gestalt_id: String, - #[serde(default)] - pressure_additions: Vec, - #[serde(default)] - pressure_resolutions: Vec, - }, - AgencyRelationShift { - relation_id: String, - strength_delta: i16, - }, - MemberMemory { - member_id: String, - memory: String, - }, - MemberObligation { - member_id: String, - obligation: String, - }, - MemberRelationship { - member_id: String, - other_subject_id: String, - description: String, - }, - KnowledgeLearned { - owner_subject_id: String, - fact_id: String, - }, - KnowledgeCommunicated { - from_subject_id: String, - #[schemars(length(min = 1, max = 4))] - to_subject_ids: Vec, - fact_id: String, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct GestaltFissionPreview { - pub schema: String, - pub campaign_id: Uuid, - pub expected_world_revision: u64, - pub parent_gestalt_id: String, - pub partition_axis: AgencyAxis, - pub children: Vec, - pub child_partition_values: BTreeMap, - pub residual_child_id: String, - #[serde(default)] - pub member_child_assignments: BTreeMap, - /// Exact scarce-resource custody after the split. Every resource owned by - /// the parent appears once and names one child; it is never inherited by - /// every child as population baseline. - #[serde(default)] - pub resource_child_assignments: BTreeMap, - pub evidence_receipt_ids: Vec, - pub gaps: Vec, - #[serde(default)] - pub canon_candidates: Vec, - pub requires_approval: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] -pub struct ActorStateDelta { - pub memories_add: Vec, - /// One public self-identifier explicitly adopted in the actor's own - /// speech. WorldKernel binds the subject and derives the identity handle; - /// the model never supplies either authority value. - #[serde(default)] - pub identity_adoption: Option, - pub conditions_add: BTreeSet, - pub conditions_remove: BTreeSet, - pub goals_add: Vec, - pub relationship_updates: BTreeMap, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct WorldActionProposal { - pub actor_id: String, - pub intent: String, - pub intended_effect: String, - pub priority: i16, - pub state_references: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ActorReaction { - pub actor_id: String, - pub speech: Option, - /// A typed, actor-owned refusal to answer. The kernel lowers this to a - /// deterministic visible transcript turn, so an Interpreter cannot smuggle - /// an unassessed physical effect through free-form reaction prose. - #[serde(default)] - pub deliberate_silence: bool, - pub private_delta: ActorStateDelta, - pub action_proposals: Vec, -} - -/// A foreground appraisal owned by one cohesive population subject. Unlike an -/// arena cell, a Gestalt has genuine collective authority and may speak in the -/// plural. Its foreground reaction cannot mutate actor-private state or smuggle -/// an unassessed strategic action through dialogue. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct GestaltReaction { - pub gestalt_id: String, - pub speech: Option, - #[serde(default)] - pub deliberate_silence: bool, -} - -pub const MAX_POSTURE_CHARS: usize = 460; - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct InstitutionState { - pub id: String, - pub name: String, - pub resources: Vec, - pub goals: Vec, - pub posture: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(default)] -#[schemars(inline)] -pub struct WorldEventScope { - pub actor_ids: Vec, - pub institution_ids: Vec, - pub gestalt_ids: Vec, - pub location_ids: Vec, - pub public_channels: Vec, -} - -impl Default for WorldEventScope { - fn default() -> Self { - Self { - actor_ids: Vec::new(), - institution_ids: Vec::new(), - gestalt_ids: Vec::new(), - location_ids: Vec::new(), - public_channels: Vec::new(), - } - } -} - -impl WorldEventScope { - pub fn is_unbound(&self) -> bool { - self.actor_ids.is_empty() - && self.institution_ids.is_empty() - && self.gestalt_ids.is_empty() - && self.location_ids.is_empty() - && self.public_channels.is_empty() - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct WorldClock { - pub id: String, - pub label: String, - pub progress: u8, - #[schemars(range(min = 1))] - pub threshold: u8, - pub consequence: String, - /// Exact subjects, places, and information routes affected when this clock - /// first reaches its threshold. Legacy snapshots may be unbound until an - /// admitted reconciliation pass supplies this scope. - #[serde(default)] - pub consequence_scope: WorldEventScope, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct WorldFact { - pub id: String, - pub statement: String, - pub scope: FactScope, - pub evidence_receipt_ids: Vec, - /// Locations whose immediate environment can expose this fact through an - /// admitted informational attempt. Empty means the fact is not directly - /// discoverable from occupancy alone. - #[serde(default)] - pub discoverable_at_location_ids: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct Event { - pub id: String, - pub at: DateTime, - pub kind: String, - pub summary: String, - pub actor_ids: Vec, - pub institution_ids: Vec, - #[serde(default)] - pub gestalt_ids: Vec, - pub location_ids: Vec, - pub public_channels: Vec, -} - -#[derive( - Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, -)] -#[serde(rename_all = "snake_case")] -pub enum PublicEventAssertionStatus { - AttemptCommittedOutcomeUnknown, - CourseCommittedEmbeddedActionsNotCompleted, - PublicDeclaration, - MaterialChangeCommitted, - PublicAccountStatusUnspecified, -} - -impl Event { - pub fn public_assertion_status(&self) -> PublicEventAssertionStatus { - match self.kind.as_str() { - "actor_activity" | "gestalt_activity" | "gestalt_member_activity" => { - PublicEventAssertionStatus::AttemptCommittedOutcomeUnknown - } - "institution_action" => { - PublicEventAssertionStatus::CourseCommittedEmbeddedActionsNotCompleted - } - "gestalt_action" | "public_notice" => PublicEventAssertionStatus::PublicDeclaration, - "strategic_activity_outcome" - | "actor_movement" - | "gestalt_migration" - | "gestalt_member_migration" - | "clock_consequence" - | "group_travel" => PublicEventAssertionStatus::MaterialChangeCommitted, - _ => PublicEventAssertionStatus::PublicAccountStatusUnspecified, - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct NewsIssue { - pub id: String, - pub at: DateTime, - pub channel: String, - pub headline: String, - pub event_ids: Vec, - pub reliability: String, -} - -pub const MAX_PUBLIC_EVENT_SUMMARY_CHARS: usize = 240; - -pub fn committed_news_headline(summary: &str) -> String { - const MAX_HEADLINE_CHARS: usize = 96; - let summary = summary.trim(); - if summary.chars().count() <= MAX_HEADLINE_CHARS { - return summary.to_owned(); - } - let mut headline = summary.chars().take(MAX_HEADLINE_CHARS).collect::(); - let semantic_cut = headline - .rfind(|character: char| matches!(character, ';' | ':' | ',' | '—')) - .filter(|cut| *cut >= MAX_HEADLINE_CHARS / 2); - let word_cut = headline - .rfind(char::is_whitespace) - .filter(|cut| *cut >= MAX_HEADLINE_CHARS / 2); - if let Some(cut) = semantic_cut.or(word_cut) { - headline.truncate(cut); - } - headline = headline - .trim_end_matches(|character: char| character.is_whitespace() || character == '.') - .to_owned(); - headline.push('…'); - headline -} - -pub fn append_event_with_publications(campaign: &mut Campaign, event: Event) { - for channel in &event.public_channels { - campaign.news.push(NewsIssue { - id: event_publication_id(&event.id, channel), - at: event.at, - channel: channel.clone(), - headline: committed_news_headline(&event.summary), - event_ids: vec![event.id.clone()], - reliability: "committed public channel".into(), - }); - } - campaign.events.push(event); -} - -pub fn event_publication_id(event_id: &str, channel: &str) -> String { - use sha2::{Digest, Sha256}; - - let channel_id = format!("{:x}", Sha256::digest(channel.as_bytes()))[..12].to_owned(); - format!("news:{event_id}:{channel_id}") -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] -pub struct StrategicTickPlan { - /// Canonical admitted strategic choices. The action arrays below are - /// deterministic projections used by the legacy event and transition - /// lowering path; production callers rebuild them from this list. - #[serde(default)] - pub selected_actions: Vec, - pub institution_actions: Vec, - pub gestalt_actions: Vec, - #[serde(default)] - pub gestalt_activities: Vec, - #[serde(default)] - pub gestalt_migrations: Vec, - pub actor_moves: Vec, - #[serde(default)] - pub actor_activities: Vec, - #[serde(default)] - pub member_migrations: Vec, - #[serde(default)] - pub member_activities: Vec, - #[serde(default)] - pub activity_outcomes: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct StrategicInstitutionAction { - pub institution_id: String, - pub posture: String, - pub location_ids: Vec, - pub public_channels: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct StrategicGestaltAction { - pub gestalt_id: String, - pub pressure_additions: Vec, - pub pressure_resolutions: Vec, - pub public_channels: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct StrategicGestaltActivity { - pub action_digest: String, - pub gestalt_id: String, - pub activity: StrategicActivityKind, - pub target_subject_ids: Vec, - pub location_ids: Vec, - pub public_channels: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct StrategicGestaltMigration { - pub gestalt_id: String, - pub destination_gestalt_id: String, - pub destination_location_id: String, - pub public_channels: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct StrategicActorMove { - pub actor_id: String, - pub destination_id: String, - pub public_channels: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct StrategicActorActivity { - pub action_digest: String, - pub actor_id: String, - pub activity: StrategicActivityKind, - pub target_subject_ids: Vec, - pub location_ids: Vec, - pub public_channels: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct StrategicMemberMigration { - pub member_id: String, - pub source_gestalt_id: String, - pub destination_gestalt_id: String, - pub destination_location_id: String, - pub public_channels: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct StrategicMemberActivity { - pub action_digest: String, - pub member_id: String, - pub source_gestalt_id: String, - pub activity: StrategicActivityKind, - pub target_subject_ids: Vec, - pub location_ids: Vec, - pub public_channels: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct StrategicTickReceipt { - pub schema: String, - pub campaign_id: Uuid, - pub previous_revision: u64, - pub revision: u64, - pub source: TickSource, - pub model_receipt_hash: Option, - #[serde(default)] - pub model_receipt_hashes: Vec, - #[serde(default)] - pub resolution_epoch: Option, - #[serde(default)] - pub resolution_cover_id: Option, - pub event_ids: Vec, - pub committed_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct CanonCandidate { - pub schema: String, - pub id: String, - pub originating_campaign_id: Uuid, - pub gap: String, - pub evidence_receipt_ids: Vec, - pub conflicts: Vec, - pub proposed_wording: String, - pub affected_vault_sources: Vec, - pub status: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum FactScope { - CanonBaseline, - BranchLocal, - ProvisionalLocal, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct NarrativeTurn { - pub revision: u64, - pub at: DateTime, - pub speaker: String, - pub text: String, - /// Exact model-controlled Persona subject IDs whom this committed speech - /// asks to respond. The legacy field name includes actors, folded named - /// members, and cohesive Gestalts. Other present subjects still perceive - /// and appraise the turn but are not response-bound. Human-controlled - /// actors never appear here. - #[serde(default)] - pub persona_response_actor_ids: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct CampaignLifecycleReceipt { - pub schema: String, - pub campaign_id: Uuid, - pub operation: String, - pub parent_campaign_id: Option, - pub parent_revision: Option, - pub created_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct RejectedProposalReceipt { - pub schema: String, - pub id: String, - pub campaign_id: Uuid, - pub revision: u64, - pub command_kind: String, - pub reason: String, - pub rejected_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ActionIntent { - pub actor_id: String, - pub description: String, - pub intended_effect: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(tag = "type", rename_all = "snake_case")] -pub enum WorldCommand { - CreateCampaign { - campaign: Campaign, - evidence_receipts: Vec, - #[serde(default)] - model_stage_receipts: Vec, - }, - ApplyExternalSubjectSnapshot { - snapshot: crate::consumer::ExternalSubjectSnapshot, - }, - Speak { - expected_revision: u64, - actor_id: String, - text: String, - intended_effect: Option, - /// Filled by the server-side scene-address resolver from the exact - /// present-actor catalog. Player boundaries must not accept authority - /// IDs in this field. - #[serde(default)] - persona_response_actor_ids: BTreeSet, - }, - Assess { - expected_revision: u64, - intent: ActionIntent, - #[serde(default)] - proposal: Option, - }, - Attempt { - actor_id: String, - assessment_digest: String, - }, - Wait { - expected_revision: u64, - minutes: u32, - }, - ProposeTimeAdvance { - expected_revision: u64, - member_id: String, - minutes: u32, - }, - ApproveTimeAdvance { - expected_revision: u64, - proposal_id: String, - member_id: String, - }, - ProposeGroupTravel { - expected_revision: u64, - member_id: String, - destination_location_id: String, - }, - ApproveGroupTravel { - expected_revision: u64, - proposal_id: String, - member_id: String, - }, - AdvanceStrategicTick { - expected_revision: u64, - source: TickSource, - #[serde(default)] - plan: Option, - #[serde(default)] - model_receipt_hash: Option, - #[serde(default)] - resolution_wave: Option, - }, - SetResolutionBudget { - expected_revision: u64, - expected_resolution_epoch: u64, - active_cell_budget: u8, - }, - ProposeResolutionBudget { - expected_revision: u64, - expected_resolution_epoch: u64, - member_id: String, - active_cell_budget: u8, - }, - ApproveResolutionBudget { - expected_revision: u64, - proposal_id: String, - member_id: String, - }, - SetProviderParallelism { - expected_revision: u64, - expected_provider_configuration_epoch: u64, - provider_parallelism: u8, - }, - ReplaceResolutionPins { - expected_revision: u64, - expected_resolution_epoch: u64, - pins: Vec, - }, - FissionGestalt { - expected_revision: u64, - preview: GestaltFissionPreview, - evidence_receipts: Vec, - #[serde(default)] - model_stage_receipts: Vec, - }, - ElaborateGestaltFission { - expected_revision: u64, - preview: GestaltFissionPreview, - qualification: crate::elaboration::WorldComplexityFissionQualification, - #[serde(default)] - model_stage_receipts: Vec, - }, - ElaborateGestaltIndividuation { - expected_revision: u64, - individuation: GestaltIndividuation, - qualification: crate::elaboration::WorldComplexityIndividuationQualification, - #[serde(default)] - model_stage_receipts: Vec, - }, - ReconcileFissionCivicBindings { - expected_revision: u64, - }, - ExpandRegion { - expected_revision: u64, - expansion: RegionExpansion, - evidence_receipts: Vec, - canon_candidates: Vec, - #[serde(default)] - model_stage_receipts: Vec, - }, - ElaborateLocality { - expected_revision: u64, - elaboration: LocalityElaboration, - evidence_receipts: Vec, - canon_candidates: Vec, - #[serde(default)] - model_stage_receipts: Vec, - }, - MaterializeGestaltMember { - expected_revision: u64, - gestalt_id: String, - expected_gestalt_version: u64, - member_id: String, - expected_member_version: u64, - location_id: String, - }, - IndividuateGestaltMember { - expected_revision: u64, - individuation: GestaltIndividuation, - }, - DematerializeGestaltMember { - expected_revision: u64, - actor_id: String, - }, - ReconcileGestaltPresence { - expected_revision: u64, - reason: String, - plan: GestaltPresencePlan, - }, - ResolveReactionWave { - expected_revision: u64, - event_summary: String, - reactions: Vec, - #[serde(default)] - gestalt_reactions: Vec, - }, - ResolveNpcAction { - expected_revision: u64, - proposal: WorldActionProposal, - assessment: ActionAssessment, - }, - BindClockConsequences { - expected_revision: u64, - admission: crate::clock::ClockConsequenceBindingAdmission, - model_stage_receipts: Vec, - }, -} - -fn default_true() -> bool { - true -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct RegionExpansion { - pub origin_location_id: String, - /// Exact outbound routes added to the already-materialized origin. Keeping - /// these separate from `locations` makes the existing-place mutation - /// explicit in the approval preview instead of deriving a hidden reverse - /// route after commit. - #[serde(default)] - pub origin_routes: BTreeMap, - pub locations: Vec, - pub facts: Vec, - /// Optional population leaves that make an inhabited destination part of - /// the agency graph. Destination compilation admits these subjects; it - /// never moves an existing population or named member into them. - #[serde(default)] - pub populations: Vec, - /// Exact agency inputs for `populations`. Keeping these in the approved - /// expansion makes the resolution cover reproducible without making the - /// cover itself canonical. - #[serde(default)] - pub population_profiles: Vec, - /// Directed population routes admitted with the destination. A migration - /// remains a later strategic choice validated against one of these exact - /// relations and the physical topology. - #[serde(default)] - pub migration_relations: Vec, - /// Institutions admitted with the region or locality. Institutions remain - /// distinct strategic subjects; population leaves may know public civic - /// facts without inheriting an institution's goals, resources, or voice. - #[serde(default)] - pub institutions: Vec, - /// Exact agency inputs for `institutions`. - #[serde(default)] - pub institution_profiles: Vec, - /// Political and administrative relations among newly admitted local - /// institutions and populations. Migration remains in its separate lane. - #[serde(default)] - pub local_relations: Vec, - /// Structural receipt proving that an inhabited locality exposes enough - /// committed public state for ordinary civic questions. The facts may say - /// that no mayor or election exists; a player's presupposition never gets - /// to choose the answer. - #[serde(default)] - pub civic_system: Option, -} - -#[derive(JsonSchema)] -#[allow(dead_code)] -pub(crate) enum CivicSystemManifestSchemaV1 { - #[schemars(rename = "ghostlight.civic_system_manifest.v1")] - V1, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct CivicSystemManifest { - #[schemars(with = "CivicSystemManifestSchemaV1")] - pub schema: String, - #[serde(default)] - pub version: u64, - pub jurisdiction_location_id: String, - pub governing_institution_ids: BTreeSet, - pub resident_population_ids: BTreeSet, - pub public_authority_fact_ids: BTreeSet, - pub public_selection_fact_ids: BTreeSet, - pub public_resource_fact_ids: BTreeSet, - pub public_redress_fact_ids: BTreeSet, - pub political_relation_ids: BTreeSet, - /// Exact locally rebound verifier receipt that covers this complete civic - /// candidate. The compiler supplies it after inference; models never own - /// this binding. - #[serde(default)] - pub semantic_verification_receipt_id: String, -} - -/// Admission of bounded child detail beneath one exact canonical coarse place. -/// The target identity is immutable; the nested expansion contains only new -/// subjects, facts, child places, and edges admitted beneath it. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct LocalityElaboration { - pub target_location_id: String, - pub expansion: RegionExpansion, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct RegionExpansionPreview { - pub schema: String, - pub campaign_id: Uuid, - pub expected_revision: u64, - pub expansion: RegionExpansion, - pub evidence_receipts: Vec, - /// Consequential game-scale detail synthesized for this campaign because - /// the Vault constrains the destination without exhaustively specifying a - /// playable map. These assumptions are reviewable branch state, not canon - /// gaps or canon-candidate proposals. - #[serde(default)] - pub branch_assumptions: Vec, - pub gaps: Vec, - pub canon_candidates: Vec, - pub requires_approval: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct LocalityElaborationPreview { - pub schema: String, - pub campaign_id: Uuid, - pub expected_revision: u64, - pub elaboration: LocalityElaboration, - pub evidence_receipts: Vec, - #[serde(default)] - pub branch_assumptions: Vec, - pub gaps: Vec, - pub canon_candidates: Vec, - pub requires_approval: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(tag = "kind", content = "preview", rename_all = "snake_case")] -pub enum DestinationCompilationPreview { - RegionExpansion(RegionExpansionPreview), - LocalityElaboration(LocalityElaborationPreview), -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TickSource { - Scheduler, - ReturnCatchUp, - PlayerWait, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ContextModifier { - pub label: String, - pub value: i8, - pub references: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] -pub struct ConditionDelta { - pub add: BTreeSet, - pub remove: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] -pub struct CommitmentDelta { - pub goals_add: BTreeSet, - pub goals_retire: BTreeSet, - pub obligations_add: BTreeSet, - pub obligations_retire: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] -#[serde(default)] -pub struct WorldEffectDelta { - pub actor_conditions: BTreeMap, - /// Bounded changes to goals or obligations owned by exact present actors. - /// A social outcome may create a voluntary commitment; it may not transfer - /// custody of the actor or guarantee behavior beyond that commitment. - #[serde(default)] - pub actor_commitments: BTreeMap, - /// Exact player-readable natural-language findings learned by each actor. - /// Values are declarative statements, never fact IDs, labels, or keys. - #[serde(default)] - pub actor_knowledge_additions: BTreeMap>, - /// New branch-local propositions established by the acting actor's exact - /// means in this outcome. These are observations, measurements, or test - /// results—not pre-existing facts selected from the campaign catalog. Each - /// value is the concrete proposition learned, never a report that an - /// inquiry occurred or an unresolved placeholder for a later resolver. - #[serde(default)] - pub actor_observations: BTreeMap>, - pub actor_relationship_updates: BTreeMap>, - pub actor_moves: BTreeMap, - pub clock_advances: BTreeMap, - /// Bounded progress removed from an existing world clock. This is the - /// persistent inverse of an advance for repairs, relief, and obstruction. - #[serde(default)] - pub clock_reductions: BTreeMap, - pub institution_postures: BTreeMap, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ActionAssessment { - pub schema: String, - pub campaign_id: Uuid, - pub revision: u64, - pub intent: ActionIntent, - pub admissible: bool, - pub missing_permission: Option, - pub dc: u8, - pub modifiers: Vec, - pub modifier_total: i8, - pub effect_ceiling: String, - pub success_stake: String, - pub mixed_stake: String, - pub failure_stake: String, - #[serde(default)] - pub strong_effect: WorldEffectDelta, - #[serde(default)] - pub success_effect: WorldEffectDelta, - #[serde(default)] - pub mixed_effect: WorldEffectDelta, - #[serde(default)] - pub failure_effect: WorldEffectDelta, - pub bargains: Vec, - pub expires_at: DateTime, - pub digest: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum OutcomeBand { - Failure, - Mixed, - Success, - StrongSuccess, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct RollReceipt { - pub schema: String, - pub assessment_digest: String, - pub d20: u8, - pub modifier_total: i8, - pub total: i16, - pub dc: u8, - pub outcome: OutcomeBand, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct WorldCommitReceipt { - pub schema: String, - pub campaign_id: Uuid, - pub previous_revision: u64, - pub revision: u64, - pub command_kind: String, - pub committed_at: DateTime, - pub roll: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct VaultEvidenceReceipt { - pub schema: String, - pub id: String, - pub provider: String, - pub query_hash: String, - pub witnesses: Vec, - pub retrieved_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct SourceWitness { - pub source_id: String, - pub exact_locator: String, - pub content_hash: String, - pub excerpt: String, - pub authority_lane: String, - pub temporal_scope: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct WorldCompilePreview { - pub schema: String, - pub title: String, - pub campaign: Campaign, - pub evidence_receipts: Vec, - #[serde(default)] - pub evidence_coverage: Vec, - pub gaps: Vec, - pub branch_assumptions: Vec, - pub requires_approval: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum EvidenceUseLane { - DirectSeed, - SettingBackground, - Excluded, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct EvidenceCoverage { - pub source_id: String, - pub lane: EvidenceUseLane, - pub rationale: String, -} diff --git a/crates/ghostlight-dungeon/src/elaboration.rs b/crates/ghostlight-dungeon/src/elaboration.rs deleted file mode 100644 index 732ab26..0000000 --- a/crates/ghostlight-dungeon/src/elaboration.rs +++ /dev/null @@ -1,6378 +0,0 @@ -use anyhow::{Result, anyhow}; -use async_trait::async_trait; -use schemars::{JsonSchema, schema_for}; -use serde::{Deserialize, Serialize}; -use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::sync::Arc; -use uuid::Uuid; - -pub const MAX_ELABORATOR_WEIGHT: u16 = 100; -pub const COVER_BASIS_POINTS: u32 = 10_000; - -/// Consumer-owned scale intent for world elaboration. This states how much of -/// the potentially acting world may receive simultaneous cell attention; it -/// does not change the campaign's active-cell entitlement or admit subjects. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldScaleIntent { - pub schema: String, - #[schemars(range(min = 1, max = 10000))] - pub target_active_cover_basis_points: u16, -} - -impl WorldScaleIntent { - pub fn ten_percent() -> Self { - Self { - schema: "ghostlight.world_scale_intent.v1".into(), - target_active_cover_basis_points: 1_000, - } - } - - pub fn twenty_percent() -> Self { - Self { - schema: "ghostlight.world_scale_intent.v1".into(), - target_active_cover_basis_points: 2_000, - } - } -} - -/// Deterministic elaboration pressure derived from scale intent and current -/// canonical state. The scheduler may spend this budget on proposals; only -/// existing admission and WorldKernel paths can turn them into subjects. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldElaborationDemand { - pub schema: String, - pub active_cell_budget: u16, - pub target_active_cover_basis_points: u16, - pub target_actionable_subjects: u32, - pub current_actionable_subjects: u32, - pub actionable_subject_deficit: u32, - /// Bounded work to attempt before remeasuring canonical complexity. This - /// is pressure, not an assumed subject yield or model-call count. - pub round_mutation_budget: u32, - pub realm_complexity_weights: BTreeMap, - pub realm_subject_targets: BTreeMap, -} - -pub fn residual_gestalt_ids(campaign: &crate::domain::Campaign) -> BTreeSet { - campaign - .gestalt_lineages - .values() - .map(|lineage| lineage.residual_child_id.clone()) - .collect() -} - -fn semantically_qualified_fission_child( - campaign: &crate::domain::Campaign, - child_id: &str, - parent_id: &str, -) -> bool { - let Some(child) = campaign.gestalts.get(child_id) else { - return false; - }; - let Some(parent) = campaign.gestalts.get(parent_id) else { - return false; - }; - if !child - .shared_capabilities - .is_superset(&parent.shared_capabilities) - || !child.shared_knowledge.is_superset(&parent.shared_knowledge) - || !child.goals.starts_with(&parent.goals) - || !child.pressures.starts_with(&parent.pressures) - { - return false; - } - [ - child.shared_capabilities.len() > parent.shared_capabilities.len(), - child.shared_knowledge.len() > parent.shared_knowledge.len(), - child.goals.len() > parent.goals.len(), - child.pressures.len() > parent.pressures.len(), - ] - .into_iter() - .filter(|present| *present) - .count() - >= 2 -} - -/// Returns active action owners whose current state can justify complexity -/// credit. Compiler-admitted roots and individuated people are admitted by -/// their owning gates. A fission child must additionally retain two or more -/// semantic dimensions beyond its exact parent; a merely relabelled ordinary -/// split remains simulatable but cannot pay the world-size bill. -pub fn canonical_actionable_subject_ids(campaign: &crate::domain::Campaign) -> BTreeSet { - let residual_ids = residual_gestalt_ids(campaign); - let fission_parents = campaign - .gestalt_lineages - .values() - .flat_map(|lineage| { - lineage - .child_gestalt_ids - .iter() - .map(move |child_id| (child_id.clone(), lineage.parent_gestalt_id.clone())) - }) - .collect::>(); - campaign - .agency_profiles - .values() - .filter(|profile| { - profile.active_leaf - && profile.simulation_eligible - && !residual_ids.contains(&profile.subject_id) - && fission_parents - .get(&profile.subject_id) - .is_none_or(|parent_id| { - semantically_qualified_fission_child( - campaign, - &profile.subject_id, - parent_id, - ) - }) - }) - .map(|profile| profile.subject_id.clone()) - .collect() -} - -/// Counts qualified active agency leaves that could own an action. Dormant -/// member records, census texture, and unresolved residual populations do not -/// satisfy world-complexity demand. Residuals preserve unresolved lineage and -/// membership state, but are not simulation-eligible action owners and cannot -/// be recursively split for quota. -pub fn canonical_actionable_subject_count(campaign: &crate::domain::Campaign) -> u32 { - u32::try_from(canonical_actionable_subject_ids(campaign).len()).unwrap_or(u32::MAX) -} - -/// Resolve exact operating places through canonical containment to one -/// consumer-declared jurisdiction. Presence remains owned by the profile; -/// this read-only derivation never promotes a container into occupancy. -pub fn unique_containing_jurisdiction( - campaign: &crate::domain::Campaign, - location_ids: &BTreeSet, - jurisdiction_ids: &BTreeSet, -) -> Option { - let mut jurisdictions = BTreeSet::new(); - for location_id in location_ids { - let mut current = Some(location_id.as_str()); - let mut visited = BTreeSet::new(); - while let Some(candidate) = current { - if !visited.insert(candidate) { - break; - } - if jurisdiction_ids.contains(candidate) { - jurisdictions.insert(candidate.to_owned()); - break; - } - current = campaign - .locations - .get(candidate) - .and_then(|location| location.container_id.as_deref()); - } - } - (jurisdictions.len() == 1).then(|| { - jurisdictions - .into_iter() - .next() - .expect("one jurisdiction was resolved") - }) -} - -pub fn derive_world_elaboration_demand( - active_cell_budget: u16, - current_actionable_subjects: u32, - intent: &WorldScaleIntent, - realm_complexity_weights: BTreeMap, -) -> Result { - if intent.schema != "ghostlight.world_scale_intent.v1" - || intent.target_active_cover_basis_points == 0 - || u32::from(intent.target_active_cover_basis_points) > COVER_BASIS_POINTS - { - return Err(anyhow!("world scale intent is unsupported or out of range")); - } - if active_cell_budget == 0 { - return Err(anyhow!( - "world scale intent requires a nonzero active-cell budget" - )); - } - if realm_complexity_weights.is_empty() - || realm_complexity_weights - .iter() - .any(|(realm, weight)| realm.trim().is_empty() || *weight == 0) - { - return Err(anyhow!( - "world elaboration demand requires nonempty realms with positive complexity weights" - )); - } - let cover = u32::from(intent.target_active_cover_basis_points); - let target_actionable_subjects = u32::from(active_cell_budget) - .saturating_mul(COVER_BASIS_POINTS) - .div_ceil(cover); - let actionable_subject_deficit = - target_actionable_subjects.saturating_sub(current_actionable_subjects); - let round_mutation_budget = if actionable_subject_deficit == 0 { - 0 - } else { - u32::from(active_cell_budget) - .saturating_mul(actionable_subject_deficit) - .div_ceil(target_actionable_subjects) - .max(1) - }; - let total_weight = realm_complexity_weights - .values() - .try_fold(0_u32, |total, weight| total.checked_add(*weight)) - .ok_or_else(|| anyhow!("realm complexity weights overflow"))?; - let mut realm_subject_targets = BTreeMap::new(); - let mut assigned = 0_u32; - let last_realm = realm_complexity_weights.keys().next_back().cloned(); - for (realm, weight) in &realm_complexity_weights { - let share = if Some(realm) == last_realm.as_ref() { - target_actionable_subjects.saturating_sub(assigned) - } else { - target_actionable_subjects.saturating_mul(*weight) / total_weight - }; - assigned = assigned.saturating_add(share); - realm_subject_targets.insert(realm.clone(), share); - } - Ok(WorldElaborationDemand { - schema: "ghostlight.world_elaboration_demand.v1".into(), - active_cell_budget, - target_active_cover_basis_points: intent.target_active_cover_basis_points, - target_actionable_subjects, - current_actionable_subjects, - actionable_subject_deficit, - round_mutation_budget, - realm_complexity_weights, - realm_subject_targets, - }) -} - -#[derive( - Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, Hash, -)] -#[serde(rename_all = "snake_case")] -pub enum ElaboratorTitle { - /// Ordinary objects, customs, nicknames, local jokes, and other reusable - /// low-stakes texture. - Patina, - /// Government, law, offices, selection, succession, and redress. - Charter, - /// Resources, labor, trade, infrastructure, scarcity, and class pressure. - Ledger, - /// Kinship, daily life, care, obligation, belonging, and neighborhood ties. - Hearth, - /// Factions, alliances, rivalries, leverage, and political maneuvering. - Tangle, - /// Secrets, rumors, misinformation, taboos, and unevenly held knowledge. - Veil, - /// Active disputes, hazards, instability, escalation, and urgent pressure. - Ember, - /// Religion, magic, ritual, awe, cosmology, and the genuinely strange. - Numen, -} - -impl ElaboratorTitle { - pub const ALL: [Self; 8] = [ - Self::Patina, - Self::Charter, - Self::Ledger, - Self::Hearth, - Self::Tangle, - Self::Veil, - Self::Ember, - Self::Numen, - ]; - - pub fn mandate(self) -> &'static str { - match self { - Self::Patina => { - "Add durable, locally grounded, low-stakes texture that later events may acquire meaning from." - } - Self::Charter => { - "Elaborate legible institutions, offices, procedures, succession, public authority, and redress." - } - Self::Ledger => { - "Elaborate material dependencies: work, resources, infrastructure, exchange, scarcity, and class pressure." - } - Self::Hearth => { - "Elaborate ordinary social life: kinship, care, neighborhood, obligation, belonging, and private stakes." - } - Self::Tangle => { - "Elaborate political relationships: factions, alliances, rivalries, leverage, constituencies, and plots." - } - Self::Veil => { - "Elaborate uneven knowledge: secrets, rumors, taboos, misinformation, mysteries, and disclosure paths." - } - Self::Ember => { - "Elaborate active pressure: disputes, hazards, instability, escalation paths, and urgent consequences." - } - Self::Numen => { - "Elaborate numinous meaning: religion, ritual, magic, cosmology, wonder, and bounded strangeness." - } - } - } - - pub fn display_name(self) -> &'static str { - match self { - Self::Patina => "Patina", - Self::Charter => "Charter", - Self::Ledger => "Ledger", - Self::Hearth => "Hearth", - Self::Tangle => "Tangle", - Self::Veil => "Veil", - Self::Ember => "Ember", - Self::Numen => "Numen", - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct ElaboratorDescriptor { - pub title: ElaboratorTitle, - pub display_name: String, - pub mandate: String, -} - -pub fn elaborator_catalog() -> Vec { - ElaboratorTitle::ALL - .into_iter() - .map(|title| ElaboratorDescriptor { - title, - display_name: title.display_name().into(), - mandate: title.mandate().into(), - }) - .collect() -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct ElaboratorControl { - pub title: ElaboratorTitle, - /// Relative scheduler weight. Zero disables this elaborator. Positive - /// values are normalized across the titles eligible for each dispatch. - #[schemars(range(min = 0, max = 100))] - pub weight: u16, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldElaborationProfile { - pub schema: String, - pub controls: Vec, -} - -impl Default for WorldElaborationProfile { - fn default() -> Self { - Self { - schema: "ghostlight.world_elaboration_profile.v1".into(), - controls: ElaboratorTitle::ALL - .into_iter() - .map(|title| ElaboratorControl { title, weight: 50 }) - .collect(), - } - } -} - -impl WorldElaborationProfile { - pub fn weights(&self) -> Result> { - if self.schema != "ghostlight.world_elaboration_profile.v1" { - return Err(anyhow!("world elaboration profile schema is unsupported")); - } - let mut weights = BTreeMap::new(); - for control in &self.controls { - if control.weight > MAX_ELABORATOR_WEIGHT - || weights.insert(control.title, control.weight).is_some() - { - return Err(anyhow!( - "world elaboration profile requires unique titles with weights from zero to {MAX_ELABORATOR_WEIGHT}" - )); - } - } - if weights.values().all(|weight| *weight == 0) { - return Err(anyhow!( - "world elaboration profile must enable at least one titled elaborator" - )); - } - Ok(weights) - } -} - -/// Compacted working memory for one titled elaborator. Narrative fields steer -/// later proposals but own no world truth; exact commit receipts and the -/// canonical campaign remain authoritative. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct ElaboratorSessionCheckpoint { - pub schema: String, - pub session_id: String, - pub title: ElaboratorTitle, - pub generation: u32, - pub campaign_id: Uuid, - pub through_world_revision: u64, - pub target_location_id: String, - pub frontier_summary: String, - pub unresolved_leads: Vec, - pub recent_commit_receipt_ids: Vec, - pub recent_rejection_findings: Vec, - pub prior_checkpoint_digest: Option, - pub digest: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct ElaboratorSessionCompactionDraft { - pub schema: String, - pub frontier_summary: String, - pub unresolved_leads: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct ElaboratorSessionJournalEntry { - pub world_revision: u64, - pub commit_receipt_id: String, - pub mutation_kind: String, - pub affected_subject_ids: Vec, - pub summary: String, -} - -/// Stable logical-session routing key. A title keeps a distinct bounded mind -/// in each world jurisdiction instead of carrying one global transcript across -/// unrelated realms. -pub fn elaborator_session_id(title: ElaboratorTitle, jurisdiction_id: &str) -> String { - format!( - "{}:{}", - title.display_name().to_ascii_lowercase(), - jurisdiction_id - ) -} - -impl ElaboratorSessionCheckpoint { - #[allow(clippy::too_many_arguments)] - pub fn bind_compaction( - session_id: impl Into, - title: ElaboratorTitle, - generation: u32, - campaign_id: Uuid, - through_world_revision: u64, - target_location_id: impl Into, - draft: ElaboratorSessionCompactionDraft, - recent_commit_receipt_ids: Vec, - recent_rejection_findings: Vec, - prior_checkpoint_digest: Option, - ) -> Result { - if draft.schema != "ghostlight.elaborator_session_compaction_draft.v1" { - return Err(anyhow!( - "elaborator session compaction draft schema is unsupported" - )); - } - let mut checkpoint = Self { - schema: "ghostlight.elaborator_session_checkpoint.v1".into(), - session_id: session_id.into(), - title, - generation, - campaign_id, - through_world_revision, - target_location_id: target_location_id.into(), - frontier_summary: draft.frontier_summary, - unresolved_leads: draft.unresolved_leads, - recent_commit_receipt_ids, - recent_rejection_findings, - prior_checkpoint_digest, - digest: String::new(), - }; - checkpoint.validate_shape()?; - checkpoint.digest = checkpoint.recompute_digest()?; - Ok(checkpoint) - } - - pub fn validate_for( - &self, - campaign: &crate::domain::Campaign, - target_location_id: &str, - title: ElaboratorTitle, - ) -> Result<()> { - self.validate_shape()?; - if self.campaign_id != campaign.id - || self.through_world_revision > campaign.revision - || self.target_location_id != target_location_id - || self.title != title - || self.digest != self.recompute_digest()? - { - return Err(anyhow!( - "elaborator session checkpoint is stale, cross-session, or malformed" - )); - } - Ok(()) - } - - fn validate_shape(&self) -> Result<()> { - let bounded = |value: &str, maximum: usize| { - !value.trim().is_empty() && value.chars().count() <= maximum - }; - if self.schema != "ghostlight.elaborator_session_checkpoint.v1" - || !bounded(&self.session_id, 160) - || !bounded(&self.target_location_id, 240) - || !bounded(&self.frontier_summary, 4_000) - || self.unresolved_leads.len() > 32 - || self.unresolved_leads.iter().any(|lead| !bounded(lead, 600)) - || self.recent_commit_receipt_ids.len() > 64 - || self - .recent_commit_receipt_ids - .iter() - .any(|id| !bounded(id, 240)) - || self.recent_rejection_findings.len() > 32 - || self - .recent_rejection_findings - .iter() - .any(|finding| !bounded(finding, 800)) - || self - .prior_checkpoint_digest - .as_deref() - .is_some_and(|digest| !bounded(digest, 160)) - { - return Err(anyhow!( - "elaborator session checkpoint exceeds its bounded memory contract" - )); - } - Ok(()) - } - - fn recompute_digest(&self) -> Result { - crate::legacy_transition::digest_serializable(&( - "ghostlight.elaborator_session_checkpoint.v1", - &self.session_id, - self.title, - self.generation, - self.campaign_id, - self.through_world_revision, - &self.target_location_id, - &self.frontier_summary, - &self.unresolved_leads, - &self.recent_commit_receipt_ids, - &self.recent_rejection_findings, - &self.prior_checkpoint_digest, - )) - } -} - -#[derive(Clone, Debug, Serialize)] -#[serde(deny_unknown_fields)] -struct ElaboratorSessionCompactionFinding { - diagnostic: String, -} - -struct ElaboratorSessionCompactionTool { - workbench: serde_json::Value, -} - -#[async_trait] -impl crate::agent::ModelAgentTool for ElaboratorSessionCompactionTool { - type Action = ElaboratorSessionCompactionDraft; - type Output = ElaboratorSessionCompactionDraft; - type Finding = ElaboratorSessionCompactionFinding; - - fn action_schema(&self) -> std::result::Result { - let mut schema = serde_json::to_value(schema_for!(ElaboratorSessionCompactionDraft)) - .map_err(|error| error.to_string())?; - schema["properties"]["schema"] = - exact_schema("ghostlight.elaborator_session_compaction_draft.v1"); - schema["properties"]["frontier_summary"]["minLength"] = serde_json::json!(1); - schema["properties"]["frontier_summary"]["maxLength"] = serde_json::json!(4000); - schema["properties"]["unresolved_leads"]["maxItems"] = serde_json::json!(32); - schema["properties"]["unresolved_leads"]["items"]["minLength"] = serde_json::json!(1); - schema["properties"]["unresolved_leads"]["items"]["maxLength"] = serde_json::json!(600); - Ok(schema) - } - - fn initial_context_snapshot(&self) -> Option { - Some(self.workbench.clone()) - } - - async fn invoke( - &mut self, - action: Self::Action, - _context: &crate::agent::ModelAgentToolContext, - ) -> crate::agent::ModelAgentToolOutcome { - let bounded = |value: &str, maximum: usize| { - !value.trim().is_empty() && value.chars().count() <= maximum - }; - let mut findings = Vec::new(); - if action.schema != "ghostlight.elaborator_session_compaction_draft.v1" { - findings.push("compaction schema is unsupported".to_owned()); - } - if !bounded(&action.frontier_summary, 4_000) { - findings.push("frontier summary must contain 1 through 4000 characters".to_owned()); - } - if action.unresolved_leads.len() > 32 { - findings.push("compaction contains more than 32 unresolved leads".to_owned()); - } - for (index, lead) in action.unresolved_leads.iter().enumerate() { - if !bounded(lead, 600) { - findings.push(format!( - "unresolved lead {index} must contain 1 through 600 characters" - )); - } - } - if !findings.is_empty() { - return crate::agent::ModelAgentToolOutcome::Rejected { - finding: ElaboratorSessionCompactionFinding { - diagnostic: findings.join("; "), - }, - receipts: Vec::new(), - }; - } - crate::agent::ModelAgentToolOutcome::Accepted { - output: action, - receipts: Vec::new(), - } - } -} - -#[allow(clippy::too_many_arguments)] -pub async fn compact_elaborator_session( - model: &dyn crate::model::ModelPort, - campaign: &crate::domain::Campaign, - target_location_id: &str, - title: ElaboratorTitle, - session_id: &str, - prior: Option<&ElaboratorSessionCheckpoint>, - journal: &[ElaboratorSessionJournalEntry], - recent_rejection_findings: Vec, -) -> Result<( - ElaboratorSessionCheckpoint, - Vec, -)> { - let mut findings = Vec::new(); - if !campaign.locations.contains_key(target_location_id) { - findings.push(format!( - "target location {target_location_id:?} is absent from the canonical campaign" - )); - } - if journal.is_empty() && recent_rejection_findings.is_empty() { - findings.push( - "compaction requires an admitted mutation or a semantic rejection finding".to_owned(), - ); - } - if journal.len() > 64 { - findings.push(format!( - "journal contains {} entries; the maximum is 64", - journal.len() - )); - } - for (index, entry) in journal.iter().enumerate() { - if entry.world_revision > campaign.revision { - findings.push(format!( - "journal[{index}].world_revision {} exceeds canonical revision {}", - entry.world_revision, campaign.revision - )); - } - if entry.commit_receipt_id.trim().is_empty() { - findings.push(format!("journal[{index}].commit_receipt_id is empty")); - } - if entry.mutation_kind.trim().is_empty() { - findings.push(format!("journal[{index}].mutation_kind is empty")); - } - if entry.summary.trim().is_empty() { - findings.push(format!("journal[{index}].summary is empty")); - } - let summary_length = entry.summary.chars().count(); - if summary_length > 1_000 { - findings.push(format!( - "journal[{index}].summary contains {summary_length} characters; the maximum is 1000" - )); - } - if entry.affected_subject_ids.len() > 32 { - findings.push(format!( - "journal[{index}].affected_subject_ids contains {} subjects; the maximum is 32", - entry.affected_subject_ids.len() - )); - } - } - if recent_rejection_findings.len() > 32 { - findings.push(format!( - "recent_rejection_findings contains {} entries; the maximum is 32", - recent_rejection_findings.len() - )); - } - for (index, finding) in recent_rejection_findings.iter().enumerate() { - let length = finding.trim().chars().count(); - if length == 0 || length > 800 { - findings.push(format!( - "recent_rejection_findings[{index}] contains {length} characters; the permitted range is 1 through 800" - )); - } - } - if !findings.is_empty() { - return Err(anyhow!( - "elaborator session compaction preflight failed: {}", - findings.join("; ") - )); - } - if let Some(prior) = prior { - prior.validate_for(campaign, target_location_id, title)?; - } - let generation = prior.map_or(0, |checkpoint| checkpoint.generation.saturating_add(1)); - let snapshot_binding = crate::legacy_transition::digest_serializable(&( - "ghostlight.elaborator_session_compaction_snapshot.v1", - campaign.id, - campaign.revision, - target_location_id, - title, - session_id, - prior.map(|checkpoint| checkpoint.digest.as_str()), - journal, - &recent_rejection_findings, - ))?; - let instructions = format!( - "You compact working memory for the {} elaborator. {} Preserve the causal frontier, unfinished structural leads, and useful rejected paths. Do not invent commits, subjects, facts, or completed work. The canonical world and exact journal remain authoritative; your summary only steers the next turn.", - title.display_name(), - title.mandate(), - ); - let spec = crate::agent::ModelAgentSpec { - stage: format!( - "world-elaboration-{}-session-compaction", - title.display_name().to_ascii_lowercase() - ), - model: crate::model::MODEL_FAST.into(), - snapshot_binding, - instructions, - source_receipt_ids: Vec::new(), - temperature: Some(0.1), - max_output_tokens: Some(1_400), - max_steps: 2, - }; - let mut tool = ElaboratorSessionCompactionTool { - workbench: serde_json::json!({ - "schema":"ghostlight.elaborator_session_compaction_workbench.v1", - "prior_checkpoint":prior, - "recent_admitted_journal":journal, - "recent_rejection_findings":recent_rejection_findings, - "through_world_revision":campaign.revision, - "target_location_id":target_location_id, - }), - }; - let run = crate::agent::run_model_agent(model, &spec, &mut tool) - .await - .map_err(|failure| anyhow!(failure.message))?; - let checkpoint = ElaboratorSessionCheckpoint::bind_compaction( - session_id, - title, - generation, - campaign.id, - campaign.revision, - target_location_id, - run.output, - journal - .iter() - .map(|entry| entry.commit_receipt_id.clone()) - .collect(), - recent_rejection_findings, - prior.map(|checkpoint| checkpoint.digest.clone()), - )?; - Ok((checkpoint, run.receipts)) -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct ElaborationDispatchState { - pub schema: String, - pub profile_digest: String, - /// Smooth weighted-round-robin credit across every enabled title. Blocked - /// selections consume their configured slots without invoking an agent, - /// so their share is never donated to another elaborator. - pub current_scores: BTreeMap, - pub dispatch_counts: BTreeMap, - pub total_budget_slots: u64, - pub total_dispatches: u64, -} - -impl Default for ElaborationDispatchState { - fn default() -> Self { - Self { - schema: "ghostlight.elaboration_dispatch_state.v1".into(), - profile_digest: String::new(), - current_scores: BTreeMap::new(), - dispatch_counts: BTreeMap::new(), - total_budget_slots: 0, - total_dispatches: 0, - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct ElaborationDispatch { - pub schema: String, - pub budget_ordinal: u64, - pub ordinal: u64, - pub title: ElaboratorTitle, - pub title_weight: u16, - pub total_enabled_weight: u32, - /// Requested share of the complete configured invocation budget. - pub requested_share_millionths: u32, - pub title_dispatch_count: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct ElaborationScheduleReceipt { - pub schema: String, - pub requested_invocations: u32, - pub unused_invocations: u32, - pub eligible_titles: BTreeSet, - /// Actual invocations allocated inside this receipt's budget window. - pub dispatch_counts: BTreeMap, - /// Configured allocations that could not invoke their titled agent. These - /// remain unused instead of being redistributed to another slider. - pub unused_counts: BTreeMap, - pub dispatches: Vec, - pub final_state: ElaborationDispatchState, -} - -enum ElaborationBudgetAllocation { - Dispatch(ElaborationDispatch), - Unused(ElaboratorTitle), -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct ElaborationWaveBinding { - pub schema: String, - /// Content-addressed or revision-addressed identity for the immutable - /// world projection shared by every invocation in this wave. - pub snapshot_binding: String, -} - -impl ElaborationWaveBinding { - pub fn validate(&self) -> Result<()> { - if self.schema != "ghostlight.elaboration_wave_binding.v1" { - return Err(anyhow!("elaboration wave binding schema is unsupported")); - } - if self.snapshot_binding.trim().is_empty() { - return Err(anyhow!("elaboration wave snapshot binding cannot be empty")); - } - Ok(()) - } -} - -#[derive(Clone, Debug)] -pub struct ElaborationSubAgentInvocation { - pub wave: ElaborationWaveBinding, - pub dispatch: ElaborationDispatch, -} - -#[derive(Debug)] -pub struct ElaborationInvocation { - pub wave: ElaborationWaveBinding, - pub dispatch: ElaborationDispatch, - /// A proposal against the frozen elaboration snapshot. The invocation - /// cannot commit canonical world state; admission and conflict handling - /// remain downstream owners. - pub proposal: Proposal, - /// Exact model/tool ancestry for this proposal. These receipts are audit - /// evidence only; they never become source evidence or mutation authority. - pub model_stage_receipts: Vec, -} - -#[derive(Debug)] -pub struct ElaborationSubAgentOutput { - pub proposal: Proposal, - pub model_stage_receipts: Vec, -} - -impl ElaborationSubAgentOutput { - pub fn deterministic(proposal: Proposal) -> Self { - Self { - proposal, - model_stage_receipts: Vec::new(), - } - } -} - -#[derive(Clone, Debug)] -pub struct ElaborationSubAgentFailure { - pub diagnostic: String, - pub model_stage_receipts: Vec, -} - -impl std::fmt::Display for ElaborationSubAgentFailure { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter.write_str(&self.diagnostic) - } -} - -impl std::error::Error for ElaborationSubAgentFailure {} - -#[derive(Debug)] -pub struct ElaborationWaveRun { - wave: ElaborationWaveBinding, - schedule: ElaborationScheduleReceipt, - invocations: Vec>, -} - -impl ElaborationWaveRun { - pub fn wave(&self) -> &ElaborationWaveBinding { - &self.wave - } - - pub fn schedule(&self) -> &ElaborationScheduleReceipt { - &self.schedule - } - - pub fn invocations(&self) -> &[ElaborationInvocation] { - &self.invocations - } -} - -#[derive(Clone, Debug)] -pub struct ElaborationInvocationFailure { - pub dispatch: Option, - pub diagnostic: String, - pub model_stage_receipts: Vec, -} - -#[derive(Debug)] -pub struct ElaborationWaveFailure { - pub wave: Option, - pub schedule: Option, - pub completed_invocations: Vec>, - pub invocation_failures: Vec, -} - -#[async_trait] -pub trait ElaborationSubAgentPort: Send + Sync { - async fn invoke( - &self, - invocation: ElaborationSubAgentInvocation, - ) -> std::result::Result, ElaborationSubAgentFailure>; -} - -pub struct ElaborationScheduler { - weights: BTreeMap, - state: ElaborationDispatchState, -} - -impl ElaborationScheduler { - pub fn new(profile: &WorldElaborationProfile) -> Result { - Self::from_state(profile, ElaborationDispatchState::default()) - } - - pub fn from_state( - profile: &WorldElaborationProfile, - mut state: ElaborationDispatchState, - ) -> Result { - let weights = profile.weights()?; - let profile_digest = crate::legacy_transition::digest_serializable(&( - "ghostlight.world_elaboration_profile.v1", - &weights, - ))?; - if state.schema != "ghostlight.elaboration_dispatch_state.v1" { - return Err(anyhow!("elaboration dispatch state schema is unsupported")); - } - if state.profile_digest.is_empty() { - state.profile_digest = profile_digest; - } else if state.profile_digest != profile_digest { - return Err(anyhow!( - "elaboration dispatch state belongs to a different slider profile" - )); - } - state - .current_scores - .retain(|title, _| weights.contains_key(title)); - state - .dispatch_counts - .retain(|title, _| weights.contains_key(title)); - Ok(Self { weights, state }) - } - - pub fn state(&self) -> &ElaborationDispatchState { - &self.state - } - - fn next_allocation( - &mut self, - eligible_titles: &BTreeSet, - ) -> ElaborationBudgetAllocation { - let enabled = self - .weights - .iter() - .filter(|(_, weight)| **weight > 0) - .map(|(title, weight)| (*title, *weight)) - .collect::>(); - let total_enabled_weight = enabled - .iter() - .map(|(_, weight)| u32::from(*weight)) - .sum::(); - debug_assert!(total_enabled_weight > 0); - - let mut selected = None; - for (title, weight) in &enabled { - let score = self.state.current_scores.entry(*title).or_default(); - *score = score.saturating_add(i64::from(*weight)); - let candidate = (*title, *score); - if selected.is_none_or(|best: (ElaboratorTitle, i64)| candidate.1 > best.1) { - selected = Some(candidate); - } - } - let (title, _) = selected.expect("a valid profile requires one enabled title"); - *self.state.current_scores.entry(title).or_default() -= i64::from(total_enabled_weight); - self.state.total_budget_slots = self.state.total_budget_slots.saturating_add(1); - if !eligible_titles.contains(&title) { - return ElaborationBudgetAllocation::Unused(title); - } - - self.state.total_dispatches = self.state.total_dispatches.saturating_add(1); - let title_dispatch_count = self - .state - .dispatch_counts - .entry(title) - .and_modify(|count| *count = count.saturating_add(1)) - .or_insert(1); - let title_weight = self.weights[&title]; - ElaborationBudgetAllocation::Dispatch(ElaborationDispatch { - schema: "ghostlight.elaboration_dispatch.v1".into(), - budget_ordinal: self.state.total_budget_slots, - ordinal: self.state.total_dispatches, - title, - title_weight, - total_enabled_weight, - requested_share_millionths: u32::from(title_weight).saturating_mul(1_000_000) - / total_enabled_weight, - title_dispatch_count: *title_dispatch_count, - }) - } - - pub fn schedule( - &mut self, - eligible_titles: &BTreeSet, - invocation_budget: u32, - ) -> ElaborationScheduleReceipt { - let mut dispatches = Vec::with_capacity(invocation_budget as usize); - let mut unused_counts = BTreeMap::new(); - for _ in 0..invocation_budget { - match self.next_allocation(eligible_titles) { - ElaborationBudgetAllocation::Dispatch(dispatch) => dispatches.push(dispatch), - ElaborationBudgetAllocation::Unused(title) => { - *unused_counts.entry(title).or_default() += 1; - } - } - } - ElaborationScheduleReceipt { - schema: "ghostlight.elaboration_schedule_receipt.v1".into(), - requested_invocations: invocation_budget, - unused_invocations: unused_counts.values().copied().sum(), - eligible_titles: eligible_titles.clone(), - dispatch_counts: dispatches - .iter() - .fold(BTreeMap::new(), |mut counts, dispatch| { - *counts.entry(dispatch.title).or_default() += 1; - counts - }), - unused_counts, - dispatches, - final_state: self.state.clone(), - } - } -} - -/// Dispatches one immutable-snapshot elaboration wave. Weight determines the -/// number of actual sub-agent invocations, not prompt emphasis. Proposals are -/// returned in deterministic dispatch order after parallel execution; this -/// function has no canonical world-state writer. -pub async fn dispatch_elaboration_wave( - scheduler: &mut ElaborationScheduler, - wave: ElaborationWaveBinding, - eligible_titles: &BTreeSet, - invocation_budget: u32, - parallelism: usize, - worker: Arc, -) -> std::result::Result, ElaborationWaveFailure> -where - Worker: ElaborationSubAgentPort + 'static, - Proposal: Send + 'static, -{ - if let Err(error) = wave.validate() { - return Err(ElaborationWaveFailure { - wave: Some(wave), - schedule: None, - completed_invocations: Vec::new(), - invocation_failures: vec![ElaborationInvocationFailure { - dispatch: None, - diagnostic: error.to_string(), - model_stage_receipts: Vec::new(), - }], - }); - } - if parallelism == 0 { - return Err(ElaborationWaveFailure { - wave: Some(wave), - schedule: None, - completed_invocations: Vec::new(), - invocation_failures: vec![ElaborationInvocationFailure { - dispatch: None, - diagnostic: "elaboration wave parallelism must be greater than zero".into(), - model_stage_receipts: Vec::new(), - }], - }); - } - let schedule = scheduler.schedule(eligible_titles, invocation_budget); - let (invocations, invocation_failures) = invoke_elaboration_dispatches( - wave.clone(), - schedule.dispatches.iter().cloned().collect(), - parallelism, - worker, - ) - .await; - if !invocation_failures.is_empty() { - return Err(ElaborationWaveFailure { - wave: Some(wave), - schedule: Some(schedule), - completed_invocations: invocations, - invocation_failures, - }); - } - Ok(ElaborationWaveRun { - wave, - schedule, - invocations, - }) -} - -/// Resumes only the failed dispatches from one complete, immutable wave -/// checkpoint. The original schedule remains authoritative: successful -/// invocations are retained, scheduler state is not advanced, and every retry -/// keeps its exact title, ordinal, and frozen snapshot binding. -pub async fn resume_elaboration_wave( - failure: ElaborationWaveFailure, - parallelism: usize, - worker: Arc, -) -> std::result::Result, ElaborationWaveFailure> -where - Worker: ElaborationSubAgentPort + 'static, - Proposal: Send + 'static, -{ - let ElaborationWaveFailure { - wave, - schedule, - mut completed_invocations, - invocation_failures, - } = failure; - let Some(wave) = wave else { - return Err(ElaborationWaveFailure { - wave: None, - schedule, - completed_invocations, - invocation_failures, - }); - }; - let Some(schedule) = schedule else { - return Err(ElaborationWaveFailure { - wave: Some(wave), - schedule: None, - completed_invocations, - invocation_failures, - }); - }; - let checkpoint_error = validate_partial_wave_checkpoint( - &wave, - &schedule, - &completed_invocations, - &invocation_failures, - ) - .err() - .map(|error| error.to_string()) - .or_else(|| { - (parallelism == 0).then(|| "elaboration wave parallelism must be greater than zero".into()) - }); - if let Some(diagnostic) = checkpoint_error { - return Err(ElaborationWaveFailure { - wave: Some(wave), - schedule: Some(schedule), - completed_invocations, - invocation_failures: vec![ElaborationInvocationFailure { - dispatch: None, - diagnostic, - model_stage_receipts: Vec::new(), - }], - }); - } - let failed_dispatches = invocation_failures - .into_iter() - .map(|failure| failure.dispatch.expect("validated checkpoint dispatch")) - .collect::>(); - let (mut resumed_invocations, invocation_failures) = - invoke_elaboration_dispatches(wave.clone(), failed_dispatches, parallelism, worker).await; - completed_invocations.append(&mut resumed_invocations); - completed_invocations.sort_by_key(|invocation| invocation.dispatch.ordinal); - if !invocation_failures.is_empty() { - return Err(ElaborationWaveFailure { - wave: Some(wave), - schedule: Some(schedule), - completed_invocations, - invocation_failures, - }); - } - let run = ElaborationWaveRun { - wave, - schedule, - invocations: completed_invocations, - }; - if let Err(error) = validate_successful_wave_run(&run) { - return Err(ElaborationWaveFailure { - wave: Some(run.wave), - schedule: Some(run.schedule), - completed_invocations: run.invocations, - invocation_failures: vec![ElaborationInvocationFailure { - dispatch: None, - diagnostic: error.to_string(), - model_stage_receipts: Vec::new(), - }], - }); - } - Ok(run) -} - -async fn invoke_elaboration_dispatches( - wave: ElaborationWaveBinding, - dispatches: Vec, - parallelism: usize, - worker: Arc, -) -> ( - Vec>, - Vec, -) -where - Worker: ElaborationSubAgentPort + 'static, - Proposal: Send + 'static, -{ - let invocation_count = dispatches.len(); - let semaphore = Arc::new(tokio::sync::Semaphore::new(parallelism)); - let mut jobs = tokio::task::JoinSet::new(); - let mut task_dispatches = HashMap::new(); - for dispatch in dispatches { - let worker = worker.clone(); - let semaphore = semaphore.clone(); - let wave = wave.clone(); - let task_dispatch = dispatch.clone(); - let task = jobs.spawn(async move { - let _slot = - semaphore - .acquire_owned() - .await - .map_err(|_| ElaborationInvocationFailure { - dispatch: Some(dispatch.clone()), - diagnostic: "elaboration invocation gate closed".into(), - model_stage_receipts: Vec::new(), - })?; - let request = ElaborationSubAgentInvocation { - wave: wave.clone(), - dispatch: dispatch.clone(), - }; - let output = - worker - .invoke(request) - .await - .map_err(|error| ElaborationInvocationFailure { - dispatch: Some(dispatch.clone()), - diagnostic: error.diagnostic.chars().take(2_000).collect(), - model_stage_receipts: error.model_stage_receipts, - })?; - Ok::<_, ElaborationInvocationFailure>(ElaborationInvocation { - wave, - dispatch, - proposal: output.proposal, - model_stage_receipts: output.model_stage_receipts, - }) - }); - task_dispatches.insert(task.id(), task_dispatch); - } - - let mut invocations = Vec::with_capacity(invocation_count); - let mut invocation_failures = Vec::new(); - while let Some(result) = jobs.join_next_with_id().await { - match result { - Ok((task_id, Ok(invocation))) => { - task_dispatches.remove(&task_id); - invocations.push(invocation); - } - Ok((task_id, Err(failure))) => { - task_dispatches.remove(&task_id); - invocation_failures.push(failure); - } - Err(error) => invocation_failures.push(ElaborationInvocationFailure { - dispatch: task_dispatches.remove(&error.id()), - diagnostic: format!("elaboration sub-agent task failed: {error}"), - model_stage_receipts: Vec::new(), - }), - } - } - invocations.sort_by_key(|invocation| invocation.dispatch.ordinal); - invocation_failures.sort_by_key(|failure| { - failure - .dispatch - .as_ref() - .map(|dispatch| dispatch.ordinal) - .unwrap_or(u64::MAX) - }); - (invocations, invocation_failures) -} - -/// Provider-backed titled worker for one additive locality operation. The -/// model chooses content through the generic agent harness; a deterministic -/// tool checks the exact task assignment and frozen campaign namespace before -/// returning a proposal to wave admission. -pub struct ModelWorldElaborationWorker { - model: Arc, - campaign: Arc, - target_location_id: String, - request: String, - session_checkpoints: BTreeMap, -} - -impl ModelWorldElaborationWorker { - pub fn new( - model: Arc, - campaign: Arc, - target_location_id: impl Into, - request: impl Into, - ) -> Result { - let target_location_id = target_location_id.into(); - if !campaign.locations.contains_key(&target_location_id) { - return Err(anyhow!("world elaboration worker target is unknown")); - } - if !campaign.civic_systems.contains_key(&target_location_id) { - return Err(anyhow!( - "provider-backed titled elaboration currently requires an admitted civic foundation" - )); - } - Ok(Self { - model, - campaign, - target_location_id, - request: request.into(), - session_checkpoints: BTreeMap::new(), - }) - } - - pub fn with_session_checkpoints( - mut self, - checkpoints: BTreeMap, - ) -> Result { - for (title, checkpoint) in &checkpoints { - checkpoint.validate_for(&self.campaign, &self.target_location_id, *title)?; - } - self.session_checkpoints = checkpoints; - Ok(self) - } - - /// The exact semantic task shared by the worker wave, its artifacts, and - /// the independent verifier. Callers should read this value from the - /// prepared worker instead of retaining a second request owner. - pub fn task_request(&self) -> &str { - &self.request - } - - fn projection(&self) -> Result { - let civic = &self.campaign.civic_systems[&self.target_location_id]; - let subject_ids = civic - .governing_institution_ids - .iter() - .chain(civic.resident_population_ids.iter()) - .cloned() - .collect::>(); - let projection = serde_json::json!({ - "campaign_id":self.campaign.id, - "world_revision":self.campaign.revision, - "campaign_name":self.campaign.name, - "target_location":self.campaign.locations.get(&self.target_location_id), - "current_civic_system":civic, - "civic_institutions":subject_ids.iter().filter_map(|id|self.campaign.institutions.get(id)).collect::>(), - "civic_populations":subject_ids.iter().filter_map(|id|self.campaign.gestalts.get(id)).collect::>(), - "political_relations":civic.political_relation_ids.iter().filter_map(|id|self.campaign.agency_relations.get(id)).collect::>(), - "public_facts":civic.public_authority_fact_ids.iter() - .chain(civic.public_selection_fact_ids.iter()) - .chain(civic.public_resource_fact_ids.iter()) - .chain(civic.public_redress_fact_ids.iter()) - .filter_map(|id|self.campaign.facts.get(id)).collect::>(), - "existing_fact_namespace":self.campaign.facts.values().map(|fact|serde_json::json!({ - "id":fact.id, - "statement":fact.statement, - })).collect::>(), - "request":self.request, - }); - Ok(serde_json::to_string(&projection)?) - } -} - -/// Provider-backed worker for one causally meaningful Gestalt subdivision. -/// A round assigns distinct active parents against one frozen campaign. The -/// worker proposes only; callers must revalidate and commit each preview -/// through `WorldKernel::ElaborateGestaltFission`. -pub struct ModelWorldComplexityWorker { - model: Arc, - campaign: Arc, - wave: ElaborationWaveBinding, - first_dispatch_ordinal: u64, - parent_gestalt_ids: Vec, - parent_jurisdiction_ids: BTreeMap, - target_actionable_gains: BTreeMap, - session_checkpoints: BTreeMap, -} - -impl ModelWorldComplexityWorker { - pub fn new( - model: Arc, - campaign: Arc, - first_dispatch_ordinal: u64, - parent_gestalt_ids: Vec, - parent_jurisdiction_ids: BTreeMap, - actionable_subject_deficit: u32, - session_checkpoints: BTreeMap, - ) -> Result { - if parent_gestalt_ids.is_empty() - || parent_gestalt_ids.iter().collect::>().len() != parent_gestalt_ids.len() - { - return Err(anyhow!( - "complexity round requires distinct assigned parent Gestalts" - )); - } - if actionable_subject_deficit == 0 - || u32::try_from(parent_gestalt_ids.len()).unwrap_or(u32::MAX) - > actionable_subject_deficit - { - return Err(anyhow!( - "complexity round cannot dispatch more parents than its remaining subject deficit" - )); - } - for parent_id in &parent_gestalt_ids { - let profile = campaign.agency_profiles.get(parent_id); - if !campaign.gestalts.contains_key(parent_id) - || profile.is_none_or(|profile| { - !profile.active_leaf - || !profile.simulation_eligible - || profile.subject_kind != crate::domain::AgencySubjectKind::Gestalt - }) - { - return Err(anyhow!( - "complexity round parent is not an unresolved active Gestalt" - )); - } - let Some(jurisdiction_id) = parent_jurisdiction_ids.get(parent_id) else { - return Err(anyhow!( - "complexity round parent has no session jurisdiction" - )); - }; - let permitted_jurisdictions = BTreeSet::from([jurisdiction_id.clone()]); - if unique_containing_jurisdiction( - &campaign, - &campaign.agency_profiles[parent_id].location_ids, - &permitted_jurisdictions, - ) - .as_deref() - != Some(jurisdiction_id.as_str()) - { - return Err(anyhow!( - "complexity round session jurisdiction does not contain the parent location" - )); - } - } - if parent_jurisdiction_ids.len() != parent_gestalt_ids.len() { - return Err(anyhow!( - "complexity round session jurisdictions do not match assigned parents" - )); - } - let planned_gain = actionable_subject_deficit.min( - u32::try_from(parent_gestalt_ids.len()) - .unwrap_or(u32::MAX) - .saturating_mul(6), - ); - let parent_count = u32::try_from(parent_gestalt_ids.len()).unwrap_or(u32::MAX); - let base_gain = planned_gain / parent_count; - let remainder = planned_gain % parent_count; - let target_actionable_gains = parent_gestalt_ids - .iter() - .enumerate() - .map(|(index, _)| { - let index = u32::try_from(index).unwrap_or(u32::MAX); - let gain = base_gain.saturating_add(u32::from(index < remainder)); - Ok(( - first_dispatch_ordinal.saturating_add(u64::from(index)), - u8::try_from(gain.clamp(1, 6))?, - )) - }) - .collect::, std::num::TryFromIntError>>()?; - for (session_id, checkpoint) in &session_checkpoints { - if checkpoint.session_id != *session_id - || elaborator_session_id(checkpoint.title, &checkpoint.target_location_id) - != *session_id - { - return Err(anyhow!( - "complexity worker received a stale or misrouted session checkpoint" - )); - } - checkpoint.validate_for(&campaign, &checkpoint.target_location_id, checkpoint.title)?; - } - let wave = ElaborationWaveBinding { - schema: "ghostlight.elaboration_wave_binding.v1".into(), - snapshot_binding: crate::legacy_transition::digest_serializable(&( - "ghostlight.world_complexity_round.v1", - campaign.id, - campaign.revision, - first_dispatch_ordinal, - &parent_gestalt_ids, - ))?, - }; - Ok(Self { - model, - campaign, - wave, - first_dispatch_ordinal, - parent_gestalt_ids, - parent_jurisdiction_ids, - target_actionable_gains, - session_checkpoints, - }) - } - - pub fn wave(&self) -> &ElaborationWaveBinding { - &self.wave - } - - fn parent_for(&self, dispatch: &ElaborationDispatch) -> Result<&str> { - let offset = dispatch - .ordinal - .checked_sub(self.first_dispatch_ordinal) - .ok_or_else(|| anyhow!("complexity dispatch predates its assigned round"))?; - self.parent_gestalt_ids - .get(usize::try_from(offset).unwrap_or(usize::MAX)) - .map(String::as_str) - .ok_or_else(|| anyhow!("complexity dispatch exceeds its assigned parent set")) - } -} - -fn complexity_partition_axis(title: ElaboratorTitle) -> crate::domain::AgencyAxis { - use crate::domain::AgencyAxis; - match title { - ElaboratorTitle::Patina | ElaboratorTitle::Hearth | ElaboratorTitle::Ember => { - AgencyAxis::Geography - } - ElaboratorTitle::Charter => AgencyAxis::Authority, - ElaboratorTitle::Ledger => AgencyAxis::EconomyRole, - ElaboratorTitle::Tangle | ElaboratorTitle::Numen => AgencyAxis::Ideology, - ElaboratorTitle::Veil => AgencyAxis::Information, - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum WorldComplexityOperation { - Fission, - Individuate, -} - -fn complexity_operation(title: ElaboratorTitle) -> WorldComplexityOperation { - match title { - ElaboratorTitle::Hearth | ElaboratorTitle::Tangle | ElaboratorTitle::Veil => { - WorldComplexityOperation::Individuate - } - _ => WorldComplexityOperation::Fission, - } -} - -/// One proposed increase in causally meaningful world resolution. This is -/// deliberately the same command algebra the kernel already owns: elaborators -/// may either split a population into distinct active leaves or promote one -/// consequential person from it. They do not own a parallel subject store. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)] -pub enum WorldComplexityProposal { - Fission { - preview: crate::domain::GestaltFissionPreview, - qualification: WorldComplexityFissionQualification, - }, - Individuate { - individuation: crate::domain::GestaltIndividuation, - qualification: WorldComplexityIndividuationQualification, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] -#[serde(deny_unknown_fields)] -pub struct WorldComplexitySemanticQualification { - pub schema: String, - pub identity_namespace: String, - pub frozen_campaign_id: Uuid, - pub frozen_world_revision: u64, - pub established_names_digest: String, - pub semantic_context_digest: String, - pub owner_lane_digest: String, - pub candidate_digest: String, - pub semantic_verification_binding: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldComplexityFissionQualification { - pub schema: String, - pub title: ElaboratorTitle, - pub jurisdiction_location_id: String, - pub target_actionable_gain: u8, - #[serde(default)] - pub semantic: WorldComplexitySemanticQualification, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldComplexityIndividuationQualification { - pub schema: String, - pub title: ElaboratorTitle, - pub jurisdiction_location_id: String, - #[serde(default)] - pub semantic: WorldComplexitySemanticQualification, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct WorldComplexityAction { - schema: String, - mutation: WorldComplexityMutationDraft, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)] -enum WorldComplexityMutationDraft { - Fission { - children: Vec, - residual_child_id: String, - member_child_assignments: BTreeMap, - resource_child_assignments: BTreeMap, - }, - Individuate { - member: WorldComplexityMemberDraft, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct WorldComplexityChildDraft { - id: String, - name: String, - partition_value: String, - home_location_id: String, - capability_additions: BTreeSet, - knowledge_additions: BTreeSet, - goals_add: Vec, - pressures_add: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct WorldComplexityMemberDraft { - id: String, - name: String, - capability_additions: BTreeSet, - capability_removals: BTreeSet, - knowledge_additions: BTreeSet, - knowledge_removals: BTreeSet, - equipment: BTreeSet, - conditions: BTreeSet, - obligations: BTreeSet, - relationships: BTreeMap, - goals: Vec, - memories: Vec, -} - -impl From for WorldComplexityMemberDraft { - fn from(member: crate::domain::GestaltMemberDelta) -> Self { - Self { - id: member.id, - name: member.name, - capability_additions: member.capability_additions, - capability_removals: member.capability_removals, - knowledge_additions: member.knowledge_additions, - knowledge_removals: member.knowledge_removals, - equipment: member.equipment, - conditions: member.conditions, - obligations: member.obligations, - relationships: member.relationships, - goals: member.goals, - memories: member.memories, - } - } -} - -impl WorldComplexityProposal { - pub fn parent_gestalt_id(&self) -> &str { - match self { - Self::Fission { preview, .. } => &preview.parent_gestalt_id, - Self::Individuate { individuation, .. } => &individuation.gestalt_id, - } - } - - pub fn mutation_kind(&self) -> &'static str { - match self { - Self::Fission { .. } => "elaborate_gestalt_fission", - Self::Individuate { .. } => "elaborate_gestalt_individuation", - } - } - - pub fn expected_world_revision(&self) -> u64 { - match self { - Self::Fission { preview, .. } => preview.expected_world_revision, - Self::Individuate { qualification, .. } => qualification.semantic.frozen_world_revision, - } - } -} - -/// Rebinds only the optimistic revision of a proposal produced in a frozen -/// parallel round. The assigned parent, its active profile, and all of its -/// member state must remain byte-identical; unrelated earlier commits may not -/// force an expensive proposal replay. -pub fn world_complexity_parent_binding( - campaign: &crate::domain::Campaign, - parent_gestalt_id: &str, -) -> Result { - let members = campaign - .gestalt_members - .values() - .filter(|member| member.gestalt_id == parent_gestalt_id) - .collect::>(); - crate::legacy_transition::digest_serializable(&( - "ghostlight.world_complexity_parent.v1", - campaign.id, - campaign.gestalts.get(parent_gestalt_id), - campaign.agency_profiles.get(parent_gestalt_id), - members, - )) -} - -pub fn rebase_world_complexity_proposal( - frozen_parent_binding: &str, - current: &crate::domain::Campaign, - mut proposal: WorldComplexityProposal, -) -> Result { - let parent_id = proposal.parent_gestalt_id().to_owned(); - if world_complexity_parent_binding(current, &parent_id)? != frozen_parent_binding { - return Err(anyhow!( - "complexity mutation parent changed after its frozen proposal" - )); - } - match &mut proposal { - WorldComplexityProposal::Fission { - preview, - qualification, - } => { - if qualification.schema != "ghostlight.world_complexity_fission_qualification.v1" - || !(1..=6).contains(&qualification.target_actionable_gain) - { - return Err(anyhow!( - "complexity fission qualification is unsupported or out of range" - )); - } - if preview.campaign_id != current.id { - return Err(anyhow!("complexity fission belongs to another campaign")); - } - preview.expected_world_revision = current.revision; - reconcile_fission_child_id_collisions(current, preview)?; - crate::resolution::validate_elaborated_fission(current, preview)?; - validate_complexity_fission_semantics( - current, - ¤t.gestalts[&preview.parent_gestalt_id], - preview, - qualification.title, - &qualification.jurisdiction_location_id, - qualification.target_actionable_gain, - )?; - } - WorldComplexityProposal::Individuate { individuation, .. } => { - crate::resolution::validate_gestalt_individuation(current, individuation)?; - } - } - Ok(proposal) -} - -fn reconcile_fission_child_id_collisions( - current: &crate::domain::Campaign, - preview: &mut crate::domain::GestaltFissionPreview, -) -> Result<()> { - let mut replacements = BTreeMap::new(); - for child in &preview.children { - if crate::resolution::canonical_subject_id_is_occupied(current, &child.id) { - let digest = crate::legacy_transition::digest_serializable(&( - "ghostlight.fission_child_id.v1", - current.id, - &preview.parent_gestalt_id, - &child.id, - ))?; - let suffix = digest - .strip_prefix("sha256:") - .unwrap_or(&digest) - .chars() - .take(16) - .collect::(); - let replacement = format!("{}:fission:{suffix}", preview.parent_gestalt_id); - if crate::resolution::canonical_subject_id_is_occupied(current, &replacement) - || preview - .children - .iter() - .any(|other| other.id == replacement && other.id != child.id) - || replacements.values().any(|other| other == &replacement) - { - return Err(anyhow!( - "deterministic fission child id reconciliation collided" - )); - } - replacements.insert(child.id.clone(), replacement); - } - } - if replacements.is_empty() { - return Ok(()); - } - for child in &mut preview.children { - if let Some(replacement) = replacements.get(&child.id) { - child.id = replacement.clone(); - } - } - preview.child_partition_values = preview - .child_partition_values - .iter() - .map(|(child_id, value)| { - ( - replacements - .get(child_id) - .cloned() - .unwrap_or_else(|| child_id.clone()), - value.clone(), - ) - }) - .collect(); - if let Some(replacement) = replacements.get(&preview.residual_child_id) { - preview.residual_child_id = replacement.clone(); - } - for child_id in preview.member_child_assignments.values_mut() { - if let Some(replacement) = replacements.get(child_id) { - *child_id = replacement.clone(); - } - } - for child_id in preview.resource_child_assignments.values_mut() { - if let Some(replacement) = replacements.get(child_id) { - *child_id = replacement.clone(); - } - } - Ok(()) -} - -#[derive(Clone, Debug, Serialize)] -#[serde(deny_unknown_fields)] -struct WorldComplexityFinding { - diagnostic: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldComplexitySemanticVerification { - pub public_names_are_legible_identifiers: bool, - pub names_do_not_repeat_an_overused_template: bool, - pub cultural_resemblance_is_grounded_not_quota_cloning: bool, - pub causal_additions_are_materially_distinct: bool, - pub causal_additions_do_not_repeat_an_overused_procedural_template: bool, - #[schemars(length(min = 1, max = 1_000))] - pub rationale: String, -} - -struct WorldComplexityTool<'a> { - campaign: &'a crate::domain::Campaign, - parent_gestalt_id: &'a str, - title: ElaboratorTitle, - operation: WorldComplexityOperation, - partition_axis: crate::domain::AgencyAxis, - jurisdiction_location_id: &'a str, - target_actionable_gain: u8, - workbench: serde_json::Value, -} - -pub fn locations_in_jurisdiction( - campaign: &crate::domain::Campaign, - jurisdiction_location_id: &str, -) -> Vec { - let jurisdictions = BTreeSet::from([jurisdiction_location_id.to_owned()]); - campaign - .locations - .keys() - .filter(|location_id| { - unique_containing_jurisdiction( - campaign, - &BTreeSet::from([(*location_id).clone()]), - &jurisdictions, - ) - .as_deref() - == Some(jurisdiction_location_id) - }) - .cloned() - .collect() -} - -fn semantic_text_key(value: &str) -> String { - value - .split_whitespace() - .flat_map(|part| part.chars()) - .filter(|character| character.is_alphanumeric()) - .flat_map(char::to_lowercase) - .collect() -} - -fn world_complexity_semantic_candidate_digest( - proposal: &WorldComplexityProposal, -) -> Result { - let candidate = match proposal { - WorldComplexityProposal::Fission { preview, .. } => serde_json::json!({ - "operation":"fission", - "parent_gestalt_id":preview.parent_gestalt_id, - "partition_axis":preview.partition_axis, - "specific_children":preview.children.iter() - .filter(|child|child.id != preview.residual_child_id) - .map(|child|serde_json::json!({ - "name":child.name, - "partition_value":preview.child_partition_values.get(&child.id), - "home_location_id":child.home_location_id, - "capabilities":child.shared_capabilities, - "knowledge":child.shared_knowledge, - "goals":child.goals, - "pressures":child.pressures, - })).collect::>(), - }), - WorldComplexityProposal::Individuate { individuation, .. } => serde_json::json!({ - "operation":"individuate", - "parent_gestalt_id":individuation.gestalt_id, - "location_id":individuation.location_id, - "member":individuation.member, - }), - }; - crate::legacy_transition::digest_serializable(&( - "ghostlight.world_complexity_semantic_candidate.v1", - candidate, - )) -} - -fn world_complexity_semantic_verification_binding( - semantic: &WorldComplexitySemanticQualification, -) -> Result { - crate::legacy_transition::digest_serializable(&( - "ghostlight.world_complexity_semantic_verification.v1", - semantic.frozen_campaign_id, - semantic.frozen_world_revision, - &semantic.identity_namespace, - &semantic.established_names_digest, - &semantic.semantic_context_digest, - &semantic.owner_lane_digest, - &semantic.candidate_digest, - )) -} - -fn world_complexity_owner_lane_digest(proposal: &WorldComplexityProposal) -> Result { - let lane = match proposal { - WorldComplexityProposal::Fission { qualification, .. } => serde_json::json!({ - "operation":"fission", - "title":qualification.title, - "jurisdiction_location_id":qualification.jurisdiction_location_id, - "target_actionable_gain":qualification.target_actionable_gain, - }), - WorldComplexityProposal::Individuate { qualification, .. } => serde_json::json!({ - "operation":"individuate", - "title":qualification.title, - "jurisdiction_location_id":qualification.jurisdiction_location_id, - }), - }; - crate::legacy_transition::digest_serializable(&( - "ghostlight.world_complexity_owner_lane.v1", - lane, - )) -} - -pub fn validate_world_complexity_semantic_qualification_shape( - proposal: &WorldComplexityProposal, - semantic: &WorldComplexitySemanticQualification, -) -> Result<()> { - let expected_namespace = match proposal { - WorldComplexityProposal::Fission { .. } => "population", - WorldComplexityProposal::Individuate { .. } => "person", - }; - if semantic.schema != "ghostlight.world_complexity_semantic_qualification.v1" - || semantic.identity_namespace != expected_namespace - || semantic.candidate_digest != world_complexity_semantic_candidate_digest(proposal)? - || semantic.established_names_digest.trim().is_empty() - || semantic.semantic_context_digest.trim().is_empty() - || semantic.owner_lane_digest != world_complexity_owner_lane_digest(proposal)? - || semantic.semantic_verification_binding - != world_complexity_semantic_verification_binding(semantic)? - { - return Err(anyhow!( - "world-complexity semantic qualification is malformed or bound to another candidate" - )); - } - Ok(()) -} - -pub fn validate_world_complexity_semantic_qualification( - campaign: &crate::domain::Campaign, - proposal: &WorldComplexityProposal, - semantic: &WorldComplexitySemanticQualification, -) -> Result<()> { - validate_world_complexity_semantic_qualification_shape(proposal, semantic)?; - let expected_namespace = match proposal { - WorldComplexityProposal::Fission { .. } => "population", - WorldComplexityProposal::Individuate { .. } => "person", - }; - let established_names = match expected_namespace { - "population" => { - let residual_ids = residual_gestalt_ids(campaign); - campaign - .gestalts - .values() - .filter(|gestalt| !residual_ids.contains(&gestalt.id)) - .map(|gestalt| gestalt.name.as_str()) - .collect::>() - } - "person" => campaign - .actors - .values() - .map(|actor| actor.name.as_str()) - .chain(campaign.gestalt_members.values().filter_map(|member| { - member - .materialized_actor_id - .is_none() - .then_some(member.name.as_str()) - })) - .collect::>(), - _ => unreachable!("semantic namespace is fixed above"), - }; - let expected_names_digest = crate::legacy_transition::digest_serializable(&( - "ghostlight.world_complexity_established_names.v1", - expected_namespace, - established_names, - ))?; - if semantic.frozen_campaign_id != campaign.id - || semantic.frozen_world_revision != campaign.revision - || semantic.established_names_digest != expected_names_digest - { - return Err(anyhow!( - "world-complexity semantic qualification is stale, malformed, or bound to another candidate" - )); - } - Ok(()) -} - -pub fn validate_world_complexity_semantic_receipt_provenance( - proposal: &WorldComplexityProposal, - semantic: &WorldComplexitySemanticQualification, - receipts: &[crate::model::ModelStageReceipt], -) -> Result<()> { - validate_world_complexity_semantic_qualification_shape(proposal, semantic)?; - let receipt_keys = receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - if receipt_keys.len() != receipts.len() { - return Err(anyhow!( - "world-complexity semantic provenance contains duplicate model receipts" - )); - } - let verifier_receipts = receipts - .iter() - .filter(|receipt| receipt.stage == "world-complexity-semantic-verification") - .collect::>(); - if verifier_receipts.len() != 1 { - return Err(anyhow!( - "world-complexity semantic qualification needs exactly one valid bound verifier receipt" - )); - } - let verifier = verifier_receipts[0]; - let expected_sources = receipts - .iter() - .filter(|receipt| receipt.stage != "world-complexity-semantic-verification") - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - let actual_sources = verifier - .source_receipt_ids - .iter() - .cloned() - .collect::>(); - if verifier.model != crate::model::MODEL_BALANCED - || verifier.validation_result != "valid" - || verifier.local_validation_error.is_some() - || verifier.snapshot_binding != semantic.semantic_verification_binding - || expected_sources.is_empty() - || actual_sources.len() != verifier.source_receipt_ids.len() - || actual_sources != expected_sources - { - return Err(anyhow!( - "world-complexity semantic verifier ancestry does not exactly cover its generation receipts" - )); - } - Ok(()) -} - -pub(crate) fn validate_world_complexity_semantic_provenance( - campaign: &crate::domain::Campaign, - proposal: &WorldComplexityProposal, - semantic: &WorldComplexitySemanticQualification, - receipts: &[crate::model::ModelStageReceipt], -) -> Result<()> { - validate_world_complexity_semantic_qualification(campaign, proposal, semantic)?; - validate_world_complexity_semantic_receipt_provenance(proposal, semantic, receipts) -} - -impl WorldComplexitySemanticVerification { - pub fn accepted(&self) -> bool { - self.public_names_are_legible_identifiers - && self.names_do_not_repeat_an_overused_template - && self.cultural_resemblance_is_grounded_not_quota_cloning - && self.causal_additions_are_materially_distinct - && self.causal_additions_do_not_repeat_an_overused_procedural_template - && !self.rationale.trim().is_empty() - } -} - -pub async fn qualify_world_complexity_proposal_semantics( - model: &dyn crate::model::ModelPort, - campaign: &crate::domain::Campaign, - semantic_comparison_context: &serde_json::Value, - mut proposal: WorldComplexityProposal, - source_receipt_ids: Vec, -) -> Result<( - WorldComplexityProposal, - WorldComplexitySemanticVerification, - crate::model::ModelStageReceipt, -)> { - if source_receipt_ids.is_empty() { - return Err(anyhow!( - "world-complexity semantic verification has no source generation receipt" - )); - } - let (identity_namespace, established_names) = match &proposal { - WorldComplexityProposal::Fission { .. } => { - let residual_ids = residual_gestalt_ids(campaign); - ( - "population", - campaign - .gestalts - .values() - .filter(|gestalt| !residual_ids.contains(&gestalt.id)) - .map(|gestalt| gestalt.name.as_str()) - .collect::>(), - ) - } - WorldComplexityProposal::Individuate { .. } => ( - "person", - campaign - .actors - .values() - .map(|actor| actor.name.as_str()) - .chain(campaign.gestalt_members.values().filter_map(|member| { - member - .materialized_actor_id - .is_none() - .then_some(member.name.as_str()) - })) - .collect::>(), - ), - }; - let established_names_digest = crate::legacy_transition::digest_serializable(&( - "ghostlight.world_complexity_established_names.v1", - identity_namespace, - &established_names, - ))?; - let semantic_context_digest = crate::legacy_transition::digest_serializable(&( - "ghostlight.world_complexity_semantic_context.v1", - semantic_comparison_context, - ))?; - let candidate_digest = world_complexity_semantic_candidate_digest(&proposal)?; - let mut qualification = WorldComplexitySemanticQualification { - schema: "ghostlight.world_complexity_semantic_qualification.v1".into(), - identity_namespace: identity_namespace.into(), - frozen_campaign_id: campaign.id, - frozen_world_revision: campaign.revision, - established_names_digest, - semantic_context_digest, - owner_lane_digest: world_complexity_owner_lane_digest(&proposal)?, - candidate_digest, - semantic_verification_binding: String::new(), - }; - qualification.semantic_verification_binding = - world_complexity_semantic_verification_binding(&qualification)?; - let parent = campaign - .gestalts - .get(proposal.parent_gestalt_id()) - .ok_or_else(|| anyhow!("world-complexity semantic proposal lost its parent"))?; - let prompt = format!( - "Independently judge one proposed world-complexity mutation against the current canonical world and the supplied recent peer context. This is semantic review, not a keyword or spelling rule. Every public name must be a legible person or population identifier, not a role label, serial placeholder, or lightly varied quota template. Reject an overused surname, epithet, grammatical mold, bureaucratic construction, or cultureless fantasy-name pattern unless actual kinship or local culture grounds the resemblance. Also reject goals, pressures, capabilities, knowledge, obligations, relationships, or memories that merely paraphrase an overused procedural mold (for example everybody filing, registering, petitioning, or serving on another council) without adding materially different means, stakes, affordances, or causal behavior. Repeated vocabulary is allowed when the concrete mechanism and consequence differ. Judge the proposal as a whole and return only the verdict object.\n\nIDENTITY NAMESPACE:\n{}\nCOMPLETE ESTABLISHED NAMES:\n{}\nPARENT POPULATION:\n{}\nRECENT SEMANTIC COMPARISON CONTEXT:\n{}\nCANDIDATE PROPOSAL:\n{}", - identity_namespace, - serde_json::to_string(&established_names)?, - serde_json::to_string(parent)?, - serde_json::to_string(semantic_comparison_context)?, - serde_json::to_string(&proposal)?, - ); - let request = crate::model::ModelStageRequest { - stage: "world-complexity-semantic-verification".into(), - model: crate::model::MODEL_BALANCED.into(), - snapshot_binding: qualification.semantic_verification_binding.clone(), - lived_stream: prompt, - output_schema: Some(serde_json::to_value(schema_for!( - WorldComplexitySemanticVerification - ))?), - source_receipt_ids, - temperature: Some(0.0), - max_output_tokens: Some(1_000), - }; - let output = crate::model::run_validated_stage(model, &request).await?; - let verdict = serde_json::from_value::( - output - .structured - .ok_or_else(|| anyhow!("semantic verifier returned no structured verdict"))?, - )?; - let mut receipt = output.receipt; - if !verdict.accepted() { - crate::model::mark_model_receipt_semantic_invalid( - &mut receipt, - &format!( - "world-complexity semantic verifier rejected the candidate: {}", - serde_json::to_string(&verdict).unwrap_or_else(|_| verdict.rationale.clone()) - ), - ); - } - match &mut proposal { - WorldComplexityProposal::Fission { - qualification: owner, - .. - } => owner.semantic = qualification, - WorldComplexityProposal::Individuate { - qualification: owner, - .. - } => owner.semantic = qualification, - } - Ok((proposal, verdict, receipt)) -} - -fn validate_new_semantic_texts<'a>( - label: &str, - additions: impl IntoIterator, - inherited: impl IntoIterator, - established: impl IntoIterator, -) -> Result> { - let inherited = inherited - .into_iter() - .map(|value| semantic_text_key(value)) - .collect::>(); - let established = established - .into_iter() - .map(|value| semantic_text_key(value)) - .collect::>(); - let mut keys = BTreeSet::new(); - for value in additions { - let key = semantic_text_key(value); - if value.trim().is_empty() || value.chars().count() > 300 || key.is_empty() { - return Err(anyhow!( - "{label} must contain 1 through 300 readable characters" - )); - } - if inherited.contains(&key) || established.contains(&key) || !keys.insert(key) { - return Err(anyhow!( - "{label} must add text distinct from its parent, siblings, and established world" - )); - } - } - Ok(keys) -} - -pub(crate) fn validate_complexity_fission_semantics( - campaign: &crate::domain::Campaign, - parent: &crate::domain::GestaltPersonaState, - preview: &crate::domain::GestaltFissionPreview, - title: ElaboratorTitle, - jurisdiction_location_id: &str, - target_actionable_gain: u8, -) -> Result<()> { - if complexity_operation(title) != WorldComplexityOperation::Fission { - return Err(anyhow!( - "complexity fission qualification names a non-fission elaborator" - )); - } - if preview.partition_axis != complexity_partition_axis(title) { - return Err(anyhow!( - "complexity fission partition axis does not belong to its elaborator title" - )); - } - let actual_gain = preview.children.len().saturating_sub(2); - if actual_gain != usize::from(target_actionable_gain) { - return Err(anyhow!( - "complexity fission must add exactly {target_actionable_gain} qualified subjects" - )); - } - let residual = preview - .children - .iter() - .find(|child| child.id == preview.residual_child_id) - .ok_or_else(|| anyhow!("complexity fission lost its residual child"))?; - if residual.home_location_id != parent.home_location_id - || residual.shared_capabilities != parent.shared_capabilities - || residual.shared_knowledge != parent.shared_knowledge - || residual.goals != parent.goals - || residual.pressures != parent.pressures - { - return Err(anyhow!( - "the residual child is unresolved background and cannot claim new semantic detail" - )); - } - - let residual_ids = residual_gestalt_ids(campaign); - let established_names = campaign - .gestalts - .values() - .filter(|gestalt| !residual_ids.contains(&gestalt.id)) - .map(|gestalt| crate::resolution::public_identity_key(&gestalt.name)) - .collect::>(); - let allowed_locations = locations_in_jurisdiction(campaign, jurisdiction_location_id) - .into_iter() - .collect::>(); - let mut child_names = BTreeSet::new(); - let mut sibling_capabilities = BTreeSet::new(); - let mut sibling_knowledge = BTreeSet::new(); - let mut sibling_goals = BTreeSet::new(); - let mut sibling_pressures = BTreeSet::new(); - let mut specific_homes = BTreeSet::new(); - for child in preview - .children - .iter() - .filter(|child| child.id != preview.residual_child_id) - { - let name_key = crate::resolution::public_identity_key(&child.name); - if name_key.is_empty() - || established_names.contains(&name_key) - || !child_names.insert(name_key) - { - return Err(anyhow!( - "every fission child needs a distinct public population identity" - )); - } - if !allowed_locations.contains(&child.home_location_id) { - return Err(anyhow!( - "fission child {} is outside its assigned jurisdiction", - child.id - )); - } - if preview.partition_axis != crate::domain::AgencyAxis::Geography - && child.home_location_id != parent.home_location_id - { - return Err(anyhow!( - "only a geography fission may distribute children to other admitted places" - )); - } - specific_homes.insert(child.home_location_id.clone()); - let capability_additions = child - .shared_capabilities - .difference(&parent.shared_capabilities) - .cloned() - .collect::>(); - let knowledge_additions = child - .shared_knowledge - .difference(&parent.shared_knowledge) - .cloned() - .collect::>(); - let goal_additions = child - .goals - .iter() - .filter(|goal| !parent.goals.contains(goal)) - .cloned() - .collect::>(); - let pressure_additions = child - .pressures - .iter() - .filter(|pressure| !parent.pressures.contains(pressure)) - .cloned() - .collect::>(); - let semantic_dimensions = [ - !capability_additions.is_empty(), - !knowledge_additions.is_empty(), - !goal_additions.is_empty(), - !pressure_additions.is_empty(), - ] - .into_iter() - .filter(|present| *present) - .count(); - if semantic_dimensions < 2 - || goal_additions.len() > 1 - || pressure_additions.len() > 1 - || capability_additions.len() > 2 - || knowledge_additions.len() > 2 - { - return Err(anyhow!( - "each specific child needs two or more bounded causal dimensions without template padding" - )); - } - let title_shape_is_valid = match title { - ElaboratorTitle::Patina => { - !goal_additions.is_empty() && !capability_additions.is_empty() - } - ElaboratorTitle::Charter | ElaboratorTitle::Ledger => { - !goal_additions.is_empty() - && !pressure_additions.is_empty() - && (!capability_additions.is_empty() || !knowledge_additions.is_empty()) - } - ElaboratorTitle::Ember => { - !pressure_additions.is_empty() - && (!capability_additions.is_empty() || !knowledge_additions.is_empty()) - } - ElaboratorTitle::Numen => { - !goal_additions.is_empty() - && !pressure_additions.is_empty() - && !knowledge_additions.is_empty() - } - ElaboratorTitle::Hearth | ElaboratorTitle::Tangle | ElaboratorTitle::Veil => false, - }; - if !title_shape_is_valid { - return Err(anyhow!( - "specific child additions do not satisfy the assigned elaborator's causal lane" - )); - } - let capability_keys = validate_new_semantic_texts( - "child capability", - capability_additions.iter(), - parent.shared_capabilities.iter(), - campaign - .gestalts - .values() - .flat_map(|gestalt| gestalt.shared_capabilities.iter()), - )?; - let knowledge_keys = validate_new_semantic_texts( - "child knowledge", - knowledge_additions.iter(), - parent.shared_knowledge.iter(), - campaign - .gestalts - .values() - .flat_map(|gestalt| gestalt.shared_knowledge.iter()), - )?; - let goal_keys = validate_new_semantic_texts( - "child goal", - goal_additions.iter(), - parent.goals.iter(), - campaign - .gestalts - .values() - .flat_map(|gestalt| gestalt.goals.iter()), - )?; - let pressure_keys = validate_new_semantic_texts( - "child pressure", - pressure_additions.iter(), - parent.pressures.iter(), - campaign - .gestalts - .values() - .flat_map(|gestalt| gestalt.pressures.iter()), - )?; - if !capability_keys.is_disjoint(&sibling_capabilities) - || !knowledge_keys.is_disjoint(&sibling_knowledge) - || !goal_keys.is_disjoint(&sibling_goals) - || !pressure_keys.is_disjoint(&sibling_pressures) - { - return Err(anyhow!( - "specific fission children must not repeat one another's causal additions" - )); - } - sibling_capabilities.extend(capability_keys); - sibling_knowledge.extend(knowledge_keys); - sibling_goals.extend(goal_keys); - sibling_pressures.extend(pressure_keys); - } - if preview.partition_axis == crate::domain::AgencyAxis::Geography - && allowed_locations.len() > 1 - && specific_homes.len() < 2 - { - return Err(anyhow!( - "geography fission must distribute specific children across at least two admitted places" - )); - } - Ok(()) -} - -pub(crate) fn validate_complexity_individuation_semantics( - campaign: &crate::domain::Campaign, - title: ElaboratorTitle, - individuation: &crate::domain::GestaltIndividuation, -) -> Result<()> { - if !matches!( - title, - ElaboratorTitle::Hearth | ElaboratorTitle::Tangle | ElaboratorTitle::Veil - ) { - return Err(anyhow!( - "only Hearth, Tangle, or Veil may own a complexity individuation" - )); - } - let member = &individuation.member; - let parent = &campaign.gestalts[&individuation.gestalt_id]; - let dimensions = [ - !member.capability_additions.is_empty(), - !member.knowledge_additions.is_empty(), - !member.equipment.is_empty(), - !member.obligations.is_empty(), - !member.relationships.is_empty(), - !member.goals.is_empty(), - !member.memories.is_empty(), - ] - .into_iter() - .filter(|present| *present) - .count(); - if dimensions < 3 || member.goals.is_empty() || member.memories.is_empty() { - return Err(anyhow!( - "complexity individuation needs a goal, a concrete memory, and at least one additional identity-bearing difference" - )); - } - validate_new_semantic_texts( - "member goal", - member.goals.iter(), - parent.goals.iter(), - campaign - .gestalt_members - .values() - .flat_map(|existing| existing.goals.iter()), - )?; - validate_new_semantic_texts( - "member memory", - member.memories.iter(), - std::iter::empty(), - campaign - .gestalt_members - .values() - .flat_map(|existing| existing.memories.iter()), - )?; - match title { - ElaboratorTitle::Hearth if member.obligations.is_empty() => Err(anyhow!( - "Hearth individuation requires one concrete care or belonging obligation" - )), - ElaboratorTitle::Tangle if member.relationships.is_empty() => Err(anyhow!( - "Tangle individuation requires a relationship to an existing canonical subject" - )), - ElaboratorTitle::Veil if member.knowledge_additions.is_empty() => Err(anyhow!( - "Veil individuation requires uneven knowledge not held by the parent population" - )), - _ => Ok(()), - } -} - -impl WorldComplexityTool<'_> { - fn materialize_proposal( - &self, - mutation: WorldComplexityMutationDraft, - ) -> Result { - let parent = &self.campaign.gestalts[self.parent_gestalt_id]; - match mutation { - WorldComplexityMutationDraft::Fission { - children, - residual_child_id, - member_child_assignments, - resource_child_assignments, - } => { - if self.operation != WorldComplexityOperation::Fission { - return Err(anyhow!("complexity action changed its assigned operation")); - } - let child_ids = children - .iter() - .map(|child| child.id.clone()) - .collect::>(); - let partition_values = children - .iter() - .map(|child| child.partition_value.trim().to_ascii_lowercase()) - .collect::>(); - let expected_members = self - .campaign - .gestalt_members - .values() - .filter(|member| member.gestalt_id == self.parent_gestalt_id) - .map(|member| member.id.clone()) - .collect::>(); - let assigned_members = member_child_assignments - .keys() - .cloned() - .collect::>(); - if child_ids.len() != children.len() - || partition_values.len() != children.len() - || assigned_members != expected_members - { - return Err(anyhow!( - "fission draft must use unique children and partitions and assign every exact member" - )); - } - let child_states = children - .iter() - .map(|child| { - let mut state = parent.clone(); - state.id = child.id.clone(); - state.name = child.name.clone(); - state.version = 0; - state.home_location_id = child.home_location_id.clone(); - state - .shared_capabilities - .extend(child.capability_additions.iter().cloned()); - state - .shared_knowledge - .extend(child.knowledge_additions.iter().cloned()); - state.goals.extend(child.goals_add.iter().cloned()); - state.pressures.extend(child.pressures_add.iter().cloned()); - state.resources = resource_child_assignments - .iter() - .filter(|(_, child_id)| *child_id == &child.id) - .map(|(resource, _)| resource.clone()) - .collect(); - state - }) - .collect::>(); - let preview = crate::domain::GestaltFissionPreview { - schema: "ghostlight.gestalt_fission_preview.v1".into(), - campaign_id: self.campaign.id, - expected_world_revision: self.campaign.revision, - parent_gestalt_id: self.parent_gestalt_id.into(), - partition_axis: self.partition_axis.clone(), - child_partition_values: children - .into_iter() - .map(|child| (child.id, child.partition_value)) - .collect(), - children: child_states, - residual_child_id, - member_child_assignments, - resource_child_assignments, - evidence_receipt_ids: Vec::new(), - gaps: Vec::new(), - canon_candidates: Vec::new(), - requires_approval: true, - }; - crate::resolution::validate_elaborated_fission(self.campaign, &preview)?; - validate_complexity_fission_semantics( - self.campaign, - parent, - &preview, - self.title, - self.jurisdiction_location_id, - self.target_actionable_gain, - )?; - Ok(WorldComplexityProposal::Fission { - preview, - qualification: WorldComplexityFissionQualification { - schema: "ghostlight.world_complexity_fission_qualification.v1".into(), - title: self.title, - jurisdiction_location_id: self.jurisdiction_location_id.into(), - target_actionable_gain: self.target_actionable_gain, - semantic: WorldComplexitySemanticQualification::default(), - }, - }) - } - WorldComplexityMutationDraft::Individuate { member } => { - if self.operation != WorldComplexityOperation::Individuate { - return Err(anyhow!("complexity action changed its assigned operation")); - } - let location_id = self.campaign.agency_profiles[self.parent_gestalt_id] - .location_ids - .iter() - .next() - .ok_or_else(|| anyhow!("complexity parent has no exact location"))? - .clone(); - let individuation = crate::domain::GestaltIndividuation { - gestalt_id: self.parent_gestalt_id.into(), - expected_gestalt_version: parent.version, - member: crate::domain::GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: member.id, - gestalt_id: self.parent_gestalt_id.into(), - version: 0, - name: member.name, - capability_additions: member.capability_additions, - capability_removals: member.capability_removals, - knowledge_additions: member.knowledge_additions, - knowledge_removals: member.knowledge_removals, - equipment: member.equipment, - conditions: member.conditions, - obligations: member.obligations, - relationships: member.relationships, - goals: member.goals, - memories: member.memories, - last_location_id: Some(location_id.clone()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }, - location_id, - }; - crate::resolution::validate_gestalt_individuation(self.campaign, &individuation)?; - validate_complexity_individuation_semantics( - self.campaign, - self.title, - &individuation, - )?; - Ok(WorldComplexityProposal::Individuate { - individuation, - qualification: WorldComplexityIndividuationQualification { - schema: "ghostlight.world_complexity_individuation_qualification.v1".into(), - title: self.title, - jurisdiction_location_id: self.jurisdiction_location_id.into(), - semantic: WorldComplexitySemanticQualification::default(), - }, - }) - } - } - } -} - -#[async_trait] -impl crate::agent::ModelAgentTool for WorldComplexityTool<'_> { - type Action = WorldComplexityAction; - type Output = WorldComplexityProposal; - type Finding = WorldComplexityFinding; - - fn action_schema(&self) -> std::result::Result { - let mut schema = serde_json::to_value(schema_for!(WorldComplexityAction)) - .map_err(|error| error.to_string())?; - schema["properties"]["schema"] = exact_schema("ghostlight.world_complexity_action.v1"); - if self.operation == WorldComplexityOperation::Fission { - let allowed_locations = - locations_in_jurisdiction(self.campaign, self.jurisdiction_location_id); - let child = &mut schema["$defs"]["WorldComplexityChildDraft"]; - child["properties"]["home_location_id"] = serde_json::json!({ - "type":"string", - "enum":allowed_locations, - }); - child["properties"]["id"]["minLength"] = serde_json::json!(1); - child["properties"]["id"]["maxLength"] = serde_json::json!(160); - child["properties"]["name"]["minLength"] = serde_json::json!(1); - child["properties"]["name"]["maxLength"] = serde_json::json!(160); - for field in ["capability_additions", "knowledge_additions"] { - child["properties"][field]["maxItems"] = serde_json::json!(2); - child["properties"][field]["items"]["minLength"] = serde_json::json!(1); - child["properties"][field]["items"]["maxLength"] = serde_json::json!(300); - } - for field in ["goals_add", "pressures_add"] { - child["properties"][field]["maxItems"] = serde_json::json!(1); - child["properties"][field]["items"]["minLength"] = serde_json::json!(1); - child["properties"][field]["items"]["maxLength"] = serde_json::json!(300); - } - } else { - let member = &mut schema["$defs"]["WorldComplexityMemberDraft"]; - member["properties"]["name"]["minLength"] = serde_json::json!(1); - member["properties"]["name"]["maxLength"] = serde_json::json!(160); - for field in ["goals", "memories"] { - member["properties"][field]["minItems"] = serde_json::json!(1); - member["properties"][field]["maxItems"] = serde_json::json!(8); - } - match self.title { - ElaboratorTitle::Hearth => { - member["properties"]["obligations"]["minItems"] = serde_json::json!(1); - } - ElaboratorTitle::Tangle => { - member["properties"]["relationships"]["minProperties"] = serde_json::json!(1); - } - ElaboratorTitle::Veil => { - member["properties"]["knowledge_additions"]["minItems"] = serde_json::json!(1); - } - _ => {} - } - } - let variants = schema - .pointer_mut("/$defs/WorldComplexityMutationDraft/oneOf") - .and_then(serde_json::Value::as_array_mut) - .ok_or_else(|| "complexity action schema has no mutation variants".to_owned())?; - let expected_operation = match self.operation { - WorldComplexityOperation::Fission => "fission", - WorldComplexityOperation::Individuate => "individuate", - }; - let selected = variants - .iter() - .position(|variant| { - variant - .pointer("/properties/operation/const") - .and_then(serde_json::Value::as_str) - == Some(expected_operation) - }) - .ok_or_else(|| { - format!("complexity action schema has no {expected_operation} variant") - })?; - let mut selected = variants.remove(selected); - if self.operation == WorldComplexityOperation::Fission { - let children = selected - .pointer_mut("/properties/children") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| "complexity fission schema has no children".to_owned())?; - let child_count = usize::from(self.target_actionable_gain).saturating_add(2); - children.insert("minItems".into(), serde_json::json!(child_count)); - children.insert("maxItems".into(), serde_json::json!(child_count)); - let parent = &self.campaign.gestalts[self.parent_gestalt_id]; - selected["properties"]["resource_child_assignments"] = - exact_keyed_string_map_schema(parent.resources.iter().cloned()); - selected["properties"]["member_child_assignments"] = exact_keyed_string_map_schema( - self.campaign - .gestalt_members - .values() - .filter(|member| member.gestalt_id == self.parent_gestalt_id) - .map(|member| member.id.clone()), - ); - } - *variants = vec![selected]; - Ok(schema) - } - - fn initial_context_snapshot(&self) -> Option { - Some(self.workbench.clone()) - } - - async fn invoke( - &mut self, - action: Self::Action, - _context: &crate::agent::ModelAgentToolContext, - ) -> crate::agent::ModelAgentToolOutcome { - if action.schema != "ghostlight.world_complexity_action.v1" { - return crate::agent::ModelAgentToolOutcome::Rejected { - finding: WorldComplexityFinding { - diagnostic: "complexity action schema is unsupported".into(), - }, - receipts: Vec::new(), - }; - } - match self.materialize_proposal(action.mutation) { - Ok(proposal) => crate::agent::ModelAgentToolOutcome::Accepted { - output: proposal, - receipts: Vec::new(), - }, - Err(error) => crate::agent::ModelAgentToolOutcome::Rejected { - finding: WorldComplexityFinding { - diagnostic: error.to_string(), - }, - receipts: Vec::new(), - }, - } - } -} - -#[async_trait] -impl ElaborationSubAgentPort for ModelWorldComplexityWorker { - async fn invoke( - &self, - invocation: ElaborationSubAgentInvocation, - ) -> std::result::Result< - ElaborationSubAgentOutput, - ElaborationSubAgentFailure, - > { - if invocation.wave != self.wave { - return Err(ElaborationSubAgentFailure { - diagnostic: "complexity invocation does not match its frozen round".into(), - model_stage_receipts: Vec::new(), - }); - } - let parent_id = - self.parent_for(&invocation.dispatch) - .map_err(|error| ElaborationSubAgentFailure { - diagnostic: error.to_string(), - model_stage_receipts: Vec::new(), - })?; - let parent = &self.campaign.gestalts[parent_id]; - let profile = &self.campaign.agency_profiles[parent_id]; - let axis = complexity_partition_axis(invocation.dispatch.title); - let operation = complexity_operation(invocation.dispatch.title); - let location_id = - profile - .location_ids - .iter() - .next() - .ok_or_else(|| ElaborationSubAgentFailure { - diagnostic: "complexity parent has no exact location".into(), - model_stage_receipts: Vec::new(), - })?; - let jurisdiction_id = self.parent_jurisdiction_ids.get(parent_id).ok_or_else(|| { - ElaborationSubAgentFailure { - diagnostic: "complexity parent lost its session jurisdiction".into(), - model_stage_receipts: Vec::new(), - } - })?; - let target_actionable_gain = *self - .target_actionable_gains - .get(&invocation.dispatch.ordinal) - .ok_or_else(|| ElaborationSubAgentFailure { - diagnostic: "complexity dispatch has no bounded actionable gain".into(), - model_stage_receipts: Vec::new(), - })?; - let session_id = elaborator_session_id(invocation.dispatch.title, jurisdiction_id); - let assignment = match operation { - WorldComplexityOperation::Fission => serde_json::json!({ - "operation":"fission_gestalt", - "parent_gestalt_id":parent_id, - "partition_axis":axis, - "target_actionable_gain":target_actionable_gain, - "exact_child_count":usize::from(target_actionable_gain) + 2, - "requirements":[ - "Return a ghostlight.world_complexity_action.v1 envelope whose mutation has operation=fission.", - "Create the exact assigned number of non-overlapping children with distinct partition values.", - "Exactly one residual child must have partition value other/unknown, remain at the parent home, and provide empty capability_additions, knowledge_additions, goals_add, and pressures_add.", - "Every specific child needs a unique public name and title-appropriate causal additions. Patina adds a concrete practice plus a goal; Charter and Ledger add a goal, pressure, and operational capability or knowledge; Ember adds pressure plus an operational capability or knowledge; Numen adds a goal, pressure, and uneven numinous knowledge.", - "A geography fission distributes specific children among admitted places in this jurisdiction. Other axes keep the parent home.", - "Assign every scarce resource and named member exactly once; materialized people retain their Actor identity while changing population affiliation.", - "Do not restate inherited capabilities, knowledge, goals, pressures, evidence, or approval fields in the additive fields." - ] - }), - WorldComplexityOperation::Individuate => serde_json::json!({ - "operation":"individuate_gestalt_member", - "parent_gestalt_id":parent_id, - "location_id":location_id, - "requirements":[ - "Return a ghostlight.world_complexity_action.v1 envelope whose mutation has operation=individuate and one compact member draft.", - "The deterministic tool owns schema, exact parent id, parent version, assigned location, materialization state, and relevance revisions; those fields are absent from your draft.", - "Create one consequential named person with a distinct full public name, at least one new goal, one situated memory, and one additional identity-bearing difference grounded in the parent state.", - "Hearth requires a concrete care or belonging obligation. Tangle requires leverage expressed as a relationship to one supplied canonical target. Veil requires uneven knowledge not held by the parent population.", - "Use a new local member id without the member: prefix.", - "Do not create quota names, unsupported relationships, or decorative biography." - ] - }), - }; - let instructions = format!( - "You are {}, one titled elaborator in an iterative world-complexity session. {} Perform exactly the assigned structural mutation where the frozen world supports consequential agency. Prefer one strong change over quota padding. Your proposal cannot commit, approve itself, or invent evidence.", - invocation.dispatch.title.display_name(), - invocation.dispatch.title.mandate(), - ); - let residual_ids = residual_gestalt_ids(&self.campaign); - let (public_identity_namespace, established_public_names) = match operation { - WorldComplexityOperation::Fission => ( - "population", - self.campaign - .gestalts - .values() - .filter(|gestalt| !residual_ids.contains(&gestalt.id)) - .map(|gestalt| gestalt.name.as_str()) - .collect::>(), - ), - WorldComplexityOperation::Individuate => ( - "person", - self.campaign - .actors - .values() - .map(|actor| actor.name.as_str()) - .chain( - self.campaign - .gestalt_members - .values() - .map(|member| member.name.as_str()), - ) - .collect::>(), - ), - }; - let workbench = serde_json::json!({ - "schema":"ghostlight.world_complexity_workbench.v1", - "frozen_world":{ - "campaign_id":self.campaign.id, - "world_revision":self.campaign.revision, - }, - "assignment":assignment, - "session_jurisdiction_id":jurisdiction_id, - "admitted_home_location_ids":locations_in_jurisdiction(&self.campaign, jurisdiction_id), - "canonical_relationship_target_ids":self.campaign.civic_systems.get(jurisdiction_id) - .into_iter() - .flat_map(|civic| civic.governing_institution_ids.iter().chain(civic.resident_population_ids.iter())) - .filter(|id|id.as_str()!=parent_id) - .take(64).cloned().collect::>(), - "public_identity_namespace":public_identity_namespace, - "established_names_in_this_identity_namespace":established_public_names, - "required_resource_assignment_ids":parent.resources, - "required_member_assignment_ids":self.campaign.gestalt_members.values() - .filter(|member|member.gestalt_id == parent_id) - .map(|member|member.id.clone()).collect::>(), - "parent":parent, - "parent_profile":profile, - "parent_members":self.campaign.gestalt_members.values() - .filter(|member|member.gestalt_id == parent_id).collect::>(), - "local_relations":self.campaign.agency_relations.values() - .filter(|relation|relation.from_subject_id == parent_id || relation.to_subject_id == parent_id) - .collect::>(), - "compacted_session":self.session_checkpoints.get(&session_id), - }); - let mut tool = WorldComplexityTool { - campaign: &self.campaign, - parent_gestalt_id: parent_id, - title: invocation.dispatch.title, - operation, - partition_axis: axis, - jurisdiction_location_id: jurisdiction_id, - target_actionable_gain, - workbench, - }; - let spec = crate::agent::ModelAgentSpec { - stage: format!( - "world-complexity-{}-{}", - invocation - .dispatch - .title - .display_name() - .to_ascii_lowercase(), - match operation { - WorldComplexityOperation::Fission => "fission", - WorldComplexityOperation::Individuate => "individuate", - } - ), - model: match invocation.dispatch.title { - ElaboratorTitle::Charter | ElaboratorTitle::Tangle => { - crate::model::MODEL_BALANCED.into() - } - ElaboratorTitle::Numen => crate::model::MODEL_CAPABLE.into(), - _ => crate::model::MODEL_FAST.into(), - }, - snapshot_binding: crate::legacy_transition::digest_serializable(&( - "ghostlight.world_complexity_invocation.v1", - &self.wave, - &invocation.dispatch, - parent_id, - )) - .map_err(|error| ElaborationSubAgentFailure { - diagnostic: error.to_string(), - model_stage_receipts: Vec::new(), - })?, - instructions, - source_receipt_ids: Vec::new(), - temperature: Some(0.35), - max_output_tokens: Some(4_000), - max_steps: 3, - }; - match crate::agent::run_model_agent(self.model.as_ref(), &spec, &mut tool).await { - Ok(run) => Ok(ElaborationSubAgentOutput { - proposal: run.output, - model_stage_receipts: run.receipts, - }), - Err(error) => Err(ElaborationSubAgentFailure { - diagnostic: error.message, - model_stage_receipts: error.receipts, - }), - } - } -} - -#[derive(Clone, Debug)] -enum WorldElaborationAssignment { - PatinaPlace { - child_location_id: String, - }, - PatinaOriginRoute { - child_location_id: String, - route_id: String, - }, - PatinaReturnRoute { - child_location_id: String, - route_id: String, - }, - PreserveCivicSystem { - system: crate::domain::CivicSystemManifest, - }, - AddFact { - fact_id: String, - }, - AddPoliticalRelation { - relation_id: String, - allowed_subject_ids: BTreeSet, - }, -} - -impl WorldElaborationAssignment { - fn for_dispatch( - campaign: &crate::domain::Campaign, - target_location_id: &str, - dispatch: &ElaborationDispatch, - ) -> Result { - let title_count = dispatch.title_dispatch_count; - let title_name = dispatch.title.display_name().to_ascii_lowercase(); - match dispatch.title { - ElaboratorTitle::Patina => { - let cycle = (title_count.saturating_sub(1) / 3).saturating_add(1); - let child_location_id = format!("elab:{target_location_id}:patina-place:{cycle}"); - match title_count.saturating_sub(1) % 3 { - 0 => Ok(Self::PatinaPlace { child_location_id }), - 1 => Ok(Self::PatinaOriginRoute { - child_location_id, - route_id: format!("elab:{target_location_id}:patina-route:{cycle}:out"), - }), - _ => Ok(Self::PatinaReturnRoute { - child_location_id, - route_id: format!("elab:{target_location_id}:patina-route:{cycle}:back"), - }), - } - } - ElaboratorTitle::Charter if title_count % 2 == 1 => { - let mut system = campaign - .civic_systems - .get(target_location_id) - .cloned() - .ok_or_else(|| anyhow!("Charter requires an admitted civic system"))?; - system.version = system.version.saturating_add(1); - system.semantic_verification_receipt_id.clear(); - Ok(Self::PreserveCivicSystem { system }) - } - ElaboratorTitle::Tangle if title_count % 2 == 1 => { - let civic = campaign - .civic_systems - .get(target_location_id) - .ok_or_else(|| anyhow!("Tangle requires an admitted civic system"))?; - let allowed_subject_ids = civic - .governing_institution_ids - .iter() - .chain(civic.resident_population_ids.iter()) - .cloned() - .collect::>(); - if allowed_subject_ids.len() < 2 { - return Err(anyhow!("Tangle requires at least two exact civic subjects")); - } - Ok(Self::AddPoliticalRelation { - relation_id: format!( - "elab:{target_location_id}:{title_name}-relation:{title_count}" - ), - allowed_subject_ids, - }) - } - _ => Ok(Self::AddFact { - fact_id: format!("elab:{target_location_id}:{title_name}-fact:{title_count}"), - }), - } - } - - fn instruction(&self, target_location_id: &str) -> Result { - let instruction = match self { - Self::PatinaPlace { child_location_id } => format!( - "Submit exactly one add_place operation. Its id must be {child_location_id:?}, container_id must be {target_location_id:?}, name must be concrete, and persistent_features must contain one or more durable visible local details. This is Patina's texture-bearing place; a later assigned operation supplies its routes." - ), - Self::PatinaOriginRoute { - child_location_id, - route_id, - } => format!( - "Submit exactly one add_route operation from {target_location_id:?}. route_id must be {route_id:?}; destination_id must be {child_location_id:?}; distance must be \"a short internal path\"; travel_minutes must be 3." - ), - Self::PatinaReturnRoute { - child_location_id, - route_id, - } => format!( - "Submit exactly one add_route operation from {child_location_id:?}. route_id must be {route_id:?}; destination_id must be {target_location_id:?}; distance must be \"a short internal path\"; travel_minutes must be 3." - ), - Self::PreserveCivicSystem { system } => format!( - "Submit exactly one set_civic_system operation containing this exact next-version manifest, byte-for-byte in meaning and with an empty semantic_verification_receipt_id: {}. Do not add or omit an ID; the independent verifier owns semantic acceptance.", - serde_json::to_string(system)? - ), - Self::AddFact { fact_id } => format!( - "Submit exactly one add_fact operation. The fact id must be {fact_id:?}; scope must be branch_local; evidence_receipt_ids must be empty; discoverable_at_location_ids must contain exactly {target_location_id:?}. Invent one concrete, consequential, title-appropriate statement that does not duplicate an existing fact." - ), - Self::AddPoliticalRelation { - relation_id, - allowed_subject_ids, - } => format!( - "Submit exactly one add_local_relation operation. Its schema must be {relation_schema:?}; id must be {relation_id:?}; both distinct endpoints must come from {}; kind must be alliance, rivalry, trade, communication, command, or coercion; strength must be 1 through 100; active must be true; evidence_receipt_ids must be empty.", - serde_json::to_string(allowed_subject_ids)?, - relation_schema = crate::domain::AgencyRelation::SCHEMA, - ), - }; - Ok(instruction) - } - - fn action_schema(&self, target_location_id: &str) -> Result { - let mut schema = serde_json::to_value(schema_for!(WorldElaborationProposal))?; - schema["properties"]["schema"] = serde_json::json!({ - "type":"string", - "const":"ghostlight.world_elaboration_proposal.v1", - }); - let operation = schema - .pointer_mut("/$defs/WorldElaborationOperation") - .ok_or_else(|| anyhow!("world elaboration schema has no operation definition"))?; - let variants = operation - .get_mut("oneOf") - .and_then(serde_json::Value::as_array_mut) - .ok_or_else(|| anyhow!("world elaboration operation schema has no typed variants"))?; - let expected_type = self.operation_type(); - let index = variants - .iter() - .position(|variant| { - variant - .pointer("/properties/type/const") - .and_then(serde_json::Value::as_str) - == Some(expected_type) - }) - .ok_or_else(|| { - anyhow!("world elaboration schema has no {expected_type} operation variant") - })?; - let selected = variants.remove(index); - *variants = vec![selected]; - - match self { - Self::PatinaPlace { child_location_id } => { - let branch = selected_operation_branch(&mut schema)?; - branch["properties"]["id"] = exact_schema(child_location_id); - branch["properties"]["container_id"] = exact_schema(target_location_id); - branch["properties"]["name"]["minLength"] = serde_json::json!(1); - branch["properties"]["persistent_features"]["minItems"] = serde_json::json!(1); - branch["required"] = serde_json::json!([ - "type", - "id", - "name", - "container_id", - "persistent_features" - ]); - } - Self::PatinaOriginRoute { - child_location_id, - route_id, - } => { - let branch = selected_operation_branch(&mut schema)?; - branch["properties"]["origin_location_id"] = exact_schema(target_location_id); - branch["properties"]["route_id"] = exact_schema(route_id); - constrain_exact_object( - schema.pointer_mut("/$defs/Route").ok_or_else(|| { - anyhow!("world elaboration schema has no route definition") - })?, - &serde_json::json!({ - "destination_id":child_location_id, - "distance":"a short internal path", - "travel_minutes":3, - }), - )?; - } - Self::PatinaReturnRoute { - child_location_id, - route_id, - } => { - let branch = selected_operation_branch(&mut schema)?; - branch["properties"]["origin_location_id"] = exact_schema(child_location_id); - branch["properties"]["route_id"] = exact_schema(route_id); - constrain_exact_object( - schema.pointer_mut("/$defs/Route").ok_or_else(|| { - anyhow!("world elaboration schema has no route definition") - })?, - &serde_json::json!({ - "destination_id":target_location_id, - "distance":"a short internal path", - "travel_minutes":3, - }), - )?; - } - Self::PreserveCivicSystem { system } => constrain_exact_object( - schema - .pointer_mut("/$defs/CivicSystemManifest") - .ok_or_else(|| anyhow!("world elaboration schema has no civic definition"))?, - &serde_json::to_value(system)?, - )?, - Self::AddFact { fact_id } => { - let fact = schema - .pointer_mut("/$defs/WorldFact") - .ok_or_else(|| anyhow!("world elaboration schema has no fact definition"))?; - fact["properties"]["id"] = exact_schema(fact_id); - fact["properties"]["scope"] = exact_schema("branch_local"); - fact["properties"]["evidence_receipt_ids"] = exact_schema(&Vec::::new()); - fact["properties"]["discoverable_at_location_ids"] = - exact_schema(&vec![target_location_id]); - fact["properties"]["statement"]["minLength"] = serde_json::json!(1); - fact["properties"]["statement"]["maxLength"] = serde_json::json!(500); - fact["required"] = serde_json::json!([ - "id", - "statement", - "scope", - "evidence_receipt_ids", - "discoverable_at_location_ids" - ]); - fact["additionalProperties"] = serde_json::json!(false); - } - Self::AddPoliticalRelation { - relation_id, - allowed_subject_ids, - } => { - let relation = schema.pointer_mut("/$defs/AgencyRelation").ok_or_else(|| { - anyhow!("world elaboration schema has no relation definition") - })?; - relation["properties"]["schema"] = - exact_schema(crate::domain::AgencyRelation::SCHEMA); - relation["properties"]["id"] = exact_schema(relation_id); - let allowed = allowed_subject_ids.iter().cloned().collect::>(); - relation["properties"]["from_subject_id"] = serde_json::json!({ - "type":"string", - "enum":allowed, - }); - relation["properties"]["to_subject_id"] = serde_json::json!({ - "type":"string", - "enum":allowed_subject_ids.iter().cloned().collect::>(), - }); - relation["properties"]["kind"] = serde_json::json!({ - "type":"string", - "enum":["alliance", "rivalry", "trade", "communication", "command", "coercion"], - }); - relation["properties"]["active"] = exact_schema(&true); - relation["properties"]["evidence_receipt_ids"] = - exact_schema(&Vec::::new()); - relation["additionalProperties"] = serde_json::json!(false); - } - } - Ok(schema) - } - - fn operation_type(&self) -> &'static str { - match self { - Self::PatinaPlace { .. } => "add_place", - Self::PatinaOriginRoute { .. } | Self::PatinaReturnRoute { .. } => "add_route", - Self::PreserveCivicSystem { .. } => "set_civic_system", - Self::AddFact { .. } => "add_fact", - Self::AddPoliticalRelation { .. } => "add_local_relation", - } - } - - fn validate( - &self, - campaign: &crate::domain::Campaign, - target_location_id: &str, - proposal: &WorldElaborationProposal, - ) -> Result<()> { - if proposal.schema != "ghostlight.world_elaboration_proposal.v1" { - return Err(anyhow!("world elaboration proposal schema is unsupported")); - } - operation_claims(&proposal.operation)?; - use WorldElaborationOperation::*; - match (self, &proposal.operation) { - ( - Self::PatinaPlace { child_location_id }, - AddPlace { - id, - name, - container_id, - persistent_features, - }, - ) if id == child_location_id - && !name.trim().is_empty() - && container_id.as_deref() == Some(target_location_id) - && !persistent_features.is_empty() => {} - ( - Self::PatinaOriginRoute { - child_location_id, - route_id: expected_route_id, - }, - AddRoute { - origin_location_id, - route_id, - route, - }, - ) if origin_location_id == target_location_id - && route_id == expected_route_id - && route.destination_id == *child_location_id - && route.distance == "a short internal path" - && route.travel_minutes == 3 => {} - ( - Self::PatinaReturnRoute { - child_location_id, - route_id: expected_route_id, - }, - AddRoute { - origin_location_id, - route_id, - route, - }, - ) if origin_location_id == child_location_id - && route_id == expected_route_id - && route.destination_id == target_location_id - && route.distance == "a short internal path" - && route.travel_minutes == 3 => {} - (Self::PreserveCivicSystem { system }, SetCivicSystem { system: proposed }) - if proposed == system => {} - (Self::AddFact { fact_id }, AddFact { fact }) - if fact.id == *fact_id - && fact.scope == crate::domain::FactScope::BranchLocal - && fact.evidence_receipt_ids.is_empty() - && fact.discoverable_at_location_ids - == BTreeSet::from([target_location_id.to_owned()]) - && !fact.statement.trim().is_empty() - && fact.statement.chars().count() <= 500 - && campaign - .facts - .values() - .all(|existing| existing.statement != fact.statement) => {} - ( - Self::AddPoliticalRelation { - relation_id, - allowed_subject_ids, - }, - AddLocalRelation { relation }, - ) if relation.id == *relation_id - && relation.schema == crate::domain::AgencyRelation::SCHEMA - && allowed_subject_ids.contains(&relation.from_subject_id) - && allowed_subject_ids.contains(&relation.to_subject_id) - && relation.from_subject_id != relation.to_subject_id - && matches!( - relation.kind, - crate::domain::AgencyRelationKind::Alliance - | crate::domain::AgencyRelationKind::Rivalry - | crate::domain::AgencyRelationKind::Trade - | crate::domain::AgencyRelationKind::Communication - | crate::domain::AgencyRelationKind::Command - | crate::domain::AgencyRelationKind::Coercion - ) - && relation.active - && (1..=100).contains(&relation.strength) - && relation.evidence_receipt_ids.is_empty() => {} - _ => { - return Err(anyhow!( - "proposal does not satisfy the exact titled elaboration task assignment; correct it against this exact contract: {}", - self.instruction(target_location_id)? - )); - } - } - Ok(()) - } -} - -fn selected_operation_branch(schema: &mut serde_json::Value) -> Result<&mut serde_json::Value> { - schema - .pointer_mut("/$defs/WorldElaborationOperation/oneOf/0") - .ok_or_else(|| anyhow!("world elaboration schema lost its selected operation variant")) -} - -fn exact_schema(value: impl Serialize) -> serde_json::Value { - let value = serde_json::to_value(value).expect("serializable assignment value"); - let value_type = match &value { - serde_json::Value::Null => "null", - serde_json::Value::Bool(_) => "boolean", - serde_json::Value::Number(number) if number.is_i64() || number.is_u64() => "integer", - serde_json::Value::Number(_) => "number", - serde_json::Value::String(_) => "string", - serde_json::Value::Array(_) => "array", - serde_json::Value::Object(_) => "object", - }; - serde_json::json!({ - "type":value_type, - "const":value, - }) -} - -fn exact_keyed_string_map_schema(keys: impl IntoIterator) -> serde_json::Value { - let keys = keys.into_iter().collect::>(); - let properties = keys - .iter() - .cloned() - .map(|key| (key, serde_json::json!({"type":"string","minLength":1}))) - .collect::>(); - serde_json::json!({ - "type":"object", - "properties":properties, - "required":keys, - "additionalProperties":false, - }) -} - -fn constrain_exact_object(schema: &mut serde_json::Value, exact: &serde_json::Value) -> Result<()> { - let exact = exact - .as_object() - .ok_or_else(|| anyhow!("exact assignment value is not an object"))?; - let properties = schema - .get_mut("properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("generated assignment object schema has no properties"))?; - for (name, value) in exact { - if !properties.contains_key(name) { - return Err(anyhow!( - "generated assignment object schema has no {name} property" - )); - } - properties.insert(name.clone(), exact_schema(value)); - } - schema["required"] = serde_json::json!(exact.keys().collect::>()); - schema["additionalProperties"] = serde_json::json!(false); - Ok(()) -} - -#[derive(Clone, Debug, Serialize)] -#[serde(deny_unknown_fields)] -struct WorldElaborationAgentFinding { - diagnostic: String, -} - -struct WorldElaborationAgentTool<'a> { - campaign: &'a crate::domain::Campaign, - target_location_id: &'a str, - assignment: &'a WorldElaborationAssignment, - workbench: serde_json::Value, -} - -#[async_trait] -impl crate::agent::ModelAgentTool for WorldElaborationAgentTool<'_> { - type Action = WorldElaborationProposal; - type Output = WorldElaborationProposal; - type Finding = WorldElaborationAgentFinding; - - fn action_schema(&self) -> std::result::Result { - self.assignment - .action_schema(self.target_location_id) - .map_err(|error| error.to_string()) - } - - fn initial_context_snapshot(&self) -> Option { - Some(self.workbench.clone()) - } - - async fn invoke( - &mut self, - action: Self::Action, - _context: &crate::agent::ModelAgentToolContext, - ) -> crate::agent::ModelAgentToolOutcome { - match self - .assignment - .validate(self.campaign, self.target_location_id, &action) - { - Ok(()) => crate::agent::ModelAgentToolOutcome::Accepted { - output: action, - receipts: Vec::new(), - }, - Err(error) => crate::agent::ModelAgentToolOutcome::Rejected { - finding: WorldElaborationAgentFinding { - diagnostic: error.to_string(), - }, - receipts: Vec::new(), - }, - } - } -} - -#[async_trait] -impl ElaborationSubAgentPort for ModelWorldElaborationWorker { - async fn invoke( - &self, - invocation: ElaborationSubAgentInvocation, - ) -> std::result::Result< - ElaborationSubAgentOutput, - ElaborationSubAgentFailure, - > { - let expected_wave = - world_elaboration_wave_binding(&self.campaign, &self.target_location_id).map_err( - |error| ElaborationSubAgentFailure { - diagnostic: error.to_string(), - model_stage_receipts: Vec::new(), - }, - )?; - if invocation.wave != expected_wave { - return Err(ElaborationSubAgentFailure { - diagnostic: - "world elaboration worker invocation does not match its frozen campaign".into(), - model_stage_receipts: Vec::new(), - }); - } - let assignment = WorldElaborationAssignment::for_dispatch( - &self.campaign, - &self.target_location_id, - &invocation.dispatch, - ) - .map_err(|error| ElaborationSubAgentFailure { - diagnostic: error.to_string(), - model_stage_receipts: Vec::new(), - })?; - let snapshot_binding = - world_elaboration_invocation_binding(&invocation.wave, &invocation.dispatch).map_err( - |error| ElaborationSubAgentFailure { - diagnostic: error.to_string(), - model_stage_receipts: Vec::new(), - }, - )?; - // Keep identity and mandate as the stable cacheable prefix. Exact - // assignment, mutable world projection, and (later) compacted working - // memory belong to the bounded workbench snapshot. - let instructions = format!( - "You are {}, one titled elaborator in an iterative worldbuilding session. {} Your authority is one proposal at a time. Use the typed submit tool to negotiate with the deterministic validator; never claim canonical state, invent evidence receipts, or alter another assignment. Preserve admitted structure and make each contribution specific enough that later events can use it.", - invocation.dispatch.title.display_name(), - invocation.dispatch.title.mandate(), - ); - let assignment_instruction = - assignment - .instruction(&self.target_location_id) - .map_err(|error| ElaborationSubAgentFailure { - diagnostic: error.to_string(), - model_stage_receipts: Vec::new(), - })?; - let projection = self - .projection() - .map_err(|error| ElaborationSubAgentFailure { - diagnostic: error.to_string(), - model_stage_receipts: Vec::new(), - })?; - let model = match invocation.dispatch.title { - ElaboratorTitle::Charter | ElaboratorTitle::Tangle => crate::model::MODEL_BALANCED, - ElaboratorTitle::Numen => crate::model::MODEL_CAPABLE, - _ => crate::model::MODEL_FAST, - }; - let spec = crate::agent::ModelAgentSpec { - stage: elaborator_stage(invocation.dispatch.title), - model: model.into(), - snapshot_binding, - instructions, - source_receipt_ids: Vec::new(), - temperature: Some(0.4), - max_output_tokens: Some(1_800), - max_steps: 2, - }; - let mut tool = WorldElaborationAgentTool { - campaign: &self.campaign, - target_location_id: &self.target_location_id, - assignment: &assignment, - workbench: serde_json::json!({ - "schema":"ghostlight.elaborator_workbench.v1", - "assignment":assignment_instruction, - "compacted_session":self.session_checkpoints.get(&invocation.dispatch.title), - "frozen_public_world_projection":serde_json::from_str::(&projection) - .unwrap_or_else(|_| serde_json::Value::String(projection)), - }), - }; - match crate::agent::run_model_agent(self.model.as_ref(), &spec, &mut tool).await { - Ok(run) => Ok(ElaborationSubAgentOutput { - proposal: run.output, - model_stage_receipts: run.receipts, - }), - Err(error) => Err(ElaborationSubAgentFailure { - diagnostic: error.message, - model_stage_receipts: error.receipts, - }), - } - } -} - -/// One additive world operation proposed by one titled elaborator. These are -/// deliberately compiler inputs, not kernel commands or mutation permits. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(tag = "type", rename_all = "snake_case")] -pub enum WorldElaborationOperation { - AddPlace { - id: String, - name: String, - container_id: Option, - #[serde(default)] - persistent_features: Vec, - }, - AddRoute { - origin_location_id: String, - route_id: String, - route: crate::domain::Route, - }, - AddFact { - fact: crate::domain::WorldFact, - }, - AddPopulation { - population: crate::domain::GestaltPersonaState, - profile: crate::domain::AgencyProfile, - }, - AddInstitution { - institution: crate::domain::InstitutionState, - profile: crate::domain::AgencyProfile, - }, - AddLocalRelation { - relation: crate::domain::AgencyRelation, - }, - AddMigrationRelation { - relation: crate::domain::AgencyRelation, - }, - SetCivicSystem { - system: crate::domain::CivicSystemManifest, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -pub struct WorldElaborationProposal { - pub schema: String, - pub operation: WorldElaborationOperation, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -pub struct AdmittedWorldElaborationOperation { - pub dispatch: ElaborationDispatch, - pub operation: WorldElaborationOperation, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum WorldElaborationRejectionKind { - InvalidProposal, - WriteConflict, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -pub struct WorldElaborationRejection { - pub dispatch: ElaborationDispatch, - pub proposal: WorldElaborationProposal, - pub kind: WorldElaborationRejectionKind, - pub conflicting_dispatch_ordinal: Option, - pub diagnostic: String, -} - -/// Deterministic result of admitting one successful parallel elaboration wave. -/// The candidate remains non-canonical and carries an empty civic verifier -/// binding until an independent semantic verifier finalizes it. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -pub struct WorldElaborationAdmission { - schema: String, - wave: ElaborationWaveBinding, - campaign_id: Uuid, - expected_revision: u64, - target_location_id: String, - schedule: ElaborationScheduleReceipt, - accepted_operations: Vec, - rejections: Vec, - model_stage_receipts: Vec, - candidate: Option, - candidate_diagnostic: Option, - digest: String, -} - -/// A finalized elaboration value ready to lower through the owning world command path. -/// It binds the immutable admission result to an independently generated -/// semantic-verifier receipt without letting that verifier rewrite the draft. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -pub struct FinalizedWorldElaboration { - schema: String, - admission: WorldElaborationAdmission, - semantic_verifier_receipt: crate::model::ModelStageReceipt, - digest: String, -} - -pub fn world_elaboration_wave_binding( - campaign: &crate::domain::Campaign, - target_location_id: &str, -) -> Result { - if !campaign.locations.contains_key(target_location_id) { - return Err(anyhow!("world elaboration target location is unknown")); - } - Ok(ElaborationWaveBinding { - schema: "ghostlight.elaboration_wave_binding.v1".into(), - snapshot_binding: crate::legacy_transition::digest_serializable(&( - "ghostlight.world_elaboration_snapshot.v1", - campaign.id, - campaign.revision, - target_location_id, - ))?, - }) -} - -pub fn world_elaboration_invocation_binding( - wave: &ElaborationWaveBinding, - dispatch: &ElaborationDispatch, -) -> Result { - crate::legacy_transition::digest_serializable(&( - "ghostlight.world_elaboration_agent_snapshot.v1", - wave, - dispatch, - )) -} - -/// Deterministically validates, conflict-selects, and merges every proposal in -/// a successful wave. First writer in scheduler dispatch order owns a write -/// claim; later colliding proposals are retained as exact rejections. -pub fn admit_world_elaboration_wave( - campaign: &crate::domain::Campaign, - target_location_id: &str, - run: ElaborationWaveRun, -) -> Result { - let expected_wave = world_elaboration_wave_binding(campaign, target_location_id)?; - if run.wave != expected_wave { - return Err(anyhow!( - "world elaboration wave does not bind the current target snapshot" - )); - } - validate_successful_wave_run(&run)?; - validate_invocation_model_receipts(&run)?; - let mut invocations = run.invocations; - invocations.sort_by_key(|invocation| invocation.dispatch.ordinal); - if invocations - .iter() - .zip(run.schedule.dispatches.iter()) - .any(|(invocation, dispatch)| { - invocation.wave != run.wave || invocation.dispatch != *dispatch - }) - { - return Err(anyhow!( - "world elaboration invocation provenance does not match its schedule" - )); - } - - let mut claim_owners = BTreeMap::::new(); - let mut accepted_operations = Vec::new(); - let mut rejections = Vec::new(); - let mut model_stage_receipts = Vec::new(); - for invocation in invocations { - model_stage_receipts.extend(invocation.model_stage_receipts); - let proposal = invocation.proposal; - let claims = if proposal.schema == "ghostlight.world_elaboration_proposal.v1" { - operation_claims(&proposal.operation) - } else { - Err(anyhow!("world elaboration proposal schema is unsupported")) - }; - let claims = match claims { - Ok(claims) => claims, - Err(error) => { - rejections.push(WorldElaborationRejection { - dispatch: invocation.dispatch, - proposal, - kind: WorldElaborationRejectionKind::InvalidProposal, - conflicting_dispatch_ordinal: None, - diagnostic: bounded_diagnostic(error.to_string()), - }); - continue; - } - }; - if let Some(conflicting_dispatch_ordinal) = claims - .iter() - .filter_map(|claim| claim_owners.get(claim).copied()) - .min() - { - rejections.push(WorldElaborationRejection { - dispatch: invocation.dispatch, - proposal, - kind: WorldElaborationRejectionKind::WriteConflict, - conflicting_dispatch_ordinal: Some(conflicting_dispatch_ordinal), - diagnostic: format!( - "world elaboration write conflicts with dispatch {conflicting_dispatch_ordinal}" - ), - }); - continue; - } - for claim in claims { - claim_owners.insert(claim, invocation.dispatch.ordinal); - } - accepted_operations.push(AdmittedWorldElaborationOperation { - dispatch: invocation.dispatch, - operation: proposal.operation, - }); - } - - let (candidate, candidate_diagnostic) = - candidate_from_operations(campaign, target_location_id, &accepted_operations); - let mut admission = WorldElaborationAdmission { - schema: "ghostlight.world_elaboration_admission.v1".into(), - wave: run.wave, - campaign_id: campaign.id, - expected_revision: campaign.revision, - target_location_id: target_location_id.into(), - schedule: run.schedule, - accepted_operations, - rejections, - model_stage_receipts, - candidate, - candidate_diagnostic, - digest: String::new(), - }; - admission.digest = world_elaboration_admission_digest(&admission)?; - Ok(admission) -} - -fn validate_successful_wave_run(run: &ElaborationWaveRun) -> Result<()> { - let schedule = &run.schedule; - validate_elaboration_schedule(schedule)?; - if run.invocations.len() != schedule.dispatches.len() { - return Err(anyhow!( - "world elaboration schedule receipt is not internally coherent" - )); - } - Ok(()) -} - -fn validate_elaboration_schedule(schedule: &ElaborationScheduleReceipt) -> Result<()> { - let recomputed_dispatch_counts = schedule.dispatches.iter().fold( - BTreeMap::::new(), - |mut counts, dispatch| { - *counts.entry(dispatch.title).or_default() += 1; - counts - }, - ); - if schedule.schema != "ghostlight.elaboration_schedule_receipt.v1" - || schedule.final_state.schema != "ghostlight.elaboration_dispatch_state.v1" - || schedule.final_state.profile_digest.trim().is_empty() - || schedule.requested_invocations - != schedule.dispatches.len() as u32 + schedule.unused_invocations - || schedule.unused_invocations != schedule.unused_counts.values().copied().sum::() - || schedule.dispatch_counts != recomputed_dispatch_counts - || schedule - .dispatches - .iter() - .any(|dispatch| !schedule.eligible_titles.contains(&dispatch.title)) - { - return Err(anyhow!( - "world elaboration schedule receipt is not internally coherent" - )); - } - let initial_budget_slots = schedule - .final_state - .total_budget_slots - .checked_sub(u64::from(schedule.requested_invocations)) - .ok_or_else(|| anyhow!("world elaboration schedule budget regressed"))?; - let initial_dispatches = schedule - .final_state - .total_dispatches - .checked_sub(schedule.dispatches.len() as u64) - .ok_or_else(|| anyhow!("world elaboration dispatch count regressed"))?; - let mut seen_budget_ordinals = BTreeSet::new(); - let mut next_title_counts = BTreeMap::new(); - for (index, dispatch) in schedule.dispatches.iter().enumerate() { - let expected_ordinal = initial_dispatches + index as u64 + 1; - let final_title_count = schedule - .final_state - .dispatch_counts - .get(&dispatch.title) - .copied() - .unwrap_or_default(); - let wave_title_count = u64::from( - schedule - .dispatch_counts - .get(&dispatch.title) - .copied() - .unwrap_or_default(), - ); - let initial_title_count = final_title_count - .checked_sub(wave_title_count) - .ok_or_else(|| anyhow!("world elaboration title dispatch count regressed"))?; - let expected_title_count = next_title_counts - .entry(dispatch.title) - .and_modify(|count| *count += 1) - .or_insert(initial_title_count + 1); - if dispatch.schema != "ghostlight.elaboration_dispatch.v1" - || dispatch.ordinal != expected_ordinal - || dispatch.title_dispatch_count != *expected_title_count - || dispatch.title_weight == 0 - || dispatch.total_enabled_weight == 0 - || dispatch.budget_ordinal <= initial_budget_slots - || dispatch.budget_ordinal > schedule.final_state.total_budget_slots - || !seen_budget_ordinals.insert(dispatch.budget_ordinal) - { - return Err(anyhow!( - "world elaboration dispatch provenance is not derived from its final scheduler state" - )); - } - let expected_share = u32::from(dispatch.title_weight).saturating_mul(1_000_000) - / dispatch.total_enabled_weight; - if dispatch.requested_share_millionths != expected_share { - return Err(anyhow!( - "world elaboration dispatch share is not derived from its configured weight" - )); - } - } - if next_title_counts.into_iter().any(|(title, count)| { - schedule.final_state.dispatch_counts.get(&title).copied() != Some(count) - }) { - return Err(anyhow!( - "world elaboration title dispatch totals do not reach final scheduler state" - )); - } - Ok(()) -} - -fn validate_partial_wave_checkpoint( - wave: &ElaborationWaveBinding, - schedule: &ElaborationScheduleReceipt, - completed_invocations: &[ElaborationInvocation], - invocation_failures: &[ElaborationInvocationFailure], -) -> Result<()> { - wave.validate()?; - validate_elaboration_schedule(schedule)?; - if invocation_failures.is_empty() { - return Err(anyhow!( - "elaboration resume checkpoint contains no failed dispatch" - )); - } - let scheduled = schedule - .dispatches - .iter() - .map(|dispatch| (dispatch.ordinal, dispatch)) - .collect::>(); - let mut partition = BTreeSet::new(); - for invocation in completed_invocations { - if &invocation.wave != wave - || scheduled.get(&invocation.dispatch.ordinal).copied() != Some(&invocation.dispatch) - || !partition.insert(invocation.dispatch.ordinal) - { - return Err(anyhow!( - "elaboration resume checkpoint completed work does not match its exact schedule" - )); - } - } - for failure in invocation_failures { - let Some(dispatch) = failure.dispatch.as_ref() else { - return Err(anyhow!( - "elaboration resume checkpoint has an unbound failed dispatch" - )); - }; - if scheduled.get(&dispatch.ordinal).copied() != Some(dispatch) - || !partition.insert(dispatch.ordinal) - { - return Err(anyhow!( - "elaboration resume checkpoint failed work does not match its exact schedule" - )); - } - } - if partition.len() != scheduled.len() { - return Err(anyhow!( - "elaboration resume checkpoint does not partition its exact schedule" - )); - } - Ok(()) -} - -fn validate_invocation_model_receipts(run: &ElaborationWaveRun) -> Result<()> { - let mut receipt_ids = BTreeSet::new(); - for invocation in &run.invocations { - if invocation.model_stage_receipts.is_empty() { - return Err(anyhow!( - "world elaboration invocation lacks model receipt custody" - )); - } - let expected_binding = - world_elaboration_invocation_binding(&invocation.wave, &invocation.dispatch)?; - let expected_stage = elaborator_stage(invocation.dispatch.title); - for receipt in &invocation.model_stage_receipts { - let mut rebound = receipt.clone(); - rebound.rebind_snapshot(receipt.snapshot_binding.clone()); - if receipt.schema != "ghostlight.persona_stage_receipt.v1" - || receipt.stage != expected_stage - || receipt.snapshot_binding != expected_binding - || !matches!( - receipt.validation_result.as_str(), - "valid" | "semantic_invalid" - ) - || rebound.storage_key() != receipt.storage_key() - || !receipt_ids.insert(receipt.storage_key().to_owned()) - { - return Err(anyhow!( - "world elaboration model receipt provenance is invalid or duplicated" - )); - } - } - if invocation - .model_stage_receipts - .last() - .is_none_or(|receipt| { - receipt.validation_result != "valid" || receipt.local_validation_error.is_some() - }) - { - return Err(anyhow!( - "world elaboration invocation lacks a terminal accepted model receipt" - )); - } - } - Ok(()) -} - -fn elaborator_stage(title: ElaboratorTitle) -> String { - format!( - "world_elaboration_{}", - title.display_name().to_ascii_lowercase() - ) -} - -fn validate_semantic_verifier_ancestry( - admission: &WorldElaborationAdmission, - semantic_verifier_receipt: &crate::model::ModelStageReceipt, -) -> Result<()> { - let expected = admission - .model_stage_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - let actual = semantic_verifier_receipt - .source_receipt_ids - .iter() - .cloned() - .collect::>(); - if actual.len() != semantic_verifier_receipt.source_receipt_ids.len() || actual != expected { - return Err(anyhow!( - "world elaboration semantic verifier ancestry does not exactly cover admitted model receipts" - )); - } - Ok(()) -} - -pub fn finalize_world_elaboration( - campaign: &crate::domain::Campaign, - admission: WorldElaborationAdmission, - semantic_verifier_receipt: crate::model::ModelStageReceipt, -) -> Result { - validate_semantic_verifier_ancestry(&admission, &semantic_verifier_receipt)?; - let mut elaboration = admission.valid_candidate(campaign)?; - elaboration - .expansion - .civic_system - .as_mut() - .expect("valid locality elaboration has a civic system") - .semantic_verification_receipt_id = semantic_verifier_receipt.storage_key().into(); - crate::compiler::validate_civic_admission_receipts( - campaign, - &elaboration.expansion, - std::slice::from_ref(&semantic_verifier_receipt), - )?; - let mut finalized = FinalizedWorldElaboration { - schema: "ghostlight.finalized_world_elaboration.v1".into(), - admission, - semantic_verifier_receipt, - digest: String::new(), - }; - finalized.digest = finalized_world_elaboration_digest(&finalized)?; - Ok(finalized) -} - -impl WorldElaborationAdmission { - pub fn wave(&self) -> &ElaborationWaveBinding { - &self.wave - } - - pub fn schedule(&self) -> &ElaborationScheduleReceipt { - &self.schedule - } - - pub fn accepted_operations(&self) -> &[AdmittedWorldElaborationOperation] { - &self.accepted_operations - } - - pub fn rejections(&self) -> &[WorldElaborationRejection] { - &self.rejections - } - - pub fn model_stage_receipts(&self) -> &[crate::model::ModelStageReceipt] { - &self.model_stage_receipts - } - - pub fn candidate(&self) -> Option<&crate::domain::LocalityElaboration> { - self.candidate.as_ref() - } - - pub fn candidate_diagnostic(&self) -> Option<&str> { - self.candidate_diagnostic.as_deref() - } - - pub fn digest(&self) -> &str { - &self.digest - } - - pub fn expected_revision(&self) -> u64 { - self.expected_revision - } - - pub fn target_location_id(&self) -> &str { - &self.target_location_id - } - - /// Revalidates the complete admission against the current campaign and - /// derives its candidate from the admitted operations. Recovery code uses - /// this instead of trusting a serialized candidate projection. - pub fn valid_candidate( - &self, - campaign: &crate::domain::Campaign, - ) -> Result { - if self.schema != "ghostlight.world_elaboration_admission.v1" - || self.campaign_id != campaign.id - || self.expected_revision != campaign.revision - || self.wave != world_elaboration_wave_binding(campaign, &self.target_location_id)? - || self.digest != world_elaboration_admission_digest(self)? - { - return Err(anyhow!( - "world elaboration admission is stale, malformed, or tampered" - )); - } - validate_admission_dispatch_partition(self)?; - let (candidate, candidate_diagnostic) = candidate_from_operations( - campaign, - &self.target_location_id, - &self.accepted_operations, - ); - if candidate != self.candidate || candidate_diagnostic != self.candidate_diagnostic { - return Err(anyhow!( - "world elaboration admission candidate is not derived from its accepted operations" - )); - } - if let Some(diagnostic) = &self.candidate_diagnostic { - return Err(anyhow!( - "world elaboration candidate requires reconciliation: {diagnostic}" - )); - } - let candidate = self - .candidate - .clone() - .ok_or_else(|| anyhow!("world elaboration admission has no candidate"))?; - let system = candidate - .expansion - .civic_system - .as_ref() - .ok_or_else(|| anyhow!("world elaboration candidate has no civic system"))?; - if !system.semantic_verification_receipt_id.is_empty() { - return Err(anyhow!( - "titled elaborators cannot supply the civic semantic-verifier receipt" - )); - } - Ok(candidate) - } -} - -impl FinalizedWorldElaboration { - pub fn admission(&self) -> &WorldElaborationAdmission { - &self.admission - } - - pub fn digest(&self) -> &str { - &self.digest - } - - pub fn semantic_verifier_receipt(&self) -> &crate::model::ModelStageReceipt { - &self.semantic_verifier_receipt - } -} - -fn operation_claims(operation: &WorldElaborationOperation) -> Result> { - use WorldElaborationOperation::*; - let nonempty = |value: &str, field: &str| { - if value.trim().is_empty() { - Err(anyhow!("world elaboration {field} cannot be empty")) - } else { - Ok(()) - } - }; - match operation { - AddPlace { - id, - name, - persistent_features, - .. - } => { - nonempty(id, "place id")?; - nonempty(name, "place name")?; - if persistent_features - .iter() - .any(|value| value.trim().is_empty()) - || persistent_features.iter().collect::>().len() - != persistent_features.len() - { - return Err(anyhow!("world elaboration place features are malformed")); - } - Ok(vec![format!("subject:{id}")]) - } - AddRoute { - origin_location_id, - route_id, - route, - } => { - nonempty(origin_location_id, "route origin")?; - nonempty(route_id, "route id")?; - nonempty(&route.destination_id, "route destination")?; - nonempty(&route.distance, "route distance")?; - if route.travel_minutes == 0 || route.destination_id == *origin_location_id { - return Err(anyhow!("world elaboration route is malformed")); - } - Ok(vec![format!("route:{origin_location_id}:{route_id}")]) - } - AddFact { fact } => { - nonempty(&fact.id, "fact id")?; - nonempty(&fact.statement, "fact statement")?; - if fact.scope == crate::domain::FactScope::CanonBaseline { - return Err(anyhow!( - "titled elaborators cannot assert canon-baseline facts" - )); - } - if !fact.evidence_receipt_ids.is_empty() { - return Err(anyhow!( - "titled elaborators cannot attach source-evidence receipts" - )); - } - Ok(vec![format!("fact:{}", fact.id)]) - } - AddPopulation { - population, - profile, - } => { - nonempty(&population.id, "population id")?; - if profile.subject_id != population.id - || profile.subject_kind != crate::domain::AgencySubjectKind::Gestalt - || !profile.evidence_receipt_ids.is_empty() - { - return Err(anyhow!( - "world elaboration population profile does not bind its population" - )); - } - Ok(vec![ - format!("subject:{}", population.id), - format!("agency_profile:{}", population.id), - ]) - } - AddInstitution { - institution, - profile, - } => { - nonempty(&institution.id, "institution id")?; - if profile.subject_id != institution.id - || profile.subject_kind != crate::domain::AgencySubjectKind::Institution - || !profile.evidence_receipt_ids.is_empty() - { - return Err(anyhow!( - "world elaboration institution profile does not bind its institution" - )); - } - Ok(vec![ - format!("subject:{}", institution.id), - format!("agency_profile:{}", institution.id), - ]) - } - AddLocalRelation { relation } | AddMigrationRelation { relation } => { - nonempty(&relation.id, "relation id")?; - if !relation.evidence_receipt_ids.is_empty() { - return Err(anyhow!( - "titled elaborators cannot attach source-evidence receipts" - )); - } - Ok(vec![format!("relation:{}", relation.id)]) - } - SetCivicSystem { system } => { - nonempty(&system.jurisdiction_location_id, "civic jurisdiction")?; - if !system.semantic_verification_receipt_id.is_empty() { - return Err(anyhow!( - "titled elaborators cannot supply the civic semantic-verifier receipt" - )); - } - Ok(vec!["civic_system".into()]) - } - } -} - -fn candidate_from_operations( - campaign: &crate::domain::Campaign, - target_location_id: &str, - accepted: &[AdmittedWorldElaborationOperation], -) -> (Option, Option) { - match build_candidate(target_location_id, accepted).and_then(|candidate| { - crate::compiler::validate_locality_elaboration(campaign, &candidate)?; - Ok(candidate) - }) { - Ok(candidate) => (Some(candidate), None), - Err(error) => { - let candidate = build_candidate(target_location_id, accepted).ok(); - (candidate, Some(bounded_diagnostic(error.to_string()))) - } - } -} - -fn build_candidate( - target_location_id: &str, - accepted: &[AdmittedWorldElaborationOperation], -) -> Result { - use WorldElaborationOperation::*; - let mut expansion = crate::domain::RegionExpansion { - origin_location_id: target_location_id.into(), - origin_routes: BTreeMap::new(), - locations: Vec::new(), - facts: Vec::new(), - populations: Vec::new(), - population_profiles: Vec::new(), - migration_relations: Vec::new(), - institutions: Vec::new(), - institution_profiles: Vec::new(), - local_relations: Vec::new(), - civic_system: None, - }; - for accepted in accepted { - match &accepted.operation { - AddPlace { - id, - name, - container_id, - persistent_features, - } => expansion.locations.push(crate::domain::Location { - id: id.clone(), - name: name.clone(), - container_id: container_id.clone(), - routes: BTreeMap::new(), - persistent_features: persistent_features.clone(), - }), - AddFact { fact } => expansion.facts.push(fact.clone()), - AddPopulation { - population, - profile, - } => { - expansion.populations.push(population.clone()); - expansion.population_profiles.push(profile.clone()); - } - AddInstitution { - institution, - profile, - } => { - expansion.institutions.push(institution.clone()); - expansion.institution_profiles.push(profile.clone()); - } - AddLocalRelation { relation } => expansion.local_relations.push(relation.clone()), - AddMigrationRelation { relation } => { - expansion.migration_relations.push(relation.clone()) - } - SetCivicSystem { system } => expansion.civic_system = Some(system.clone()), - AddRoute { .. } => {} - } - } - for accepted in accepted { - let AddRoute { - origin_location_id, - route_id, - route, - } = &accepted.operation - else { - continue; - }; - if origin_location_id == target_location_id { - expansion - .origin_routes - .insert(route_id.clone(), route.clone()); - } else { - let location = expansion - .locations - .iter_mut() - .find(|location| location.id == *origin_location_id) - .ok_or_else(|| { - anyhow!( - "world elaboration route origin {} was not proposed", - origin_location_id - ) - })?; - location.routes.insert(route_id.clone(), route.clone()); - } - } - Ok(crate::domain::LocalityElaboration { - target_location_id: target_location_id.into(), - expansion, - }) -} - -fn validate_admission_dispatch_partition(admission: &WorldElaborationAdmission) -> Result<()> { - let scheduled = admission - .schedule - .dispatches - .iter() - .map(|dispatch| (dispatch.ordinal, dispatch)) - .collect::>(); - let admitted = admission - .accepted_operations - .iter() - .map(|accepted| (accepted.dispatch.ordinal, &accepted.dispatch)) - .chain( - admission - .rejections - .iter() - .map(|rejection| (rejection.dispatch.ordinal, &rejection.dispatch)), - ) - .collect::>(); - if scheduled.len() != admission.schedule.dispatches.len() - || admitted.len() != admission.accepted_operations.len() + admission.rejections.len() - || scheduled != admitted - { - return Err(anyhow!( - "world elaboration admission does not partition its exact schedule" - )); - } - Ok(()) -} - -fn world_elaboration_admission_digest(admission: &WorldElaborationAdmission) -> Result { - crate::legacy_transition::digest_serializable(&( - "ghostlight.world_elaboration_admission.v1", - &admission.wave, - admission.campaign_id, - admission.expected_revision, - &admission.target_location_id, - &admission.schedule, - &admission.accepted_operations, - &admission.rejections, - &admission.model_stage_receipts, - &admission.candidate, - &admission.candidate_diagnostic, - )) -} - -fn finalized_world_elaboration_digest(finalized: &FinalizedWorldElaboration) -> Result { - crate::legacy_transition::digest_serializable(&( - "ghostlight.finalized_world_elaboration.v1", - &finalized.admission.digest, - &finalized.semantic_verifier_receipt, - )) -} - -fn bounded_diagnostic(diagnostic: String) -> String { - diagnostic.chars().take(2_000).collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ten_percent_cover_derives_twenty_four_hundred_actionable_subjects() { - let demand = derive_world_elaboration_demand( - 240, - 80, - &WorldScaleIntent::ten_percent(), - BTreeMap::from([ - ("forest".into(), 3), - ("grain".into(), 1), - ("rail".into(), 2), - ]), - ) - .unwrap(); - assert_eq!(demand.target_actionable_subjects, 2_400); - assert_eq!(demand.actionable_subject_deficit, 2_320); - assert_eq!(demand.round_mutation_budget, 232); - assert_eq!(demand.realm_subject_targets.values().sum::(), 2_400); - assert_eq!(demand.realm_subject_targets["forest"], 1_200); - assert_eq!(demand.realm_subject_targets["grain"], 400); - assert_eq!(demand.realm_subject_targets["rail"], 800); - } - - #[test] - fn twenty_percent_cover_derives_twelve_hundred_qualified_subjects() { - let demand = derive_world_elaboration_demand( - 240, - 80, - &WorldScaleIntent::twenty_percent(), - BTreeMap::from([("delvehold".into(), 1)]), - ) - .unwrap(); - assert_eq!(demand.target_actionable_subjects, 1_200); - assert_eq!(demand.actionable_subject_deficit, 1_120); - assert_eq!(demand.round_mutation_budget, 224); - } - - #[test] - fn elaboration_demand_never_reopens_a_satisfied_subject_target() { - let demand = derive_world_elaboration_demand( - 8, - 100, - &WorldScaleIntent::ten_percent(), - BTreeMap::from([("locality".into(), 1)]), - ) - .unwrap(); - assert_eq!(demand.target_actionable_subjects, 80); - assert_eq!(demand.actionable_subject_deficit, 0); - assert_eq!(demand.round_mutation_budget, 0); - } - - #[test] - fn elaboration_demand_counts_only_canonical_simulation_leaves() { - let mut campaign = campaign_with_civic_room(); - crate::resolution::ensure_agency_profiles(&mut campaign); - let mut eligible = campaign.agency_profiles[&campaign.player_actor_id].clone(); - eligible.id = "eligible-profile".into(); - eligible.subject_id = "eligible-subject".into(); - eligible.subject_kind = crate::domain::AgencySubjectKind::Gestalt; - eligible.simulation_eligible = true; - let eligible_id = eligible.subject_id.clone(); - campaign.gestalts.insert( - eligible_id.clone(), - crate::domain::GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: eligible_id.clone(), - name: "Eligible Population".into(), - version: 1, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: Vec::new(), - pressures: Vec::new(), - }, - ); - campaign - .agency_profiles - .insert(eligible_id.clone(), eligible); - campaign.gestalt_lineages.insert( - "source-parent".into(), - crate::domain::GestaltLineage { - schema: "ghostlight.gestalt_lineage.v1".into(), - parent_gestalt_id: "source-parent".into(), - child_gestalt_ids: vec![eligible_id.clone()], - partition_axis: crate::domain::AgencyAxis::Authority, - partition_values: BTreeMap::from([(eligible_id.clone(), "other/unknown".into())]), - residual_child_id: eligible_id.clone(), - source_revision: 1, - }, - ); - let mut retired = campaign.agency_profiles[&eligible_id].clone(); - retired.id = "retired-profile".into(); - retired.subject_id = "retired-subject".into(); - retired.active_leaf = false; - campaign - .agency_profiles - .insert(retired.subject_id.clone(), retired); - - let expected = campaign - .agency_profiles - .values() - .filter(|profile| { - profile.active_leaf - && profile.simulation_eligible - && profile.subject_id != eligible_id - }) - .count() as u32; - assert_eq!(canonical_actionable_subject_count(&campaign), expected); - assert!(campaign.agency_profiles[&eligible_id].simulation_eligible); - assert!(!campaign.agency_profiles[&campaign.player_actor_id].simulation_eligible); - } - - #[test] - fn ordinary_fission_children_cannot_pay_the_qualified_complexity_bill() { - let mut campaign = campaign_with_civic_room(); - crate::resolution::ensure_agency_profiles(&mut campaign); - let parent_id = "source-population".to_owned(); - let parent = crate::domain::GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: parent_id.clone(), - name: "Source Population".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: Vec::new(), - pressures: Vec::new(), - }; - campaign.gestalts.insert(parent_id.clone(), parent.clone()); - let mut parent_profile = campaign.agency_profiles[&campaign.player_actor_id].clone(); - parent_profile.id = format!("profile:{parent_id}"); - parent_profile.subject_id = parent_id.clone(); - parent_profile.subject_kind = crate::domain::AgencySubjectKind::Gestalt; - parent_profile.active_leaf = true; - parent_profile.simulation_eligible = true; - campaign - .agency_profiles - .insert(parent_id.clone(), parent_profile.clone()); - let baseline = canonical_actionable_subject_count(&campaign); - - let mut ordinary = parent.clone(); - ordinary.id = "ordinary-child".into(); - ordinary.name = "Ordinary Child".into(); - let mut qualified = parent.clone(); - qualified.id = "qualified-child".into(); - qualified.name = "Qualified Child".into(); - qualified - .shared_capabilities - .insert("operate the west sluice".into()); - qualified - .goals - .push("secure an independent flood rota".into()); - let mut residual = parent.clone(); - residual.id = "residual-child".into(); - residual.name = "Residual Child".into(); - for child in [&ordinary, &qualified, &residual] { - campaign.gestalts.insert(child.id.clone(), child.clone()); - let mut profile = parent_profile.clone(); - profile.id = format!("profile:{}", child.id); - profile.subject_id = child.id.clone(); - profile.parent_subject_id = Some(parent_id.clone()); - campaign.agency_profiles.insert(child.id.clone(), profile); - } - campaign.gestalt_lineages.insert( - parent_id.clone(), - crate::domain::GestaltLineage { - schema: "ghostlight.gestalt_lineage.v1".into(), - parent_gestalt_id: parent_id, - child_gestalt_ids: vec![ - ordinary.id.clone(), - qualified.id.clone(), - residual.id.clone(), - ], - partition_axis: crate::domain::AgencyAxis::Authority, - partition_values: BTreeMap::from([ - (ordinary.id.clone(), "ordinary".into()), - (qualified.id.clone(), "qualified".into()), - (residual.id.clone(), "other/unknown".into()), - ]), - residual_child_id: residual.id.clone(), - source_revision: campaign.revision, - }, - ); - - let ids = canonical_actionable_subject_ids(&campaign); - assert!(!ids.contains(&ordinary.id)); - assert!(ids.contains(&qualified.id)); - assert!(!ids.contains(&residual.id)); - assert_eq!(canonical_actionable_subject_count(&campaign), baseline + 1); - } - - #[test] - fn elaborator_session_compaction_binds_narrative_memory_to_exact_commits() { - let campaign = campaign_with_civic_room(); - let checkpoint = ElaboratorSessionCheckpoint::bind_compaction( - "charter:room", - ElaboratorTitle::Charter, - 2, - campaign.id, - campaign.revision, - "room", - ElaboratorSessionCompactionDraft { - schema: "ghostlight.elaborator_session_compaction_draft.v1".into(), - frontier_summary: - "The threshold witness office lacks an acknowledged succession rule.".into(), - unresolved_leads: vec![ - "Split the resident body by who can challenge a witness count.".into(), - ], - }, - vec!["world-commit:12".into()], - vec!["A proposed office duplicated an admitted institution.".into()], - Some("sha256:prior".into()), - ) - .unwrap(); - checkpoint - .validate_for(&campaign, "room", ElaboratorTitle::Charter) - .unwrap(); - - let mut tampered = checkpoint.clone(); - tampered.frontier_summary = "Invent an unrelated monarchy.".into(); - assert!( - tampered - .validate_for(&campaign, "room", ElaboratorTitle::Charter) - .is_err() - ); - assert!( - checkpoint - .validate_for(&campaign, "room", ElaboratorTitle::Patina) - .is_err() - ); - } - - #[tokio::test] - async fn session_compaction_schema_and_tool_name_every_invalid_lead() { - let mut tool = ElaboratorSessionCompactionTool { - workbench: serde_json::json!({"schema":"test.compaction_workbench.v1"}), - }; - let schema = crate::agent::ModelAgentTool::action_schema(&tool).unwrap(); - assert_eq!( - schema["properties"]["unresolved_leads"]["items"]["minLength"], - 1 - ); - assert_eq!( - schema["properties"]["unresolved_leads"]["items"]["maxLength"], - 600 - ); - let rejected = crate::agent::ModelAgentTool::invoke( - &mut tool, - ElaboratorSessionCompactionDraft { - schema: "ghostlight.elaborator_session_compaction_draft.v1".into(), - frontier_summary: "A bounded frontier remains live.".into(), - unresolved_leads: vec![String::new(), "x".repeat(601)], - }, - &crate::agent::ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }, - ) - .await; - let crate::agent::ModelAgentToolOutcome::Rejected { finding, .. } = rejected else { - panic!("invalid compaction was admitted") - }; - assert!(finding.diagnostic.contains("unresolved lead 0")); - assert!(finding.diagnostic.contains("unresolved lead 1")); - } - - fn campaign_with_civic_room() -> crate::domain::Campaign { - let mut campaign = crate::kernel::tests::campaign(); - campaign.civic_systems.insert( - "room".into(), - crate::domain::CivicSystemManifest { - schema: "ghostlight.civic_system_manifest.v1".into(), - version: 0, - jurisdiction_location_id: "room".into(), - governing_institution_ids: BTreeSet::new(), - resident_population_ids: BTreeSet::new(), - public_authority_fact_ids: BTreeSet::new(), - public_selection_fact_ids: BTreeSet::new(), - public_resource_fact_ids: BTreeSet::new(), - public_redress_fact_ids: BTreeSet::new(), - political_relation_ids: BTreeSet::new(), - semantic_verification_receipt_id: String::new(), - }, - ); - campaign - } - - fn campaign_with_fission_parent() -> crate::domain::Campaign { - let mut campaign = campaign_with_civic_room(); - campaign.gestalts.insert( - "river-households".into(), - crate::domain::GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "river-households".into(), - name: "River Households".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::from(["river tending".into()]), - shared_knowledge: BTreeSet::from(["seasonal ford marks".into()]), - resources: BTreeSet::from(["ferry charter".into()]), - goals: vec!["keep the river habitable".into()], - pressures: vec!["the banks are narrowing".into()], - }, - ); - crate::resolution::ensure_agency_profiles(&mut campaign); - campaign - .agency_profiles - .get_mut("river-households") - .unwrap() - .location_ids = BTreeSet::from(["room".into()]); - campaign - } - - fn valid_river_fission( - campaign: &crate::domain::Campaign, - ) -> crate::domain::GestaltFissionPreview { - let parent = &campaign.gestalts["river-households"]; - let child = |id: &str, name: &str| crate::domain::GestaltPersonaState { - schema: parent.schema.clone(), - id: id.into(), - name: name.into(), - version: 0, - home_location_id: parent.home_location_id.clone(), - shared_capabilities: parent.shared_capabilities.clone(), - shared_knowledge: parent.shared_knowledge.clone(), - resources: BTreeSet::new(), - goals: parent.goals.clone(), - pressures: parent.pressures.clone(), - }; - let mut licensed = child("licensed-river-households", "Licensed River Households"); - licensed.resources.insert("ferry charter".into()); - licensed - .shared_capabilities - .insert("withhold licensed ferry service".into()); - licensed - .goals - .push("keep licensed crossings under household control".into()); - licensed - .pressures - .push("the charter renewal is being challenged".into()); - let mut unlicensed = child("unlicensed-river-households", "Unlicensed River Households"); - unlicensed - .shared_knowledge - .insert("unmarked low-water crossings".into()); - unlicensed - .goals - .push("open one crossing beyond charter custody".into()); - unlicensed - .pressures - .push("licensed patrols impound unmarked ferries".into()); - crate::domain::GestaltFissionPreview { - schema: "ghostlight.gestalt_fission_preview.v1".into(), - campaign_id: campaign.id, - expected_world_revision: campaign.revision, - parent_gestalt_id: parent.id.clone(), - partition_axis: crate::domain::AgencyAxis::Authority, - children: vec![ - licensed, - unlicensed, - child("unrecorded-river-households", "Unrecorded River Households"), - ], - child_partition_values: BTreeMap::from([ - ( - "licensed-river-households".into(), - "licensed tenders".into(), - ), - ( - "unlicensed-river-households".into(), - "unlicensed tenders".into(), - ), - ("unrecorded-river-households".into(), "other/unknown".into()), - ]), - residual_child_id: "unrecorded-river-households".into(), - member_child_assignments: BTreeMap::new(), - resource_child_assignments: BTreeMap::from([( - "ferry charter".into(), - "licensed-river-households".into(), - )]), - evidence_receipt_ids: Vec::new(), - gaps: Vec::new(), - canon_candidates: Vec::new(), - requires_approval: true, - } - } - - fn river_fission_qualification() -> WorldComplexityFissionQualification { - WorldComplexityFissionQualification { - schema: "ghostlight.world_complexity_fission_qualification.v1".into(), - title: ElaboratorTitle::Charter, - jurisdiction_location_id: "room".into(), - target_actionable_gain: 1, - semantic: WorldComplexitySemanticQualification::default(), - } - } - - #[tokio::test] - async fn complexity_tool_admits_only_the_assigned_meaningful_fission() { - let campaign = campaign_with_fission_parent(); - let preview = valid_river_fission(&campaign); - let mut tool = WorldComplexityTool { - campaign: &campaign, - parent_gestalt_id: "river-households", - title: ElaboratorTitle::Charter, - operation: WorldComplexityOperation::Fission, - partition_axis: crate::domain::AgencyAxis::Authority, - jurisdiction_location_id: "room", - target_actionable_gain: 1, - workbench: serde_json::json!({"schema":"test.workbench.v1"}), - }; - let context = crate::agent::ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }; - let schema = crate::agent::ModelAgentTool::action_schema(&tool).unwrap(); - assert_eq!(schema["type"], "object"); - assert_eq!( - schema["properties"]["schema"]["const"], - "ghostlight.world_complexity_action.v1" - ); - assert_eq!( - schema["$defs"]["WorldComplexityMutationDraft"]["oneOf"] - .as_array() - .unwrap() - .len(), - 1 - ); - assert!(schema["$defs"].get("GestaltFissionPreview").is_none()); - assert_eq!( - schema["$defs"]["WorldComplexityMutationDraft"]["oneOf"][0]["properties"]["resource_child_assignments"] - ["required"], - serde_json::json!(["ferry charter"]) - ); - assert_eq!( - schema["$defs"]["WorldComplexityMutationDraft"]["oneOf"][0]["properties"]["member_child_assignments"] - ["required"], - serde_json::json!([]) - ); - let draft = WorldComplexityMutationDraft::Fission { - children: preview - .children - .iter() - .map(|child| WorldComplexityChildDraft { - id: child.id.clone(), - name: child.name.clone(), - partition_value: preview.child_partition_values[&child.id].clone(), - home_location_id: child.home_location_id.clone(), - capability_additions: child - .shared_capabilities - .difference(&campaign.gestalts["river-households"].shared_capabilities) - .cloned() - .collect(), - knowledge_additions: child - .shared_knowledge - .difference(&campaign.gestalts["river-households"].shared_knowledge) - .cloned() - .collect(), - goals_add: child - .goals - .iter() - .filter(|goal| !campaign.gestalts["river-households"].goals.contains(goal)) - .cloned() - .collect(), - pressures_add: child - .pressures - .iter() - .filter(|pressure| { - !campaign.gestalts["river-households"] - .pressures - .contains(pressure) - }) - .cloned() - .collect(), - }) - .collect(), - residual_child_id: preview.residual_child_id.clone(), - member_child_assignments: preview.member_child_assignments.clone(), - resource_child_assignments: preview.resource_child_assignments.clone(), - }; - - let admitted = crate::agent::ModelAgentTool::invoke( - &mut tool, - WorldComplexityAction { - schema: "ghostlight.world_complexity_action.v1".into(), - mutation: draft, - }, - &context, - ) - .await; - let crate::agent::ModelAgentToolOutcome::Accepted { - output: - WorldComplexityProposal::Fission { - preview: admitted, .. - }, - .. - } = admitted - else { - panic!("compact fission draft was not admitted") - }; - assert_eq!(admitted.children.len(), 3); - assert!( - admitted - .children - .iter() - .filter(|child| child.id != admitted.residual_child_id) - .all(|child| { - child.goals.len() > campaign.gestalts["river-households"].goals.len() - && child.pressures.len() - > campaign.gestalts["river-households"].pressures.len() - }) - ); - - let invalid = WorldComplexityMutationDraft::Fission { - children: preview - .children - .iter() - .map(|child| WorldComplexityChildDraft { - id: child.id.clone(), - name: child.name.clone(), - partition_value: "same partition".into(), - home_location_id: child.home_location_id.clone(), - capability_additions: BTreeSet::new(), - knowledge_additions: BTreeSet::new(), - goals_add: Vec::new(), - pressures_add: Vec::new(), - }) - .collect(), - residual_child_id: preview.residual_child_id, - member_child_assignments: preview.member_child_assignments, - resource_child_assignments: preview.resource_child_assignments, - }; - let rejected = crate::agent::ModelAgentTool::invoke( - &mut tool, - WorldComplexityAction { - schema: "ghostlight.world_complexity_action.v1".into(), - mutation: invalid, - }, - &context, - ) - .await; - assert!(matches!( - rejected, - crate::agent::ModelAgentToolOutcome::Rejected { .. } - )); - } - - #[tokio::test] - async fn complexity_tool_promotes_one_grounded_person_without_a_roster() { - let campaign = campaign_with_fission_parent(); - let individuation = crate::domain::GestaltIndividuation { - gestalt_id: "river-households".into(), - expected_gestalt_version: campaign.gestalts["river-households"].version, - location_id: "room".into(), - member: crate::domain::GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "orin-weirkeeper".into(), - gestalt_id: "river-households".into(), - version: 0, - name: "Orin Weirkeeper".into(), - capability_additions: BTreeSet::from(["read narrowing banks".into()]), - capability_removals: BTreeSet::new(), - knowledge_additions: BTreeSet::from(["which ford marks were moved".into()]), - knowledge_removals: BTreeSet::new(), - equipment: BTreeSet::from(["notched sounding pole".into()]), - conditions: BTreeSet::new(), - obligations: BTreeSet::from(["keep the river habitable".into()]), - relationships: BTreeMap::new(), - goals: vec!["force a public reckoning over the narrowing banks".into()], - memories: vec!["found three seasonal ford marks reset upstream".into()], - last_location_id: Some("room".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }, - }; - let mut punctuation_only = individuation.clone(); - punctuation_only.member.name = "---".into(); - assert!( - crate::resolution::validate_gestalt_individuation(&campaign, &punctuation_only) - .unwrap_err() - .to_string() - .contains("no public identity characters") - ); - let mut tool = WorldComplexityTool { - campaign: &campaign, - parent_gestalt_id: "river-households", - title: ElaboratorTitle::Veil, - operation: WorldComplexityOperation::Individuate, - partition_axis: crate::domain::AgencyAxis::Information, - jurisdiction_location_id: "room", - target_actionable_gain: 1, - workbench: serde_json::json!({"schema":"test.workbench.v1"}), - }; - let context = crate::agent::ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }; - let schema = crate::agent::ModelAgentTool::action_schema(&tool).unwrap(); - assert_eq!( - schema["$defs"]["WorldComplexityMutationDraft"]["oneOf"] - .as_array() - .unwrap() - .len(), - 1 - ); - assert!(schema["$defs"].get("GestaltIndividuation").is_none()); - let member_properties = schema["$defs"]["WorldComplexityMemberDraft"]["properties"] - .as_object() - .unwrap(); - for deterministic_field in [ - "schema", - "gestalt_id", - "version", - "last_location_id", - "materialized_actor_id", - "last_relevant_revision", - "relevance_lease_until_revision", - ] { - assert!(!member_properties.contains_key(deterministic_field)); - } - - let admitted = crate::agent::ModelAgentTool::invoke( - &mut tool, - WorldComplexityAction { - schema: "ghostlight.world_complexity_action.v1".into(), - mutation: WorldComplexityMutationDraft::Individuate { - member: individuation.member.into(), - }, - }, - &context, - ) - .await; - assert!(matches!( - admitted, - crate::agent::ModelAgentToolOutcome::Accepted { .. } - )); - } - - #[tokio::test] - async fn complexity_tool_reports_every_individuation_mismatch_for_agent_repair() { - let mut campaign = campaign_with_fission_parent(); - campaign.actors.insert( - "member:new-weirkeeper".into(), - crate::domain::ActorState { - id: "member:new-weirkeeper".into(), - name: "Orin Weirkeeper".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: Vec::new(), - memories: Vec::new(), - }, - ); - let mut tool = WorldComplexityTool { - campaign: &campaign, - parent_gestalt_id: "river-households", - title: ElaboratorTitle::Veil, - operation: WorldComplexityOperation::Individuate, - partition_axis: crate::domain::AgencyAxis::Information, - jurisdiction_location_id: "room", - target_actionable_gain: 1, - workbench: serde_json::json!({"schema":"test.workbench.v1"}), - }; - let context = crate::agent::ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }; - let valid_same_name = crate::domain::GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "other-weirkeeper".into(), - gestalt_id: "river-households".into(), - version: 0, - name: "Orin Weirkeeper".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::new(), - memories: Vec::new(), - last_location_id: Some("room".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }; - let same_name = crate::agent::ModelAgentTool::invoke( - &mut tool, - WorldComplexityAction { - schema: "ghostlight.world_complexity_action.v1".into(), - mutation: WorldComplexityMutationDraft::Individuate { - member: valid_same_name.clone().into(), - }, - }, - &context, - ) - .await; - let crate::agent::ModelAgentToolOutcome::Rejected { finding, .. } = same_name else { - panic!("duplicate public name was admitted") - }; - assert!(finding.diagnostic.contains("public Actor identity")); - let mut invalid = valid_same_name; - invalid.id = "new-weirkeeper".into(); - invalid.goals = (0..9).map(|index| format!("goal {index}")).collect(); - invalid - .relationships - .insert("actor:invented-stranger".into(), "owes a favor".into()); - let rejected = crate::agent::ModelAgentTool::invoke( - &mut tool, - WorldComplexityAction { - schema: "ghostlight.world_complexity_action.v1".into(), - mutation: WorldComplexityMutationDraft::Individuate { - member: invalid.into(), - }, - }, - &context, - ) - .await; - let crate::agent::ModelAgentToolOutcome::Rejected { finding, .. } = rejected else { - panic!("invalid individuation was admitted") - }; - assert!(finding.diagnostic.contains("more than eight goals")); - assert!( - finding - .diagnostic - .contains("duplicates an established canonical subject identity") - ); - assert!( - finding - .diagnostic - .contains("unsupported subjects: actor:invented-stranger") - ); - assert!(finding.diagnostic.contains("public Actor identity")); - } - - #[test] - fn complexity_fission_rebases_only_across_unchanged_parent_state() { - let frozen = campaign_with_fission_parent(); - let preview = valid_river_fission(&frozen); - let mut current = frozen.clone(); - current.revision = current.revision.saturating_add(1); - - let binding = world_complexity_parent_binding(&frozen, "river-households").unwrap(); - let rebased = rebase_world_complexity_proposal( - &binding, - ¤t, - WorldComplexityProposal::Fission { - preview: preview.clone(), - qualification: river_fission_qualification(), - }, - ) - .unwrap(); - let WorldComplexityProposal::Fission { - preview: rebased, .. - } = rebased - else { - panic!("rebased mutation changed kind") - }; - assert_eq!(rebased.expected_world_revision, current.revision); - - current - .gestalts - .get_mut("river-households") - .unwrap() - .pressures - .push("an intervening flood changed the parent".into()); - assert!( - rebase_world_complexity_proposal( - &binding, - ¤t, - WorldComplexityProposal::Fission { - preview, - qualification: river_fission_qualification(), - }, - ) - .is_err() - ); - } - - #[test] - fn complexity_fission_rebase_namespaces_only_colliding_child_ids() { - let frozen = campaign_with_fission_parent(); - let preview = valid_river_fission(&frozen); - let mut current = frozen.clone(); - current.revision = current.revision.saturating_add(1); - let mut collision = preview.children[0].clone(); - collision.name = "Preexisting Licensed Register".into(); - let parent = &frozen.gestalts["river-households"]; - collision.shared_capabilities = parent.shared_capabilities.clone(); - collision - .shared_capabilities - .insert("maintain tidal sluice clocks".into()); - collision.shared_knowledge = parent.shared_knowledge.clone(); - collision - .shared_knowledge - .insert("salt-rot marks on the old quay".into()); - collision.goals = parent.goals.clone(); - collision - .goals - .push("restore the abandoned east-quay sluice".into()); - collision.pressures = parent.pressures.clone(); - collision - .pressures - .push("spring tides are cracking the quay gates".into()); - current - .gestalts - .insert("licensed-river-households".into(), collision); - - let binding = world_complexity_parent_binding(&frozen, "river-households").unwrap(); - let rebased = rebase_world_complexity_proposal( - &binding, - ¤t, - WorldComplexityProposal::Fission { - preview, - qualification: river_fission_qualification(), - }, - ) - .unwrap(); - let WorldComplexityProposal::Fission { - preview: rebased, .. - } = rebased - else { - panic!("rebased mutation changed kind") - }; - let renamed = rebased - .children - .iter() - .find(|child| child.name == "Licensed River Households") - .unwrap(); - assert!(renamed.id.starts_with("river-households:fission:")); - assert!(rebased.child_partition_values.contains_key(&renamed.id)); - assert_eq!( - rebased.resource_child_assignments["ferry charter"], - renamed.id - ); - assert_eq!(rebased.residual_child_id, "unrecorded-river-households"); - } - - #[test] - fn complexity_fission_rebase_sees_agency_profile_id_collisions() { - let frozen = campaign_with_fission_parent(); - let preview = valid_river_fission(&frozen); - let colliding_id = preview.children[0].id.clone(); - let mut current = frozen.clone(); - current.revision = current.revision.saturating_add(1); - let mut reservation = current.agency_profiles["river-households"].clone(); - reservation.id = colliding_id; - reservation.subject_id = "detached-profile-subject".into(); - reservation.active_leaf = false; - reservation.simulation_eligible = false; - current - .agency_profiles - .insert("detached-profile-key".into(), reservation); - - let binding = world_complexity_parent_binding(&frozen, "river-households").unwrap(); - let rebase = || { - rebase_world_complexity_proposal( - &binding, - ¤t, - WorldComplexityProposal::Fission { - preview: preview.clone(), - qualification: river_fission_qualification(), - }, - ) - .unwrap() - }; - let renamed_id = |proposal: WorldComplexityProposal| { - let WorldComplexityProposal::Fission { preview, .. } = proposal else { - panic!("rebased mutation changed kind") - }; - preview - .children - .iter() - .find(|child| child.name == "Licensed River Households") - .unwrap() - .id - .clone() - }; - - let first = renamed_id(rebase()); - let second = renamed_id(rebase()); - assert!(first.starts_with("river-households:fission:")); - assert_eq!(first, second); - } - - fn profile(weights: &[(ElaboratorTitle, u16)]) -> WorldElaborationProfile { - WorldElaborationProfile { - schema: "ghostlight.world_elaboration_profile.v1".into(), - controls: weights - .iter() - .map(|(title, weight)| ElaboratorControl { - title: *title, - weight: *weight, - }) - .collect(), - } - } - - fn wave_binding() -> ElaborationWaveBinding { - ElaborationWaveBinding { - schema: "ghostlight.elaboration_wave_binding.v1".into(), - snapshot_binding: "world:7:seed-sha256".into(), - } - } - - struct CountingSubAgent { - counts: std::sync::Mutex>, - active: std::sync::atomic::AtomicUsize, - maximum: std::sync::atomic::AtomicUsize, - } - - #[async_trait] - impl ElaborationSubAgentPort for CountingSubAgent { - async fn invoke( - &self, - invocation: ElaborationSubAgentInvocation, - ) -> std::result::Result, ElaborationSubAgentFailure> - { - use std::sync::atomic::Ordering; - assert_eq!(invocation.wave, wave_binding()); - let dispatch = invocation.dispatch; - let active = self.active.fetch_add(1, Ordering::SeqCst) + 1; - self.maximum.fetch_max(active, Ordering::SeqCst); - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - *self - .counts - .lock() - .unwrap() - .entry(dispatch.title) - .or_default() += 1; - self.active.fetch_sub(1, Ordering::SeqCst); - Ok(ElaborationSubAgentOutput::deterministic(format!( - "proposal:{}", - dispatch.ordinal - ))) - } - } - - struct PartiallyFailingSubAgent; - - struct RecordingResumeSubAgent { - ordinals: std::sync::Mutex>, - } - - #[async_trait] - impl ElaborationSubAgentPort for PartiallyFailingSubAgent { - async fn invoke( - &self, - invocation: ElaborationSubAgentInvocation, - ) -> std::result::Result, ElaborationSubAgentFailure> - { - if invocation.dispatch.ordinal == 3 { - return Err(ElaborationSubAgentFailure { - diagnostic: "fixture refusal".into(), - model_stage_receipts: Vec::new(), - }); - } - if invocation.dispatch.ordinal == 4 { - panic!("fixture panic"); - } - Ok(ElaborationSubAgentOutput::deterministic(format!( - "proposal:{}", - invocation.dispatch.ordinal - ))) - } - } - - #[async_trait] - impl ElaborationSubAgentPort for RecordingResumeSubAgent { - async fn invoke( - &self, - invocation: ElaborationSubAgentInvocation, - ) -> std::result::Result, ElaborationSubAgentFailure> - { - self.ordinals - .lock() - .unwrap() - .push(invocation.dispatch.ordinal); - Ok(ElaborationSubAgentOutput::deterministic(format!( - "resumed:{}", - invocation.dispatch.ordinal - ))) - } - } - - #[test] - fn weighted_schedule_dispatches_in_proportion_to_slider_share() { - let profile = profile(&[(ElaboratorTitle::Patina, 20), (ElaboratorTitle::Tangle, 80)]); - let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); - let eligible = BTreeSet::from([ElaboratorTitle::Patina, ElaboratorTitle::Tangle]); - - let receipt = scheduler.schedule(&eligible, 100); - - assert_eq!(receipt.unused_invocations, 0); - assert_eq!(receipt.dispatch_counts[&ElaboratorTitle::Patina], 20); - assert_eq!(receipt.dispatch_counts[&ElaboratorTitle::Tangle], 80); - assert_eq!( - receipt.final_state.dispatch_counts[&ElaboratorTitle::Patina], - 20 - ); - assert_eq!( - receipt.final_state.dispatch_counts[&ElaboratorTitle::Tangle], - 80 - ); - assert!(receipt.dispatches.iter().all(|dispatch| { - dispatch.requested_share_millionths - == match dispatch.title { - ElaboratorTitle::Patina => 200_000, - ElaboratorTitle::Tangle => 800_000, - _ => unreachable!(), - } - })); - } - - #[tokio::test] - async fn weighted_share_controls_actual_parallel_sub_agent_invocations() { - use std::sync::atomic::Ordering; - let profile = profile(&[(ElaboratorTitle::Patina, 30), (ElaboratorTitle::Tangle, 70)]); - let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); - let eligible = BTreeSet::from([ElaboratorTitle::Patina, ElaboratorTitle::Tangle]); - let worker = Arc::new(CountingSubAgent { - counts: std::sync::Mutex::new(BTreeMap::new()), - active: std::sync::atomic::AtomicUsize::new(0), - maximum: std::sync::atomic::AtomicUsize::new(0), - }); - - let run = dispatch_elaboration_wave( - &mut scheduler, - wave_binding(), - &eligible, - 100, - 6, - worker.clone(), - ) - .await - .unwrap(); - - assert_eq!(run.wave, wave_binding()); - assert_eq!(run.invocations.len(), 100); - assert!( - run.invocations - .iter() - .all(|invocation| invocation.wave == wave_binding()) - ); - assert_eq!(run.invocations[0].dispatch.ordinal, 1); - assert_eq!(run.invocations[99].dispatch.ordinal, 100); - let counts = worker.counts.lock().unwrap(); - assert_eq!(counts[&ElaboratorTitle::Patina], 30); - assert_eq!(counts[&ElaboratorTitle::Tangle], 70); - assert!(worker.maximum.load(Ordering::SeqCst) > 1); - assert!(worker.maximum.load(Ordering::SeqCst) <= 6); - } - - #[tokio::test] - async fn failed_wave_preserves_consumed_schedule_and_completed_evidence() { - let profile = profile(&[(ElaboratorTitle::Patina, 100)]); - let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); - let failure = dispatch_elaboration_wave( - &mut scheduler, - wave_binding(), - &BTreeSet::from([ElaboratorTitle::Patina]), - 4, - 2, - Arc::new(PartiallyFailingSubAgent), - ) - .await - .unwrap_err(); - - assert_eq!(failure.wave, Some(wave_binding())); - assert_eq!(failure.schedule.as_ref().unwrap().dispatches.len(), 4); - assert_eq!(failure.completed_invocations.len(), 2); - assert_eq!(failure.invocation_failures.len(), 2); - assert_eq!( - failure.invocation_failures[0] - .dispatch - .as_ref() - .unwrap() - .ordinal, - 3 - ); - assert_eq!( - failure.invocation_failures[1] - .dispatch - .as_ref() - .unwrap() - .ordinal, - 4 - ); - assert_eq!(scheduler.state().total_budget_slots, 4); - assert!(failure.completed_invocations.iter().all(|invocation| { - invocation.wave == wave_binding() && invocation.dispatch.ordinal != 3 - })); - } - - #[tokio::test] - async fn partial_wave_resume_invokes_only_failed_original_dispatches() { - let profile = profile(&[(ElaboratorTitle::Patina, 100)]); - let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); - let failure = dispatch_elaboration_wave( - &mut scheduler, - wave_binding(), - &BTreeSet::from([ElaboratorTitle::Patina]), - 4, - 2, - Arc::new(PartiallyFailingSubAgent), - ) - .await - .unwrap_err(); - let original_schedule = failure.schedule.clone().unwrap(); - let completed_before = failure - .completed_invocations - .iter() - .map(|invocation| invocation.dispatch.ordinal) - .collect::>(); - let worker = Arc::new(RecordingResumeSubAgent { - ordinals: std::sync::Mutex::new(Vec::new()), - }); - - let run = resume_elaboration_wave(failure, 2, worker.clone()) - .await - .unwrap(); - - assert_eq!(worker.ordinals.lock().unwrap().as_slice(), &[3, 4]); - assert_eq!(completed_before, vec![1, 2]); - assert_eq!(run.schedule, original_schedule); - assert_eq!( - run.invocations - .iter() - .map(|invocation| invocation.dispatch.ordinal) - .collect::>(), - vec![1, 2, 3, 4] - ); - assert_eq!(scheduler.state().total_dispatches, 4); - } - - #[tokio::test] - async fn partial_wave_resume_refuses_a_checkpoint_with_duplicate_authority() { - let profile = profile(&[(ElaboratorTitle::Patina, 100)]); - let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); - let mut failure = dispatch_elaboration_wave( - &mut scheduler, - wave_binding(), - &BTreeSet::from([ElaboratorTitle::Patina]), - 4, - 2, - Arc::new(PartiallyFailingSubAgent), - ) - .await - .unwrap_err(); - failure.invocation_failures[0].dispatch = - Some(failure.completed_invocations[0].dispatch.clone()); - let worker = Arc::new(RecordingResumeSubAgent { - ordinals: std::sync::Mutex::new(Vec::new()), - }); - - let resumed = resume_elaboration_wave(failure, 2, worker.clone()).await; - - assert!(resumed.is_err()); - assert!(worker.ordinals.lock().unwrap().is_empty()); - assert!( - resumed.unwrap_err().invocation_failures[0] - .diagnostic - .contains("does not match its exact schedule") - ); - } - - #[test] - fn ineligible_titles_consume_their_share_without_catchup_debt() { - let profile = profile(&[(ElaboratorTitle::Patina, 20), (ElaboratorTitle::Tangle, 80)]); - let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); - - let patina_only = BTreeSet::from([ElaboratorTitle::Patina]); - let first = scheduler.schedule(&patina_only, 5); - assert_eq!( - first.final_state.dispatch_counts[&ElaboratorTitle::Patina], - 1 - ); - assert_eq!(first.unused_invocations, 4); - assert_eq!(first.unused_counts[&ElaboratorTitle::Tangle], 4); - - let both = BTreeSet::from([ElaboratorTitle::Patina, ElaboratorTitle::Tangle]); - let second = scheduler.schedule(&both, 100); - assert_eq!(second.dispatch_counts[&ElaboratorTitle::Patina], 20); - assert_eq!(second.dispatch_counts[&ElaboratorTitle::Tangle], 80); - assert_eq!( - second.final_state.dispatch_counts[&ElaboratorTitle::Patina], - 21 - ); - assert_eq!( - second.final_state.dispatch_counts[&ElaboratorTitle::Tangle], - 80 - ); - } - - #[test] - fn disabled_or_blocked_elaborators_leave_budget_visibly_unused() { - let profile = profile(&[(ElaboratorTitle::Patina, 100)]); - let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); - let receipt = scheduler.schedule(&BTreeSet::from([ElaboratorTitle::Veil]), 7); - - assert!(receipt.dispatches.is_empty()); - assert_eq!(receipt.unused_invocations, 7); - assert_eq!(receipt.unused_counts[&ElaboratorTitle::Patina], 7); - assert_eq!(receipt.final_state.total_budget_slots, 7); - assert_eq!(receipt.final_state.total_dispatches, 0); - } - - #[test] - fn a_partially_blocked_profile_does_not_donate_its_share() { - let profile = profile(&[(ElaboratorTitle::Patina, 20), (ElaboratorTitle::Tangle, 80)]); - let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); - let receipt = scheduler.schedule(&BTreeSet::from([ElaboratorTitle::Patina]), 100); - - assert_eq!(receipt.dispatch_counts[&ElaboratorTitle::Patina], 20); - assert_eq!(receipt.unused_counts[&ElaboratorTitle::Tangle], 80); - assert_eq!(receipt.unused_invocations, 80); - assert_eq!(receipt.final_state.total_budget_slots, 100); - assert_eq!(receipt.final_state.total_dispatches, 20); - } - - #[test] - fn profile_rejects_duplicate_titles_and_an_all_zero_budget() { - assert!( - profile(&[(ElaboratorTitle::Patina, 10), (ElaboratorTitle::Patina, 20),]) - .weights() - .is_err() - ); - assert!(profile(&[(ElaboratorTitle::Patina, 0)]).weights().is_err()); - } - - #[test] - fn persisted_scheduler_state_binds_semantic_weights_not_control_order() { - let first = profile(&[(ElaboratorTitle::Patina, 25), (ElaboratorTitle::Tangle, 75)]); - let scheduler = ElaborationScheduler::new(&first).unwrap(); - let state = scheduler.state().clone(); - let reordered = profile(&[(ElaboratorTitle::Tangle, 75), (ElaboratorTitle::Patina, 25)]); - assert!(ElaborationScheduler::from_state(&reordered, state.clone()).is_ok()); - - let changed = profile(&[(ElaboratorTitle::Patina, 75), (ElaboratorTitle::Tangle, 25)]); - assert!(ElaborationScheduler::from_state(&changed, state).is_err()); - } - - #[test] - fn catalog_exposes_every_titled_slider_with_a_distinct_mandate() { - let catalog = elaborator_catalog(); - assert_eq!(catalog.len(), ElaboratorTitle::ALL.len()); - assert_eq!( - catalog - .iter() - .map(|entry| entry.title) - .collect::>() - .len(), - ElaboratorTitle::ALL.len() - ); - assert!(catalog.iter().all(|entry| !entry.mandate.trim().is_empty())); - assert!(catalog.iter().any(|entry| { - entry.title == ElaboratorTitle::Patina && entry.mandate.contains("low-stakes texture") - })); - } - - #[test] - fn titled_operations_cannot_mint_source_evidence_authority() { - let operation = WorldElaborationOperation::AddFact { - fact: crate::domain::WorldFact { - id: "branch-fact".into(), - statement: "The gate duck is called Harold.".into(), - scope: crate::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec!["invented-receipt".into()], - discoverable_at_location_ids: BTreeSet::from(["room".into()]), - }, - }; - - let error = operation_claims(&operation).unwrap_err(); - - assert!(error.to_string().contains("cannot attach source-evidence")); - } - - struct PanicIfInvokedModel; - - struct ExactAssignmentSchemaModel; - - struct ExactSessionCompactionModel; - - struct RejectionOnlySessionCompactionModel; - - struct ReceiptlessWorldWorker; - - #[async_trait] - impl ElaborationSubAgentPort for ReceiptlessWorldWorker { - async fn invoke( - &self, - _invocation: ElaborationSubAgentInvocation, - ) -> std::result::Result< - ElaborationSubAgentOutput, - ElaborationSubAgentFailure, - > { - Ok(ElaborationSubAgentOutput::deterministic( - WorldElaborationProposal { - schema: "ghostlight.world_elaboration_proposal.v1".into(), - operation: WorldElaborationOperation::AddFact { - fact: crate::domain::WorldFact { - id: "receiptless-fact".into(), - statement: "This proposal has no provider custody.".into(), - scope: crate::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["room".into()]), - }, - }, - }, - )) - } - } - - #[async_trait] - impl crate::model::ModelPort for PanicIfInvokedModel { - async fn run(&self, _request: &crate::model::ModelStageRequest) -> Result { - panic!("stale world worker reached the model") - } - - fn provider(&self) -> &'static str { - "panic-fixture" - } - } - - #[async_trait] - impl crate::model::ModelPort for ExactAssignmentSchemaModel { - async fn run(&self, request: &crate::model::ModelStageRequest) -> Result { - let schema = request - .output_schema - .as_ref() - .ok_or_else(|| anyhow!("titled agent lost its action schema"))?; - assert_eq!( - schema.pointer("/$defs/WorldElaborationOperation/oneOf/0/properties/type/const"), - Some(&serde_json::json!("add_fact")) - ); - assert_eq!( - schema - .pointer("/$defs/WorldElaborationOperation/oneOf") - .and_then(serde_json::Value::as_array) - .map(Vec::len), - Some(1) - ); - assert_eq!( - schema.pointer("/$defs/WorldFact/properties/id/const"), - Some(&serde_json::json!("elab:room:charter-fact:2")) - ); - let output = serde_json::json!({ - "schema":"ghostlight.world_elaboration_proposal.v1", - "operation":{ - "type":"add_fact", - "fact":{ - "id":"elab:room:charter-fact:2", - "statement":"The room elects a threshold witness after every public repair count.", - "scope":"branch_local", - "evidence_receipt_ids":[], - "discoverable_at_location_ids":["room"] - } - } - }); - let validator = jsonschema::validator_for(schema)?; - assert!(validator.is_valid(&output)); - let mut wrong_id = output.clone(); - wrong_id["operation"]["fact"]["id"] = serde_json::json!("wrong-id"); - assert!(!validator.is_valid(&wrong_id)); - assert!(!validator.is_valid(&serde_json::json!({ - "schema":"ghostlight.world_elaboration_proposal.v1", - "operation":{ - "type":"set_civic_system", - "system":{} - } - }))); - let mut provider_schema = schema.clone(); - crate::model_connector::project_strict_responses_schema(&mut provider_schema)?; - assert!(jsonschema::validator_for(&provider_schema)?.is_valid(&output)); - Ok(output.to_string()) - } - - fn provider(&self) -> &'static str { - "exact-assignment-schema-fixture" - } - } - - #[async_trait] - impl crate::model::ModelPort for ExactSessionCompactionModel { - async fn run(&self, request: &crate::model::ModelStageRequest) -> Result { - assert!(request.stage.ends_with("session-compaction")); - assert!(request.lived_stream.contains("world-commit:12")); - assert!(request.lived_stream.contains("threshold witness")); - Ok(serde_json::json!({ - "schema":"ghostlight.elaborator_session_compaction_draft.v1", - "frontier_summary":"The threshold witness office still lacks a succession rule.", - "unresolved_leads":["Fission the electorate by access to public count challenges."] - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "session-compaction-fixture" - } - } - - #[async_trait] - impl crate::model::ModelPort for RejectionOnlySessionCompactionModel { - async fn run(&self, request: &crate::model::ModelStageRequest) -> Result { - assert!(request.stage.ends_with("session-compaction")); - assert!( - request - .lived_stream - .contains("causal_additions_do_not_repeat_an_overused_procedural_template") - ); - Ok(serde_json::json!({ - "schema":"ghostlight.elaborator_session_compaction_draft.v1", - "frontier_summary":"The rejected filing mold remains a live design constraint.", - "unresolved_leads":["Replace procedure with a materially executable conflict."] - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "rejection-session-compaction-fixture" - } - } - - #[tokio::test] - async fn session_compactor_preserves_exact_journal_ancestry() { - let campaign = campaign_with_civic_room(); - let (checkpoint, receipts) = compact_elaborator_session( - &ExactSessionCompactionModel, - &campaign, - "room", - ElaboratorTitle::Charter, - "charter:room", - None, - &[ElaboratorSessionJournalEntry { - world_revision: campaign.revision, - commit_receipt_id: "world-commit:12".into(), - mutation_kind: "fission_gestalt".into(), - affected_subject_ids: vec!["threshold-witnesses".into()], - summary: "The threshold witness electorate split over public challenges.".into(), - }], - vec!["A duplicate office proposal was rejected.".into()], - ) - .await - .unwrap(); - - assert_eq!(checkpoint.recent_commit_receipt_ids, ["world-commit:12"]); - assert_eq!(checkpoint.generation, 0); - assert_eq!(receipts.len(), 1); - checkpoint - .validate_for(&campaign, "room", ElaboratorTitle::Charter) - .unwrap(); - } - - #[tokio::test] - async fn session_compactor_carries_a_semantic_rejection_without_a_commit() { - let campaign = campaign_with_civic_room(); - let finding = "{\"causal_additions_do_not_repeat_an_overused_procedural_template\":false}"; - let (checkpoint, receipts) = compact_elaborator_session( - &RejectionOnlySessionCompactionModel, - &campaign, - "room", - ElaboratorTitle::Charter, - "charter:room", - None, - &[], - vec![finding.into()], - ) - .await - .unwrap(); - - assert!(checkpoint.recent_commit_receipt_ids.is_empty()); - assert_eq!(checkpoint.recent_rejection_findings, [finding]); - assert_eq!(receipts.len(), 1); - checkpoint - .validate_for(&campaign, "room", ElaboratorTitle::Charter) - .unwrap(); - } - - #[tokio::test] - async fn session_compactor_reports_every_deterministic_preflight_mismatch() { - let campaign = campaign_with_civic_room(); - let error = compact_elaborator_session( - &PanicIfInvokedModel, - &campaign, - "missing-realm", - ElaboratorTitle::Charter, - "charter:missing-realm", - None, - &[ - ElaboratorSessionJournalEntry { - world_revision: campaign.revision.saturating_add(1), - commit_receipt_id: " ".into(), - mutation_kind: "".into(), - affected_subject_ids: (0..33).map(|index| format!("subject-{index}")).collect(), - summary: " ".into(), - }, - ElaboratorSessionJournalEntry { - world_revision: campaign.revision, - commit_receipt_id: "world-commit:13".into(), - mutation_kind: "fission_gestalt".into(), - affected_subject_ids: Vec::new(), - summary: "x".repeat(1_001), - }, - ], - Vec::new(), - ) - .await - .unwrap_err() - .to_string(); - - assert!(error.contains("target location \"missing-realm\" is absent")); - assert!(error.contains("journal[0].world_revision")); - assert!(error.contains("journal[0].commit_receipt_id is empty")); - assert!(error.contains("journal[0].mutation_kind is empty")); - assert!(error.contains("journal[0].summary is empty")); - assert!(error.contains("journal[0].affected_subject_ids contains 33")); - assert!(error.contains("journal[1].summary contains 1001 characters")); - } - - #[test] - fn elaborator_session_routing_separates_titles_and_realm_jurisdictions() { - assert_ne!( - elaborator_session_id(ElaboratorTitle::Patina, "elven-realms"), - elaborator_session_id(ElaboratorTitle::Patina, "kharad-hearths") - ); - assert_ne!( - elaborator_session_id(ElaboratorTitle::Patina, "elven-realms"), - elaborator_session_id(ElaboratorTitle::Charter, "elven-realms") - ); - assert_eq!( - elaborator_session_id(ElaboratorTitle::Patina, "elven-realms"), - "patina:elven-realms" - ); - } - - #[test] - fn complexity_worker_rejects_a_cross_bound_session_identity() { - let campaign = campaign_with_fission_parent(); - let checkpoint = ElaboratorSessionCheckpoint::bind_compaction( - "patina:room", - ElaboratorTitle::Charter, - 0, - campaign.id, - campaign.revision, - "room", - ElaboratorSessionCompactionDraft { - schema: "ghostlight.elaborator_session_compaction_draft.v1".into(), - frontier_summary: "A valid checkpoint parked under another title's key.".into(), - unresolved_leads: Vec::new(), - }, - vec!["world-commit:1".into()], - Vec::new(), - None, - ) - .unwrap(); - - let result = ModelWorldComplexityWorker::new( - Arc::new(PanicIfInvokedModel), - Arc::new(campaign), - 1, - vec!["river-households".into()], - BTreeMap::from([("river-households".into(), "room".into())]), - 1, - BTreeMap::from([("patina:room".into(), checkpoint)]), - ); - - let error = match result { - Ok(_) => panic!("cross-bound elaborator session reached the worker"), - Err(error) => error, - }; - assert!(error.to_string().contains("misrouted session checkpoint")); - } - - #[test] - fn complexity_worker_accepts_a_canonical_containing_jurisdiction() { - let mut campaign = campaign_with_fission_parent(); - campaign.locations.get_mut("room").unwrap().container_id = Some("realm".into()); - campaign.locations.insert( - "realm".into(), - crate::domain::Location { - id: "realm".into(), - name: "Realm".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: Vec::new(), - }, - ); - - let worker = ModelWorldComplexityWorker::new( - Arc::new(PanicIfInvokedModel), - Arc::new(campaign), - 1, - vec!["river-households".into()], - BTreeMap::from([("river-households".into(), "realm".into())]), - 1, - BTreeMap::new(), - ); - - assert!(worker.is_ok()); - } - - #[tokio::test] - async fn provider_worker_rejects_a_wave_from_a_newer_world_before_model_inference() { - let frozen = campaign_with_civic_room(); - let worker = ModelWorldElaborationWorker::new( - Arc::new(PanicIfInvokedModel), - Arc::new(frozen.clone()), - "room", - "add texture", - ) - .unwrap(); - assert_eq!(worker.task_request(), "add texture"); - let mut current = frozen; - current.revision = 1; - let invocation = ElaborationSubAgentInvocation { - wave: world_elaboration_wave_binding(¤t, "room").unwrap(), - dispatch: ElaborationDispatch { - schema: "ghostlight.elaboration_dispatch.v1".into(), - budget_ordinal: 1, - ordinal: 1, - title: ElaboratorTitle::Patina, - title_weight: 1, - total_enabled_weight: 1, - requested_share_millionths: 1_000_000, - title_dispatch_count: 1, - }, - }; - - let error = worker.invoke(invocation).await.unwrap_err(); - - assert!(error.diagnostic.contains("frozen campaign")); - assert!(error.model_stage_receipts.is_empty()); - } - - #[tokio::test] - async fn provider_worker_publishes_the_exact_assignment_schema() { - let campaign = campaign_with_civic_room(); - let worker = ModelWorldElaborationWorker::new( - Arc::new(ExactAssignmentSchemaModel), - Arc::new(campaign.clone()), - "room", - "add political texture", - ) - .unwrap(); - let output = worker - .invoke(ElaborationSubAgentInvocation { - wave: world_elaboration_wave_binding(&campaign, "room").unwrap(), - dispatch: ElaborationDispatch { - schema: "ghostlight.elaboration_dispatch.v1".into(), - budget_ordinal: 2, - ordinal: 2, - title: ElaboratorTitle::Charter, - title_weight: 1, - total_enabled_weight: 1, - requested_share_millionths: 1_000_000, - title_dispatch_count: 2, - }, - }) - .await - .unwrap(); - - assert_eq!(output.model_stage_receipts.len(), 1); - assert!(matches!( - output.proposal.operation, - WorldElaborationOperation::AddFact { ref fact } - if fact.id == "elab:room:charter-fact:2" - )); - } - - #[test] - fn every_assignment_schema_exposes_one_owned_operation_variant() { - let mut campaign = campaign_with_civic_room(); - campaign - .civic_systems - .get_mut("room") - .unwrap() - .governing_institution_ids = - BTreeSet::from(["first-council".into(), "second-council".into()]); - let cases = [ - (ElaboratorTitle::Patina, 1, "add_place"), - (ElaboratorTitle::Patina, 2, "add_route"), - (ElaboratorTitle::Patina, 3, "add_route"), - (ElaboratorTitle::Charter, 1, "set_civic_system"), - (ElaboratorTitle::Charter, 2, "add_fact"), - (ElaboratorTitle::Tangle, 1, "add_local_relation"), - (ElaboratorTitle::Tangle, 2, "add_fact"), - (ElaboratorTitle::Ledger, 1, "add_fact"), - ]; - - for (ordinal, (title, title_dispatch_count, expected_type)) in cases.into_iter().enumerate() - { - let assignment = WorldElaborationAssignment::for_dispatch( - &campaign, - "room", - &ElaborationDispatch { - schema: "ghostlight.elaboration_dispatch.v1".into(), - budget_ordinal: ordinal as u64 + 1, - ordinal: ordinal as u64 + 1, - title, - title_weight: 1, - total_enabled_weight: 1, - requested_share_millionths: 1_000_000, - title_dispatch_count, - }, - ) - .unwrap(); - let schema = assignment.action_schema("room").unwrap(); - let branches = schema - .pointer("/$defs/WorldElaborationOperation/oneOf") - .and_then(serde_json::Value::as_array) - .unwrap(); - - assert_eq!(branches.len(), 1); - assert_eq!( - branches[0] - .pointer("/properties/type/const") - .and_then(serde_json::Value::as_str), - Some(expected_type) - ); - let mut provider_schema = schema; - crate::model_connector::project_strict_responses_schema(&mut provider_schema).unwrap(); - jsonschema::validator_for(&provider_schema).unwrap(); - } - } - - #[test] - fn assignment_rejection_returns_the_exact_correction_contract() { - let campaign = campaign_with_civic_room(); - let assignment = WorldElaborationAssignment::for_dispatch( - &campaign, - "room", - &ElaborationDispatch { - schema: "ghostlight.elaboration_dispatch.v1".into(), - budget_ordinal: 2, - ordinal: 2, - title: ElaboratorTitle::Charter, - title_weight: 1, - total_enabled_weight: 1, - requested_share_millionths: 1_000_000, - title_dispatch_count: 2, - }, - ) - .unwrap(); - let wrong = WorldElaborationProposal { - schema: "ghostlight.world_elaboration_proposal.v1".into(), - operation: WorldElaborationOperation::AddFact { - fact: crate::domain::WorldFact { - id: "wrong-id".into(), - statement: "A valid-shaped fact with the wrong assignment identity.".into(), - scope: crate::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["room".into()]), - }, - }, - }; - - let error = assignment.validate(&campaign, "room", &wrong).unwrap_err(); - - assert!( - error - .to_string() - .contains("correct it against this exact contract") - ); - assert!(error.to_string().contains("elab:room:charter-fact:2")); - assert!(error.to_string().contains("exactly one add_fact")); - } - - #[tokio::test] - async fn assignment_tool_rejects_a_relation_schema_bypass_then_accepts_the_correction() { - let mut campaign = campaign_with_civic_room(); - campaign - .civic_systems - .get_mut("room") - .unwrap() - .governing_institution_ids = - BTreeSet::from(["first-council".into(), "second-council".into()]); - let assignment = WorldElaborationAssignment::for_dispatch( - &campaign, - "room", - &ElaborationDispatch { - schema: "ghostlight.elaboration_dispatch.v1".into(), - budget_ordinal: 1, - ordinal: 1, - title: ElaboratorTitle::Tangle, - title_weight: 1, - total_enabled_weight: 1, - requested_share_millionths: 1_000_000, - title_dispatch_count: 1, - }, - ) - .unwrap(); - let wrong = WorldElaborationProposal { - schema: "ghostlight.world_elaboration_proposal.v1".into(), - operation: WorldElaborationOperation::AddLocalRelation { - relation: crate::domain::AgencyRelation { - schema: "wrong.relation.schema".into(), - id: "elab:room:tangle-relation:1".into(), - from_subject_id: "first-council".into(), - to_subject_id: "second-council".into(), - kind: crate::domain::AgencyRelationKind::Rivalry, - strength: 50, - active: true, - evidence_receipt_ids: vec![], - }, - }, - }; - let mut tool = WorldElaborationAgentTool { - campaign: &campaign, - target_location_id: "room", - assignment: &assignment, - workbench: serde_json::json!({"schema":"test.workbench.v1"}), - }; - let context = crate::agent::ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }; - - let rejected = crate::agent::ModelAgentTool::invoke(&mut tool, wrong, &context).await; - match rejected { - crate::agent::ModelAgentToolOutcome::Rejected { finding, .. } => { - assert!( - finding - .diagnostic - .contains(crate::domain::AgencyRelation::SCHEMA) - ); - } - _ => panic!("wrong relation schema bypassed the assignment tool"), - } - - let corrected = WorldElaborationProposal { - schema: "ghostlight.world_elaboration_proposal.v1".into(), - operation: WorldElaborationOperation::AddLocalRelation { - relation: crate::domain::AgencyRelation { - schema: crate::domain::AgencyRelation::SCHEMA.into(), - id: "elab:room:tangle-relation:1".into(), - from_subject_id: "first-council".into(), - to_subject_id: "second-council".into(), - kind: crate::domain::AgencyRelationKind::Rivalry, - strength: 50, - active: true, - evidence_receipt_ids: vec![], - }, - }, - }; - - let accepted = crate::agent::ModelAgentTool::invoke(&mut tool, corrected, &context).await; - assert!(matches!( - accepted, - crate::agent::ModelAgentToolOutcome::Accepted { .. } - )); - } - - #[tokio::test] - async fn world_admission_rejects_a_successful_receiptless_agent_proposal() { - let campaign = crate::kernel::tests::campaign(); - let mut scheduler = - ElaborationScheduler::new(&profile(&[(ElaboratorTitle::Patina, 1)])).unwrap(); - let run = dispatch_elaboration_wave( - &mut scheduler, - world_elaboration_wave_binding(&campaign, "room").unwrap(), - &BTreeSet::from([ElaboratorTitle::Patina]), - 1, - 1, - Arc::new(ReceiptlessWorldWorker), - ) - .await - .unwrap(); - - let error = admit_world_elaboration_wave(&campaign, "room", run).unwrap_err(); - - assert!(error.to_string().contains("lacks model receipt custody")); - } -} diff --git a/crates/ghostlight-dungeon/src/eve.rs b/crates/ghostlight-dungeon/src/eve.rs new file mode 100644 index 0000000..5dfbeca --- /dev/null +++ b/crates/ghostlight-dungeon/src/eve.rs @@ -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, + pub(crate) idempotency_key: Option, + #[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, + pub(crate) transport: Option, +} + +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 { + 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::>(); + 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::>().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, + source_version: Option, + plugin_payload: Option, + receipt: Option, +) -> 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, + commands: Vec, +) -> 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::(outer).is_err()); + + let mut route = serde_json::to_value(&exact).unwrap(); + route["operation"]["routeHint"]["caller"] = json!("legacy-owner"); + assert!(serde_json::from_value::(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()); + } +} diff --git a/crates/ghostlight-dungeon/src/follow_through.rs b/crates/ghostlight-dungeon/src/follow_through.rs deleted file mode 100644 index d96f733..0000000 --- a/crates/ghostlight-dungeon/src/follow_through.rs +++ /dev/null @@ -1,1422 +0,0 @@ -use crate::{ - agent::{ModelAgentSpec, ModelAgentTool, ModelAgentToolContext, ModelAgentToolOutcome}, - domain::{Campaign, CausalFollowThroughAssignment, Event, ResolutionCover, SimulationCell}, - model::{MODEL_BALANCED, ModelPort, ModelStageReceipt}, - resolution::cell_action_limit, -}; -use anyhow::{Result, anyhow}; -use async_trait::async_trait; -use schemars::{JsonSchema, schema_for}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; - -pub const NEMESIS_STAGE: &str = "nemesis_attention_agent_action"; -const HISTORY_PAGE_SIZE: usize = 24; -const INITIAL_EVENT_WINDOW: usize = 24; -const CURRENT_ANCHOR_PAGE_SIZE: usize = 24; -const RESPONDER_PAGE_SIZE: usize = 12; -const MAX_FOLLOW_THROUGH_STEPS: usize = 6; - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct CausalAssignmentDraft { - anchor_reference: String, - responder_subject_id: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(deny_unknown_fields)] -struct CausalFollowThroughAction { - command: CausalFollowThroughCommand, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -enum CausalFollowThroughCommand { - InspectWorldHistory { - cursor: usize, - }, - InspectSubjectHistory { - responder_subject_id: String, - cursor: usize, - }, - InspectCurrentAnchors { - cursor: usize, - }, - InspectAnchorResponders { - anchor_reference: String, - cursor: usize, - }, - Submit { - assignments: Vec, - }, -} - -#[derive(Clone, Debug, Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -enum CausalFollowThroughFinding { - HistoryPage { - scope: String, - anchors: Vec, - next_cursor: Option, - }, - ResponderPage { - anchor: CausalAnchorSummaryView, - responders: Vec, - next_cursor: Option, - }, - InvalidAgenda { - diagnostic: String, - }, -} - -#[derive(Clone, Debug, Serialize)] -struct CausalAnchorSummaryView { - anchor_reference: String, - kind: String, - account: String, - originating_subject_ids: Vec, - eligible_responder_count: usize, -} - -#[derive(Clone, Debug, Serialize)] -struct CausalResponderView { - subject_id: String, - name: String, - subject_kind: String, - stakes: Vec, - cell_id: String, - cell_decision_slot_limit: usize, -} - -#[derive(Clone, Debug)] -struct CausalAnchorCandidate { - anchor_reference: String, - kind: String, - account: String, - originating_subject_ids: Vec, - eligible_responder_ids: BTreeSet, -} - -impl CausalAnchorCandidate { - fn summary(&self) -> CausalAnchorSummaryView { - CausalAnchorSummaryView { - anchor_reference: self.anchor_reference.clone(), - kind: self.kind.clone(), - account: self.account.clone(), - originating_subject_ids: self.originating_subject_ids.clone(), - eligible_responder_count: self.eligible_responder_ids.len(), - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct CausalFollowThroughAdmission { - pub schema: String, - pub expected_revision: u64, - pub snapshot_binding: String, - pub assignment_batch_digest: String, - pub assignments: Vec, -} - -pub struct CausalFollowThroughProposal { - pub admission: CausalFollowThroughAdmission, - pub receipts: Vec, -} - -struct CausalFollowThroughTool<'a> { - campaign: &'a Campaign, - cover: &'a ResolutionCover, - all_public_events: Vec<&'a Event>, - current_anchors: Vec, - discovered: BTreeMap, - responder_views: BTreeMap, -} - -impl CausalFollowThroughTool<'_> { - fn inspect_world_page(&mut self, cursor: usize) -> Result { - if cursor > self.all_public_events.len() { - return Err(anyhow!( - "world-history cursor is outside the committed event ledger" - )); - } - let end = cursor - .saturating_add(HISTORY_PAGE_SIZE) - .min(self.all_public_events.len()); - let events = self.all_public_events[cursor..end].to_vec(); - let anchors = self.discover_events(events)?; - Ok(CausalFollowThroughFinding::HistoryPage { - scope: "committed public world history".into(), - anchors, - next_cursor: (end < self.all_public_events.len()).then_some(end), - }) - } - - fn inspect_subject_page( - &mut self, - responder_subject_id: &str, - cursor: usize, - ) -> Result { - if !self.responder_views.contains_key(responder_subject_id) { - return Err(anyhow!( - "subject-history query names an ineligible responder" - )); - } - let perceived = self - .all_public_events - .iter() - .copied() - .filter(|event| subject_perceives_event(self.campaign, responder_subject_id, event)) - .collect::>(); - if cursor > perceived.len() { - return Err(anyhow!( - "subject-history cursor is outside that subject's committed history" - )); - } - let end = cursor - .saturating_add(HISTORY_PAGE_SIZE) - .min(perceived.len()); - let anchors = self.discover_events(perceived[cursor..end].to_vec())?; - Ok(CausalFollowThroughFinding::HistoryPage { - scope: format!("committed history perceived by {responder_subject_id}"), - anchors, - next_cursor: (end < perceived.len()).then_some(end), - }) - } - - fn discover_events(&mut self, events: Vec<&Event>) -> Result> { - let mut views = Vec::new(); - for event in events { - let candidate = - event_anchor_candidate(self.campaign, self.cover, event, &self.responder_views)?; - if candidate.eligible_responder_ids.is_empty() { - continue; - } - views.push(candidate.summary()); - self.discovered - .insert(candidate.anchor_reference.clone(), candidate); - } - Ok(views) - } - - fn inspect_current_anchor_page(&mut self, cursor: usize) -> Result { - if cursor > self.current_anchors.len() { - return Err(anyhow!( - "current-anchor cursor is outside the durable pressure ledger" - )); - } - let end = cursor - .saturating_add(CURRENT_ANCHOR_PAGE_SIZE) - .min(self.current_anchors.len()); - let candidates = self.current_anchors[cursor..end].to_vec(); - let mut anchors = Vec::with_capacity(candidates.len()); - for candidate in candidates { - anchors.push(candidate.summary()); - self.discovered - .insert(candidate.anchor_reference.clone(), candidate); - } - Ok(CausalFollowThroughFinding::HistoryPage { - scope: "current durable pressure and clocks".into(), - anchors, - next_cursor: (end < self.current_anchors.len()).then_some(end), - }) - } - - fn inspect_anchor_responder_page( - &self, - anchor_reference: &str, - cursor: usize, - ) -> Result { - let candidate = self - .discovered - .get(anchor_reference) - .ok_or_else(|| anyhow!("responder query names an anchor the agent did not inspect"))?; - let responder_ids = candidate.eligible_responder_ids.iter().collect::>(); - if cursor > responder_ids.len() { - return Err(anyhow!( - "anchor-responder cursor is outside the eligible responder list" - )); - } - let end = cursor - .saturating_add(RESPONDER_PAGE_SIZE) - .min(responder_ids.len()); - let responders = responder_ids[cursor..end] - .iter() - .filter_map(|subject_id| self.responder_views.get(*subject_id).cloned()) - .collect(); - Ok(CausalFollowThroughFinding::ResponderPage { - anchor: candidate.summary(), - responders, - next_cursor: (end < responder_ids.len()).then_some(end), - }) - } - - fn validate_and_bind( - &self, - drafts: Vec, - ) -> Result> { - let maximum = self - .cover - .cells - .iter() - .map(cell_action_limit) - .sum::(); - if drafts.len() > maximum { - return Err(anyhow!( - "causal response agenda uses {} decision slots but the cover permits {maximum}", - drafts.len() - )); - } - let mut pairs = BTreeSet::new(); - let mut responders = BTreeSet::new(); - let mut per_cell = BTreeMap::::new(); - let mut assignments = Vec::with_capacity(drafts.len()); - for draft in drafts { - let anchor = self - .discovered - .get(&draft.anchor_reference) - .ok_or_else(|| { - anyhow!("causal agenda names an anchor the agent did not inspect") - })?; - if !anchor - .eligible_responder_ids - .contains(&draft.responder_subject_id) - { - return Err(anyhow!( - "{} cannot perceive or own a response to {}", - draft.responder_subject_id, - draft.anchor_reference - )); - } - if !pairs.insert(( - draft.anchor_reference.clone(), - draft.responder_subject_id.clone(), - )) || !responders.insert(draft.responder_subject_id.clone()) - { - return Err(anyhow!( - "each causal responder may own exactly one distinct anchor in a wave" - )); - } - let cell = responder_cell(self.campaign, self.cover, &draft.responder_subject_id) - .ok_or_else(|| anyhow!("causal responder is outside the exact cover"))?; - let count = per_cell.entry(cell.id.clone()).or_default(); - *count += 1; - if *count > cell_action_limit(cell) { - return Err(anyhow!( - "causal assignments exceed decision quota for cell {}", - cell.id - )); - } - assignments.push(CausalFollowThroughAssignment { - anchor_reference: draft.anchor_reference, - responder_subject_id: draft.responder_subject_id, - }); - } - for cell in &self.cover.cells { - let assigned = assignments - .iter() - .filter(|assignment| { - responder_cell(self.campaign, self.cover, &assignment.responder_subject_id) - .is_some_and(|owner| owner.id == cell.id) - }) - .collect::>(); - let represented_subjects = assigned - .iter() - .map(|assignment| { - assignment - .responder_subject_id - .strip_prefix("member:") - .and_then(|member_id| self.campaign.gestalt_members.get(member_id)) - .map(|member| member.gestalt_id.clone()) - .unwrap_or_else(|| assignment.responder_subject_id.clone()) - }) - .collect::>(); - if cell.detail_focus_subject_id.as_ref().is_some_and(|focus| { - !represented_subjects.contains(focus) && assigned.len() >= cell_action_limit(cell) - }) { - return Err(anyhow!( - "causal assignments consume every decision slot in cell {} without its mandatory detail-focus subject", - cell.id - )); - } - } - assignments.sort_by(|left, right| { - left.responder_subject_id - .cmp(&right.responder_subject_id) - .then_with(|| left.anchor_reference.cmp(&right.anchor_reference)) - }); - Ok(assignments) - } -} - -#[async_trait] -impl ModelAgentTool for CausalFollowThroughTool<'_> { - type Action = CausalFollowThroughAction; - type Output = CausalFollowThroughAdmission; - type Finding = CausalFollowThroughFinding; - - fn action_schema(&self) -> std::result::Result { - let mut schema = serde_json::to_value(schema_for!(CausalFollowThroughAction)) - .map_err(|error| error.to_string())?; - crate::model_connector::project_strict_responses_schema(&mut schema) - .map_err(|error| error.to_string())?; - constrain_action_schema( - &mut schema, - self.discovered.keys().cloned().collect(), - self.responder_views.keys().cloned().collect(), - ) - .map_err(|error| error.to_string())?; - Ok(schema) - } - - async fn invoke( - &mut self, - action: Self::Action, - context: &ModelAgentToolContext, - ) -> ModelAgentToolOutcome { - match action.command { - CausalFollowThroughCommand::InspectWorldHistory { cursor } => { - match self.inspect_world_page(cursor) { - Ok(observation) => ModelAgentToolOutcome::Continue { - observation, - receipts: Vec::new(), - }, - Err(error) => ModelAgentToolOutcome::Rejected { - finding: CausalFollowThroughFinding::InvalidAgenda { - diagnostic: error.to_string(), - }, - receipts: Vec::new(), - }, - } - } - CausalFollowThroughCommand::InspectSubjectHistory { - responder_subject_id, - cursor, - } => match self.inspect_subject_page(&responder_subject_id, cursor) { - Ok(observation) => ModelAgentToolOutcome::Continue { - observation, - receipts: Vec::new(), - }, - Err(error) => ModelAgentToolOutcome::Rejected { - finding: CausalFollowThroughFinding::InvalidAgenda { - diagnostic: error.to_string(), - }, - receipts: Vec::new(), - }, - }, - CausalFollowThroughCommand::InspectCurrentAnchors { cursor } => { - match self.inspect_current_anchor_page(cursor) { - Ok(observation) => ModelAgentToolOutcome::Continue { - observation, - receipts: Vec::new(), - }, - Err(error) => ModelAgentToolOutcome::Rejected { - finding: CausalFollowThroughFinding::InvalidAgenda { - diagnostic: error.to_string(), - }, - receipts: Vec::new(), - }, - } - } - CausalFollowThroughCommand::InspectAnchorResponders { - anchor_reference, - cursor, - } => match self.inspect_anchor_responder_page(&anchor_reference, cursor) { - Ok(observation) => ModelAgentToolOutcome::Continue { - observation, - receipts: Vec::new(), - }, - Err(error) => ModelAgentToolOutcome::Rejected { - finding: CausalFollowThroughFinding::InvalidAgenda { - diagnostic: error.to_string(), - }, - receipts: Vec::new(), - }, - }, - CausalFollowThroughCommand::Submit { assignments } => { - match self.validate_and_bind(assignments) { - Ok(assignments) => { - let Some(mut accepted_receipt) = context.current_model_receipt.clone() - else { - return ModelAgentToolOutcome::Failed { - message: "causal follow-through tool lacks its model receipt" - .into(), - receipts: Vec::new(), - }; - }; - let snapshot_binding = - match causal_follow_through_snapshot(self.campaign, self.cover) { - Ok(binding) => binding, - Err(error) => { - return ModelAgentToolOutcome::Failed { - message: error.to_string(), - receipts: Vec::new(), - }; - } - }; - let assignment_batch_digest = - match causal_assignment_batch_digest(&assignments) { - Ok(digest) => digest, - Err(error) => { - return ModelAgentToolOutcome::Failed { - message: error.to_string(), - receipts: Vec::new(), - }; - } - }; - accepted_receipt.rebind_snapshot(format!( - "{snapshot_binding}:causal-agenda:{assignment_batch_digest}" - )); - ModelAgentToolOutcome::Accepted { - output: CausalFollowThroughAdmission { - schema: "ghostlight.causal_follow_through_admission.v1".into(), - expected_revision: self.campaign.revision, - snapshot_binding, - assignment_batch_digest, - assignments, - }, - receipts: vec![accepted_receipt], - } - } - Err(error) => ModelAgentToolOutcome::Rejected { - finding: CausalFollowThroughFinding::InvalidAgenda { - diagnostic: error.to_string(), - }, - receipts: Vec::new(), - }, - } - } - } - } -} - -pub async fn propose_causal_follow_through( - model: &dyn ModelPort, - campaign: &Campaign, - cover: &ResolutionCover, -) -> std::result::Result, crate::agent::ModelAgentFailure> { - let responder_views = responder_views(campaign, cover); - let current_anchors = current_anchor_candidates(campaign, cover, &responder_views); - let all_public_events = campaign - .events - .iter() - .rev() - .filter(|event| !event.public_channels.is_empty()) - .collect::>(); - let mut tool = CausalFollowThroughTool { - campaign, - cover, - all_public_events, - current_anchors, - discovered: BTreeMap::new(), - responder_views, - }; - let initial_events = tool - .all_public_events - .iter() - .copied() - .take(INITIAL_EVENT_WINDOW) - .collect::>(); - let initial_event_anchors = - tool.discover_events(initial_events) - .map_err(|error| crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts: Vec::new(), - })?; - let initial_current_anchors = - tool.inspect_current_anchor_page(0) - .map_err(|error| crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts: Vec::new(), - })?; - if tool.discovered.is_empty() { - return Ok(None); - } - let snapshot_binding = causal_follow_through_snapshot(campaign, cover).map_err(|error| { - crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts: Vec::new(), - } - })?; - let instructions = format!( - "You are Nemesis, Ghostlight's causal attention agent. Select who receives a decision window because committed world pressure now demands an answer. You never decide their action or its outcome. Bind only exact inspected anchors to exact eligible autonomous responders. Prefer consequential acts, declared crises, active pressure, public humiliation, material loss, contested authority, and promises whose costs should now land. When one public detonation creates incompatible stakes, assign distinct rival responders to the same anchor so their independent Persona cells can make competing countermoves. Do not assign the player. Do not assign one subject twice. Stay within the cover quotas. Inspect a chosen anchor's eligible responders before assigning it. You may page through current pressure/clocks, older world history, one subject's perceived history, or one anchor's eligible responders; the committed ledger is not limited to the initial viewport. An empty assignment list is a valid judgment when nothing currently warrants a response window. Submit the smallest agenda likely to produce genuine causal follow-through. The deterministic tool alone admits it.\n\nCOVER SUMMARY:\n{}\n\nINITIAL RECENT PUBLIC ANCHORS:\n{}\n\nINITIAL CURRENT PRESSURE/CLOCK PAGE:\n{}", - serde_json::json!({ - "cell_count":cover.cells.len(), - "eligible_responder_count":tool.responder_views.len(), - "maximum_decision_slots":cover.cells.iter().map(cell_action_limit).sum::(), - }), - serde_json::to_string(&initial_event_anchors).unwrap_or_default(), - serde_json::to_string(&initial_current_anchors).unwrap_or_default(), - ); - let spec = ModelAgentSpec { - stage: NEMESIS_STAGE.into(), - model: MODEL_BALANCED.into(), - snapshot_binding, - instructions, - source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), - temperature: Some(0.15), - max_output_tokens: Some(2_400), - max_steps: MAX_FOLLOW_THROUGH_STEPS, - }; - let run = crate::agent::run_model_agent(model, &spec, &mut tool).await?; - Ok(Some(CausalFollowThroughProposal { - admission: run.output, - receipts: run.receipts, - })) -} - -pub fn validate_causal_follow_through(campaign: &Campaign, cover: &ResolutionCover) -> Result<()> { - if cover.causal_follow_through.is_empty() { - return Ok(()); - } - let responder_views = responder_views(campaign, cover); - let mut catalog = current_anchor_candidates(campaign, cover, &responder_views) - .into_iter() - .map(|candidate| (candidate.anchor_reference.clone(), candidate)) - .collect::>(); - for event in campaign - .events - .iter() - .filter(|event| !event.public_channels.is_empty()) - { - let candidate = event_anchor_candidate(campaign, cover, event, &responder_views)?; - catalog.insert(candidate.anchor_reference.clone(), candidate); - } - let tool = CausalFollowThroughTool { - campaign, - cover, - all_public_events: Vec::new(), - current_anchors: Vec::new(), - discovered: catalog, - responder_views, - }; - let drafts = cover - .causal_follow_through - .iter() - .map(|assignment| CausalAssignmentDraft { - anchor_reference: assignment.anchor_reference.clone(), - responder_subject_id: assignment.responder_subject_id.clone(), - }) - .collect::>(); - let rebound = tool.validate_and_bind(drafts)?; - if rebound != cover.causal_follow_through { - return Err(anyhow!( - "causal follow-through agenda is not canonically ordered" - )); - } - Ok(()) -} - -pub fn causal_anchor_summary(campaign: &Campaign, anchor_reference: &str) -> Option { - if let Some(event_id) = anchor_reference.strip_prefix("event:") { - return campaign - .events - .iter() - .find(|event| event.id == event_id) - .map(|event| event.summary.clone()); - } - for gestalt in campaign.gestalts.values() { - for pressure in &gestalt.pressures { - if pressure_anchor_reference(&gestalt.id, pressure) == anchor_reference { - return Some(format!( - "Current unresolved pressure on {}: {pressure}", - gestalt.name - )); - } - } - } - for clock in campaign.clocks.values() { - if clock_anchor_reference(&clock.id, clock.progress) == anchor_reference { - return Some(format!( - "{} is at {}/{}; declared consequence: {}", - clock.label, clock.progress, clock.threshold, clock.consequence - )); - } - } - None -} - -pub fn responder_cell<'a>( - campaign: &Campaign, - cover: &'a ResolutionCover, - responder_subject_id: &str, -) -> Option<&'a SimulationCell> { - let owning_subject = responder_subject_id - .strip_prefix("member:") - .and_then(|member_id| campaign.gestalt_members.get(member_id)) - .and_then(|member| { - member - .materialized_actor_id - .is_none() - .then_some(member.gestalt_id.as_str()) - }) - .unwrap_or(responder_subject_id); - cover - .cells - .iter() - .find(|cell| cell.subject_ids.contains(owning_subject)) -} - -pub fn assignments_for_cell<'a>( - campaign: &Campaign, - cover: &'a ResolutionCover, - cell: &SimulationCell, -) -> Vec<&'a CausalFollowThroughAssignment> { - cover - .causal_follow_through - .iter() - .filter(|assignment| { - responder_cell(campaign, cover, &assignment.responder_subject_id) - .is_some_and(|owner| owner.id == cell.id) - }) - .collect() -} - -pub fn causal_follow_through_snapshot( - campaign: &Campaign, - cover: &ResolutionCover, -) -> Result { - crate::legacy_transition::digest_serializable(&serde_json::json!({ - "campaign_id":campaign.id, - "world_revision":campaign.revision, - "resolution_epoch":campaign.resolution_policy.resolution_epoch, - "events":campaign.events, - "clocks":campaign.clocks, - "gestalt_pressures":campaign.gestalts.iter().map(|(id, gestalt)| (id, &gestalt.pressures)).collect::>(), - "agency_profiles":campaign.agency_profiles, - "agency_relations":campaign.agency_relations, - "nemesis_attention_history":campaign.nemesis_attention_history, - "cells":cover.cells, - "demand":cover.demand, - })) -} - -pub fn causal_assignment_batch_digest( - assignments: &[CausalFollowThroughAssignment], -) -> Result { - crate::legacy_transition::digest_serializable(&serde_json::json!({ - "schema":"ghostlight.causal_follow_through_assignment_batch.v1", - "assignments":assignments, - })) -} - -pub fn nemesis_admission_binding(campaign: &Campaign, cover: &ResolutionCover) -> Result { - Ok(format!( - "{}:causal-agenda:{}", - causal_follow_through_snapshot(campaign, cover)?, - causal_assignment_batch_digest(&cover.causal_follow_through)? - )) -} - -fn constrain_action_schema( - schema: &mut serde_json::Value, - anchors: Vec, - responders: Vec, -) -> Result<()> { - let text = serde_json::to_string(schema)?; - let mut value: serde_json::Value = serde_json::from_str(&text)?; - replace_property_schema( - &mut value, - "anchor_reference", - serde_json::json!({"type":"string","enum":anchors}), - ); - replace_property_schema( - &mut value, - "responder_subject_id", - serde_json::json!({"type":"string","enum":responders}), - ); - *schema = value; - Ok(()) -} - -fn replace_property_schema( - value: &mut serde_json::Value, - name: &str, - replacement: serde_json::Value, -) { - match value { - serde_json::Value::Object(object) => { - if let Some(properties) = object - .get_mut("properties") - .and_then(serde_json::Value::as_object_mut) - && properties.contains_key(name) - { - properties.insert(name.into(), replacement.clone()); - } - for child in object.values_mut() { - replace_property_schema(child, name, replacement.clone()); - } - } - serde_json::Value::Array(values) => { - for child in values { - replace_property_schema(child, name, replacement.clone()); - } - } - _ => {} - } -} - -fn responder_views( - campaign: &Campaign, - cover: &ResolutionCover, -) -> BTreeMap { - let mut views = BTreeMap::new(); - for profile in campaign - .agency_profiles - .values() - .filter(|profile| profile.active_leaf && profile.simulation_eligible) - .filter(|profile| profile.subject_id != campaign.player_actor_id) - { - let Some(cell) = responder_cell(campaign, cover, &profile.subject_id) else { - continue; - }; - views.insert( - profile.subject_id.clone(), - CausalResponderView { - subject_id: profile.subject_id.clone(), - name: subject_name(campaign, &profile.subject_id), - subject_kind: format!("{:?}", profile.subject_kind), - stakes: subject_stakes(campaign, &profile.subject_id), - cell_id: cell.id.clone(), - cell_decision_slot_limit: cell_action_limit(cell), - }, - ); - } - for member in campaign - .gestalt_members - .values() - .filter(|member| member.materialized_actor_id.is_none()) - { - let subject_id = crate::domain::gestalt_member_subject_id(&member.id); - let Some(cell) = responder_cell(campaign, cover, &subject_id) else { - continue; - }; - if campaign - .agency_profiles - .get(&member.gestalt_id) - .is_some_and(|profile| profile.simulation_eligible) - { - views.insert( - subject_id.clone(), - CausalResponderView { - subject_id, - name: member.name.clone(), - subject_kind: "GestaltMember".into(), - stakes: member - .goals - .iter() - .chain(&member.obligations) - .chain(&member.conditions) - .cloned() - .collect(), - cell_id: cell.id.clone(), - cell_decision_slot_limit: cell_action_limit(cell), - }, - ); - } - } - views -} - -fn event_anchor_candidate( - campaign: &Campaign, - _cover: &ResolutionCover, - event: &Event, - responder_views: &BTreeMap, -) -> Result { - let eligible_responder_ids = responder_views - .keys() - .filter(|subject_id| { - subject_perceives_event(campaign, subject_id, event) - && !nemesis_already_served(campaign, &format!("event:{}", event.id), subject_id) - }) - .cloned() - .collect::>(); - let mut originating_subject_ids = event - .actor_ids - .iter() - .chain(&event.institution_ids) - .chain(&event.gestalt_ids) - .cloned() - .collect::>(); - originating_subject_ids.sort(); - originating_subject_ids.dedup(); - Ok(CausalAnchorCandidate { - anchor_reference: format!("event:{}", event.id), - kind: event.kind.clone(), - account: event.summary.clone(), - originating_subject_ids, - eligible_responder_ids, - }) -} - -fn current_anchor_candidates( - campaign: &Campaign, - _cover: &ResolutionCover, - responder_views: &BTreeMap, -) -> Vec { - let mut anchors = Vec::new(); - for gestalt in campaign.gestalts.values() { - for pressure in &gestalt.pressures { - let eligible_responder_ids = responder_views - .keys() - .filter(|subject_id| { - (subject_id.as_str() == gestalt.id - || subject_id - .strip_prefix("member:") - .and_then(|member_id| campaign.gestalt_members.get(member_id)) - .is_some_and(|member| member.gestalt_id == gestalt.id)) - && !nemesis_already_served( - campaign, - &pressure_anchor_reference(&gestalt.id, pressure), - subject_id, - ) - }) - .cloned() - .collect::>(); - if eligible_responder_ids.is_empty() { - continue; - } - anchors.push(CausalAnchorCandidate { - anchor_reference: pressure_anchor_reference(&gestalt.id, pressure), - kind: "gestalt_pressure".into(), - account: format!( - "Current unresolved pressure on {}: {pressure}", - gestalt.name - ), - originating_subject_ids: vec![gestalt.id.clone()], - eligible_responder_ids, - }); - } - } - for clock in campaign.clocks.values().filter(|clock| clock.progress > 0) { - let synthetic = Event { - id: format!("clock:projection:{}", clock.id), - at: campaign.world_time, - kind: "world_clock".into(), - summary: clock.consequence.clone(), - 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(), - }; - let eligible_responder_ids = responder_views - .keys() - .filter(|subject_id| { - subject_perceives_event(campaign, subject_id, &synthetic) - && !nemesis_already_served( - campaign, - &clock_anchor_reference(&clock.id, clock.progress), - subject_id, - ) - }) - .cloned() - .collect::>(); - if eligible_responder_ids.is_empty() { - continue; - } - anchors.push(CausalAnchorCandidate { - anchor_reference: clock_anchor_reference(&clock.id, clock.progress), - kind: "world_clock".into(), - account: format!( - "{} is at {}/{}; declared consequence: {}", - clock.label, clock.progress, clock.threshold, clock.consequence - ), - originating_subject_ids: Vec::new(), - eligible_responder_ids, - }); - } - anchors -} - -fn pressure_anchor_reference(gestalt_id: &str, pressure: &str) -> String { - let digest = format!( - "{:x}", - Sha256::digest(format!("{gestalt_id}\0{pressure}").as_bytes()) - ); - format!("pressure:{gestalt_id}:{}", &digest[..16]) -} - -fn clock_anchor_reference(clock_id: &str, progress: u8) -> String { - format!("clock:{clock_id}:progress:{progress}") -} - -fn nemesis_already_served(campaign: &Campaign, anchor: &str, responder: &str) -> bool { - campaign - .nemesis_attention_history - .iter() - .any(|record| record.anchor_reference == anchor && record.responder_subject_id == responder) -} - -fn subject_perceives_event(campaign: &Campaign, subject_id: &str, event: &Event) -> bool { - if event.actor_ids.iter().any(|id| id == subject_id) - || event.institution_ids.iter().any(|id| id == subject_id) - || event.gestalt_ids.iter().any(|id| id == subject_id) - { - return true; - } - if let Some(member_id) = subject_id.strip_prefix("member:") - && let Some(member) = campaign.gestalt_members.get(member_id) - && let Some(gestalt) = campaign.gestalts.get(&member.gestalt_id) - { - let location = member - .last_location_id - .as_deref() - .unwrap_or(&gestalt.home_location_id); - let channels = campaign - .agency_profiles - .get(&member.gestalt_id) - .map(|profile| &profile.information_channels); - return event.location_ids.iter().any(|id| id == location) - || channels.is_some_and(|channels| { - event - .public_channels - .iter() - .any(|channel| channels.contains(channel)) - }); - } - let Some(profile) = campaign.agency_profiles.get(subject_id) else { - return false; - }; - event - .location_ids - .iter() - .any(|location| profile.location_ids.contains(location)) - || event - .public_channels - .iter() - .any(|channel| profile.information_channels.contains(channel)) -} - -fn subject_name(campaign: &Campaign, subject_id: &str) -> String { - campaign - .actors - .get(subject_id) - .map(|actor| actor.name.clone()) - .or_else(|| { - campaign - .institutions - .get(subject_id) - .map(|institution| institution.name.clone()) - }) - .or_else(|| { - campaign - .gestalts - .get(subject_id) - .map(|gestalt| gestalt.name.clone()) - }) - .or_else(|| { - subject_id - .strip_prefix("member:") - .and_then(|member_id| campaign.gestalt_members.get(member_id)) - .map(|member| member.name.clone()) - }) - .unwrap_or_else(|| subject_id.into()) -} - -fn subject_stakes(campaign: &Campaign, subject_id: &str) -> Vec { - if let Some(actor) = campaign.actors.get(subject_id) { - return actor - .goals - .iter() - .chain(&actor.obligations) - .chain(&actor.conditions) - .cloned() - .collect(); - } - if let Some(institution) = campaign.institutions.get(subject_id) { - return institution - .goals - .iter() - .cloned() - .chain(std::iter::once(institution.posture.clone())) - .collect(); - } - if let Some(gestalt) = campaign.gestalts.get(subject_id) { - return gestalt - .goals - .iter() - .chain(&gestalt.pressures) - .cloned() - .collect(); - } - Vec::new() -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - domain::{ActorState, Event, GestaltMemberDelta}, - model::ModelStageRequest, - resolution::{default_demand, ensure_agency_profiles, plan_cover}, - }; - use anyhow::Result; - use async_trait::async_trait; - use std::collections::{BTreeMap, BTreeSet, VecDeque}; - use std::sync::Mutex; - - struct ScriptedModel { - responses: Mutex>, - requests: Mutex>, - } - - #[async_trait] - impl ModelPort for ScriptedModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.requests.lock().unwrap().push(request.clone()); - self.responses - .lock() - .unwrap() - .pop_front() - .ok_or_else(|| anyhow!("follow-through fixture exhausted")) - } - - fn provider(&self) -> &'static str { - "follow-through-fixture" - } - } - - fn campaign_and_cover() -> (Campaign, ResolutionCover) { - let mut campaign = crate::kernel::tests::campaign(); - campaign.actors.insert( - "npc".into(), - ActorState { - id: "npc".into(), - name: "Nara Venn".into(), - location_id: "room".into(), - capabilities: BTreeSet::from(["publish a reply".into()]), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::from(["answer public accusations".into()]), - relationships: BTreeMap::new(), - goals: vec!["retain the ward's confidence".into()], - memories: Vec::new(), - }, - ); - ensure_agency_profiles(&mut campaign); - campaign - .agency_profiles - .get_mut("npc") - .unwrap() - .information_channels - .insert("ward broadsheet".into()); - campaign.resolution_policy.active_cell_budget = 1; - campaign.events.push(Event { - id: "old".into(), - at: campaign.world_time, - kind: "institution_action".into(), - summary: "The Thorn Bench accuses Nara Venn of hiding the winter tally.".into(), - actor_ids: Vec::new(), - institution_ids: Vec::new(), - gestalt_ids: Vec::new(), - location_ids: vec!["room".into()], - public_channels: vec!["ward broadsheet".into()], - }); - for index in 0..29 { - campaign.events.push(Event { - id: format!("new-{index:02}"), - at: campaign.world_time, - kind: "public_notice".into(), - summary: format!("Routine notice {index} is posted in the ward."), - actor_ids: Vec::new(), - institution_ids: Vec::new(), - gestalt_ids: Vec::new(), - location_ids: vec!["room".into()], - public_channels: vec!["ward broadsheet".into()], - }); - } - let cover = plan_cover( - &campaign, - default_demand(&campaign, "exercise full committed history"), - ) - .unwrap(); - (campaign, cover) - } - - #[tokio::test] - async fn nemesis_can_retrieve_and_bind_an_anchor_beyond_the_initial_viewport() { - let (campaign, cover) = campaign_and_cover(); - let model = ScriptedModel { - responses: Mutex::new(VecDeque::from([ - serde_json::json!({ - "command":{ - "kind":"inspect_world_history", - "cursor":24 - } - }) - .to_string(), - serde_json::json!({ - "command":{ - "kind":"inspect_anchor_responders", - "anchor_reference":"event:old", - "cursor":0 - } - }) - .to_string(), - serde_json::json!({ - "command":{ - "kind":"submit", - "assignments":[{ - "anchor_reference":"event:old", - "responder_subject_id":"npc" - }] - } - }) - .to_string(), - ])), - requests: Mutex::new(Vec::new()), - }; - - let proposal = propose_causal_follow_through(&model, &campaign, &cover) - .await - .unwrap() - .unwrap(); - assert_eq!( - proposal.admission.assignments, - [CausalFollowThroughAssignment { - anchor_reference: "event:old".into(), - responder_subject_id: "npc".into(), - }] - ); - assert_eq!(proposal.receipts.len(), 4); - assert!( - proposal.receipts[1] - .source_receipt_ids - .contains(&proposal.receipts[0].storage_key().to_owned()) - ); - assert!( - proposal - .receipts - .last() - .unwrap() - .snapshot_binding - .contains("causal-agenda") - ); - let requests = model.requests.lock().unwrap(); - assert!(requests[1].lived_stream.contains("event:old")); - assert!(requests[1].lived_stream.contains("next_cursor")); - assert!(requests[2].lived_stream.contains("Nara Venn")); - assert!( - requests[2] - .lived_stream - .contains("cell_decision_slot_limit") - ); - } - - #[test] - fn admitted_agenda_is_scheduler_only_and_excludes_the_player() { - let (campaign, mut cover) = campaign_and_cover(); - cover.causal_follow_through = vec![CausalFollowThroughAssignment { - anchor_reference: "event:old".into(), - responder_subject_id: "npc".into(), - }]; - validate_causal_follow_through(&campaign, &cover).unwrap(); - let cell = responder_cell(&campaign, &cover, "npc").unwrap(); - assert_eq!(assignments_for_cell(&campaign, &cover, cell).len(), 1); - assert_eq!( - causal_anchor_summary(&campaign, "event:old").as_deref(), - Some("The Thorn Bench accuses Nara Venn of hiding the winter tally.") - ); - - cover.causal_follow_through[0].responder_subject_id = "player".into(); - assert!(validate_causal_follow_through(&campaign, &cover).is_err()); - } - - #[test] - fn materialized_member_responders_use_their_actor_cell() { - let (mut campaign, mut cover) = campaign_and_cover(); - let member = |id: &str, materialized_actor_id: Option<&str>| GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: id.into(), - gestalt_id: "household".into(), - version: 0, - name: id.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::new(), - memories: Vec::new(), - last_location_id: Some("room".into()), - materialized_actor_id: materialized_actor_id.map(str::to_owned), - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }; - campaign - .gestalt_members - .insert("awake".into(), member("awake", Some("member:awake"))); - campaign - .gestalt_members - .insert("folded".into(), member("folded", None)); - - let mut actor_cell = cover.cells[0].clone(); - actor_cell.id = "actor-cell".into(); - actor_cell.subject_ids = BTreeSet::from(["member:awake".into()]); - let mut gestalt_cell = cover.cells[0].clone(); - gestalt_cell.id = "gestalt-cell".into(); - gestalt_cell.subject_ids = BTreeSet::from(["household".into()]); - cover.cells = vec![actor_cell, gestalt_cell]; - - assert_eq!( - responder_cell(&campaign, &cover, "member:awake").map(|cell| cell.id.as_str()), - Some("actor-cell") - ); - assert_eq!( - responder_cell(&campaign, &cover, "member:folded").map(|cell| cell.id.as_str()), - Some("gestalt-cell") - ); - } - - #[tokio::test] - async fn nemesis_may_decide_that_no_subject_needs_attention_now() { - let (campaign, cover) = campaign_and_cover(); - let model = ScriptedModel { - responses: Mutex::new(VecDeque::from([serde_json::json!({ - "command":{"kind":"submit","assignments":[]} - }) - .to_string()])), - requests: Mutex::new(Vec::new()), - }; - - let proposal = propose_causal_follow_through(&model, &campaign, &cover) - .await - .unwrap() - .unwrap(); - assert!(proposal.admission.assignments.is_empty()); - assert_eq!(proposal.receipts.len(), 2); - assert!( - proposal - .receipts - .last() - .unwrap() - .snapshot_binding - .contains("causal-agenda") - ); - } - - #[tokio::test] - async fn nemesis_initial_frame_does_not_multiply_anchors_by_responders() { - let (mut campaign, mut cover) = campaign_and_cover(); - for index in 0..2_400 { - let id = format!("scale-actor-{index:03}"); - let mut actor = campaign.actors["npc"].clone(); - actor.id = id.clone(); - actor.name = format!("Scale Actor {index:03}"); - actor.goals = vec![format!( - "preserve constituency {index:03} through the current dispute" - )]; - actor.obligations = BTreeSet::from([format!( - "answer pressure {index:03} without abandoning the ward" - )]); - campaign.actors.insert(id.clone(), actor); - let mut profile = campaign.agency_profiles["npc"].clone(); - profile.id = format!("agency:{id}"); - profile.subject_id = id.clone(); - campaign.agency_profiles.insert(id.clone(), profile); - cover.cells[0].subject_ids.insert(id); - } - let model = ScriptedModel { - responses: Mutex::new(VecDeque::from([serde_json::json!({ - "command":{"kind":"submit","assignments":[]} - }) - .to_string()])), - requests: Mutex::new(Vec::new()), - }; - - propose_causal_follow_through(&model, &campaign, &cover) - .await - .unwrap() - .unwrap(); - - let requests = model.requests.lock().unwrap(); - let request = &requests[0]; - let frame_chars = request.lived_stream.chars().count() - + serde_json::to_string(&request.output_schema) - .unwrap() - .chars() - .count(); - assert!(request.lived_stream.contains("eligible_responder_count")); - assert!(request.lived_stream.contains("next_cursor")); - assert!(!request.lived_stream.contains("Scale Actor 2399")); - assert!( - frame_chars < 500_000, - "bounded Nemesis frame grew to {frame_chars} characters" - ); - } - - #[test] - fn current_pressure_projection_is_paged_without_losing_candidates() { - let (campaign, cover) = campaign_and_cover(); - let responders = responder_views(&campaign, &cover); - let current_anchors = (0..30) - .map(|index| CausalAnchorCandidate { - anchor_reference: format!("pressure:test:{index:02}"), - kind: "gestalt_pressure".into(), - account: format!("Pressure {index:02} remains unresolved."), - originating_subject_ids: vec!["npc".into()], - eligible_responder_ids: responders.keys().cloned().collect(), - }) - .collect(); - let mut tool = CausalFollowThroughTool { - campaign: &campaign, - cover: &cover, - all_public_events: Vec::new(), - current_anchors, - discovered: BTreeMap::new(), - responder_views: responders, - }; - - let CausalFollowThroughFinding::HistoryPage { - anchors, - next_cursor, - .. - } = tool.inspect_current_anchor_page(0).unwrap() - else { - panic!("current anchors returned the wrong workbench view") - }; - assert_eq!(anchors.len(), CURRENT_ANCHOR_PAGE_SIZE); - assert_eq!(next_cursor, Some(CURRENT_ANCHOR_PAGE_SIZE)); - assert_eq!(tool.discovered.len(), CURRENT_ANCHOR_PAGE_SIZE); - - let CausalFollowThroughFinding::HistoryPage { - anchors, - next_cursor, - .. - } = tool - .inspect_current_anchor_page(CURRENT_ANCHOR_PAGE_SIZE) - .unwrap() - else { - panic!("current anchors returned the wrong workbench view") - }; - assert_eq!(anchors.len(), 6); - assert_eq!(next_cursor, None); - assert_eq!(tool.discovered.len(), 30); - } - - #[test] - fn a_served_anchor_responder_pair_cannot_be_scheduled_again() { - let (mut campaign, mut cover) = campaign_and_cover(); - campaign - .nemesis_attention_history - .push(crate::domain::NemesisAttentionRecord { - anchor_reference: "event:old".into(), - responder_subject_id: "npc".into(), - served_world_revision: campaign.revision, - }); - cover.causal_follow_through = vec![CausalFollowThroughAssignment { - anchor_reference: "event:old".into(), - responder_subject_id: "npc".into(), - }]; - - let error = validate_causal_follow_through(&campaign, &cover).unwrap_err(); - assert!(error.to_string().contains("cannot perceive or own")); - } -} diff --git a/crates/ghostlight-dungeon/src/gestalt.rs b/crates/ghostlight-dungeon/src/gestalt.rs deleted file mode 100644 index 7eb3e05..0000000 --- a/crates/ghostlight-dungeon/src/gestalt.rs +++ /dev/null @@ -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, - pub model_name: String, -} - -impl GestaltPresencePlanner { - pub async fn plan( - &self, - campaign: &Campaign, - event_summary: &str, - ) -> Result<(GestaltPresencePlan, Vec)> { - 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::>(); - let nearby_gestalt_ids = nearby_gestalts - .iter() - .map(|gestalt| gestalt.id.clone()) - .collect::>(); - 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::>(); - 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::>(); - 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::>(), - "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::>(); - let materialized_actor_ids = campaign - .gestalt_members - .values() - .filter_map(|member| member.materialized_actor_id.clone()) - .collect::>(); - 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 { - 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, - dormant_member_ids: &BTreeSet, - materialized_actor_ids: &BTreeSet, - 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, -) -> 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::>(); - 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::>(); - 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 { - 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 { - 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>, - } - - struct CorrectingPresenceModel { - calls: AtomicUsize, - } - - #[async_trait] - impl ModelPort for CapturePresenceModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - *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 { - 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")); - } -} diff --git a/crates/ghostlight-dungeon/src/heimdall.rs b/crates/ghostlight-dungeon/src/heimdall.rs index 9798d76..99fdd12 100644 --- a/crates/ghostlight-dungeon/src/heimdall.rs +++ b/crates/ghostlight-dungeon/src/heimdall.rs @@ -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, } #[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct AuthCompletionReceipt { pub status: String, pub handle: Option, @@ -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, + access_expires_at: DateTime, + refresh_expires_at: DateTime, + 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 { + self.0.access_expires_at.to_owned() + } + + pub(crate) fn refresh_expires_at(&self) -> DateTime { + 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, + heimdall_session_id: impl Into, + access_revision: u64, + access_expires_at: DateTime, + refresh_expires_at: DateTime, + refresh_claim: impl Into, + ) -> 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 { 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 { + completion: AuthCompletionReceipt, + ) -> anyhow::Result { 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 { + completion: AuthCompletionReceipt, + ) -> anyhow::Result { 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 { @@ -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 { + 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 = 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 = 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")) diff --git a/crates/ghostlight-dungeon/src/idunn_health.rs b/crates/ghostlight-dungeon/src/idunn_health.rs index dd61f84..240efcd 100644 --- a/crates/ghostlight-dungeon/src/idunn_health.rs +++ b/crates/ghostlight-dungeon/src/idunn_health.rs @@ -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 { + #[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 { + 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 { + #[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, private_state_exposed: bool, + activation_witness_sha256: Option, } 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, + 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, source_runtime_id: impl Into, health_contract: impl Into, identity_store: impl AsRef, + release: IdunnReleaseBinding, + activation: IdunnActivationBinding, ) -> Result { 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::( 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 { 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 { 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 { + 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::>(); + 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 { + 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 { + 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 { + 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 { + 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::>(); + 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::() + .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 { + #[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::>(); + 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::() + .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> { + #[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> { 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::(&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() + ); } } diff --git a/crates/ghostlight-dungeon/src/initiative.rs b/crates/ghostlight-dungeon/src/initiative.rs deleted file mode 100644 index e2da2d1..0000000 --- a/crates/ghostlight-dungeon/src/initiative.rs +++ /dev/null @@ -1,35 +0,0 @@ -use crate::domain::WorldActionProposal; - -pub fn winner(proposals: &[WorldActionProposal]) -> Option { - 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"); - } -} diff --git a/crates/ghostlight-dungeon/src/kernel.rs b/crates/ghostlight-dungeon/src/kernel.rs deleted file mode 100644 index dcccae0..0000000 --- a/crates/ghostlight-dungeon/src/kernel.rs +++ /dev/null @@ -1,10950 +0,0 @@ -use crate::d20::{capped_modifier, receipt}; -use crate::domain::*; -use crate::persistence::CampaignStore; -use crate::session_zero::{ - CampaignMembership, CellBudgetProposal, GroupTravelProposal, TimeAdvanceProposal, -}; -use chrono::{Duration, Utc}; -use rand::Rng; -use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; -use thiserror::Error; -use tokio::sync::{mpsc, oneshot}; - -const GESTALT_RELEVANCE_LEASE_REVISIONS: u64 = 2; - -#[derive(Debug, Error)] -pub enum KernelError { - #[error("campaign not found")] - NotFound, - #[error("stale revision: expected {expected}, actual {actual}")] - Stale { expected: u64, actual: u64 }, - #[error("action is impossible: {0}")] - Impossible(String), - #[error("assessment is unknown")] - UnknownAssessment, - #[error("assessment is stale at campaign revision {actual_revision}")] - StaleAssessment { - intent: ActionIntent, - actual_revision: u64, - }, - #[error("invalid command: {0}")] - Invalid(String), - #[error("persistence failure: {0}")] - Persistence(String), -} - -#[derive(Clone, Debug, serde::Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum CommandResult { - Created { - campaign: Campaign, - }, - Assessed { - assessment: ActionAssessment, - }, - Committed { - campaign: Campaign, - receipt: WorldCommitReceipt, - }, - ExternalSnapshotCommitted { - campaign: Campaign, - receipt: crate::consumer::ExternalSnapshotReceipt, - }, - ResolutionUpdated { - campaign: Campaign, - receipt: ResolutionControlReceipt, - }, - GovernancePending { - campaign: Campaign, - proposal: TimeAdvanceProposal, - }, - TravelGovernancePending { - campaign: Campaign, - proposal: GroupTravelProposal, - }, - ResolutionGovernancePending { - campaign: Campaign, - proposal: CellBudgetProposal, - }, - MutationCommitted { - state: crate::transition::ComponentWorldState, - receipt: crate::transition::WorldMutationReceipt, - }, -} - -enum KernelInput { - World(WorldCommand), -} - -struct Request { - input: KernelInput, - reply: oneshot::Sender>, -} - -#[derive(Clone)] -pub struct WorldKernel { - tx: mpsc::Sender, -} - -impl WorldKernel { - pub(crate) fn initialize_campaign( - store: &CampaignStore, - command: WorldCommand, - ) -> Result { - if !matches!(command, WorldCommand::CreateCampaign { .. }) { - return Err(KernelError::Invalid( - "campaign initialization accepts only CreateCampaign".into(), - )); - } - execute(store, &mut BTreeMap::new(), command) - } - - pub fn start(store: CampaignStore) -> Self { - let (tx, mut rx) = mpsc::channel::(64); - tokio::spawn(async move { - let mut assessments = BTreeMap::new(); - while let Some(request) = rx.recv().await { - let result = match request.input { - KernelInput::World(command) => execute(&store, &mut assessments, command), - }; - let _ = request.reply.send(result); - } - }); - Self { tx } - } - pub async fn command(&self, command: WorldCommand) -> Result { - let (reply, receive) = oneshot::channel(); - self.tx - .send(Request { - input: KernelInput::World(command), - reply, - }) - .await - .map_err(|_| KernelError::Invalid("kernel stopped".into()))?; - receive - .await - .map_err(|_| KernelError::Invalid("kernel stopped".into()))? - } -} - -fn execute( - store: &CampaignStore, - assessments: &mut BTreeMap, - command: WorldCommand, -) -> Result { - if let WorldCommand::CreateCampaign { - mut campaign, - evidence_receipts, - model_stage_receipts, - } = command - { - if !store.keys("campaign.v1").map_err(persist)?.is_empty() { - return Err(KernelError::Invalid("campaign already exists".into())); - } - crate::resolution::ensure_agency_profiles(&mut campaign); - crate::compiler::validate_campaign_seed(&campaign) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - store - .create_unadmitted_fixture_campaign( - &campaign, - &evidence_receipts, - &model_stage_receipts, - ) - .map_err(persist)?; - return Ok(CommandResult::Created { campaign }); - } - let campaign_id = single_campaign_id(store)?; - let (row, mut campaign): (_, Campaign) = store - .load("campaign.v1", &campaign_id) - .map_err(persist)? - .ok_or(KernelError::NotFound)?; - match command { - WorldCommand::ApplyExternalSubjectSnapshot { snapshot } => { - if snapshot.schema != "ghostlight.external_subject_snapshot.v1" - || snapshot.campaign_id != campaign.id - { - return Err(KernelError::Invalid( - "external snapshot targets another campaign".into(), - )); - } - let receipt_key = format!("{}:{}", snapshot.authority_id, snapshot.source_revision); - if let Some((_, receipt)) = store - .load::( - "external_snapshot_receipt.v1", - &receipt_key, - ) - .map_err(persist)? - { - return if receipt.payload_digest == snapshot.payload_digest - && receipt.owner_id == snapshot.owner_id - { - Ok(CommandResult::ExternalSnapshotCommitted { campaign, receipt }) - } else { - Err(KernelError::Invalid( - "external snapshot idempotency conflict".into(), - )) - }; - } - let (authority_row, authority) = store - .load::( - "external_subject_authority.v1", - &snapshot.authority_id, - ) - .map_err(persist)? - .ok_or_else(|| { - KernelError::Invalid("external subject authority is unknown".into()) - })?; - if authority.campaign_id != snapshot.campaign_id - || authority.owner_id != snapshot.owner_id - || authority.subject_id != snapshot.projection.subject_id() - || authority.subject_kind != snapshot.projection.subject_kind() - { - return Err(KernelError::Invalid( - "external snapshot does not match its authority".into(), - )); - } - crate::consumer::validate_authority_key(&authority, &snapshot.authority_key) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let actual_digest = crate::consumer::snapshot_payload_digest(&snapshot) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - if actual_digest != snapshot.payload_digest { - return Err(KernelError::Invalid( - "external snapshot payload digest is invalid".into(), - )); - } - if authority - .last_source_revision - .is_some_and(|revision| snapshot.source_revision <= revision) - { - return Err(KernelError::Invalid( - "external snapshot source revision is stale".into(), - )); - } - require_revision(&campaign, snapshot.expected_world_revision)?; - let subject_id = snapshot.projection.subject_id().to_owned(); - let mut institution_ids = Vec::new(); - let mut gestalt_ids = Vec::new(); - match &snapshot.projection { - crate::consumer::ExternalSubjectProjection::Institution(value) => { - campaign - .institutions - .insert(value.id.clone(), value.clone()); - institution_ids.push(value.id.clone()); - if let Some(profile) = campaign.agency_profiles.get_mut(&value.id) { - profile.facets.insert( - AgencyAxis::Authority, - BTreeSet::from([value.id.clone(), value.posture.clone()]), - ); - profile.facets.insert( - AgencyAxis::EconomyRole, - value.resources.iter().cloned().collect(), - ); - } - } - crate::consumer::ExternalSubjectProjection::Gestalt(value) => { - campaign.gestalts.insert(value.id.clone(), value.clone()); - gestalt_ids.push(value.id.clone()); - if let Some(profile) = campaign.agency_profiles.get_mut(&value.id) { - profile.location_ids = BTreeSet::from([value.home_location_id.clone()]); - profile.facets.insert( - AgencyAxis::Geography, - BTreeSet::from([value.home_location_id.clone()]), - ); - profile.facets.insert( - AgencyAxis::EconomyRole, - value.shared_capabilities.iter().cloned().collect(), - ); - profile.facets.insert( - AgencyAxis::Information, - value.shared_knowledge.iter().cloned().collect(), - ); - } - } - } - crate::compiler::validate_campaign_runtime(&campaign) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let previous_world_revision = campaign.revision; - campaign.revision = campaign.revision.saturating_add(1); - let now = Utc::now(); - campaign.events.push(Event { - id: format!( - "external-snapshot:{}:{}", - snapshot.authority_id, snapshot.source_revision - ), - at: now, - kind: "external_subject_snapshot".into(), - summary: format!( - "{} supplied an authoritative external subject snapshot.", - snapshot.owner_id - ), - actor_ids: Vec::new(), - institution_ids, - gestalt_ids, - location_ids: Vec::new(), - public_channels: Vec::new(), - }); - let mut next_authority = authority; - next_authority.last_source_revision = Some(snapshot.source_revision); - next_authority.last_payload_digest = Some(snapshot.payload_digest.clone()); - let receipt = crate::consumer::ExternalSnapshotReceipt { - schema: "ghostlight.external_snapshot_receipt.v1".into(), - id: receipt_key, - campaign_id: snapshot.campaign_id, - authority_id: snapshot.authority_id, - subject_id, - owner_id: snapshot.owner_id, - source_revision: snapshot.source_revision, - payload_digest: snapshot.payload_digest, - previous_world_revision, - world_revision: campaign.revision, - committed_at: now, - }; - store - .append_external_snapshot( - &row, - &authority_row, - &campaign, - &next_authority, - &receipt, - ) - .map_err(persist)?; - Ok(CommandResult::ExternalSnapshotCommitted { campaign, receipt }) - } - WorldCommand::Assess { - expected_revision, - intent, - proposal, - } => { - require_revision(&campaign, expected_revision)?; - validate_intent_text(&intent)?; - let assessment = match proposal { - Some(assessment) => { - if assessment.campaign_id != campaign.id - || assessment.revision != campaign.revision - || assessment.intent != intent - || assessment.expires_at < Utc::now() - || crate::assessor::assessment_digest(&assessment) - .map_err(|error| KernelError::Invalid(error.to_string()))? - != assessment.digest - { - return Err(KernelError::Invalid( - "assessment proposal is stale or invalid".into(), - )); - } - let actor = campaign - .actors - .get(&assessment.intent.actor_id) - .ok_or_else(|| KernelError::Invalid("assessment actor vanished".into()))?; - for (effect, stake) in [ - (&assessment.strong_effect, &assessment.success_stake), - (&assessment.success_effect, &assessment.success_stake), - (&assessment.mixed_effect, &assessment.mixed_stake), - (&assessment.failure_effect, &assessment.failure_stake), - ] { - crate::assessor::validate_effect(&campaign, actor, effect, stake) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - validate_bounded_coop_effect( - store, - &campaign, - &assessment.intent.actor_id, - effect, - )?; - } - assessment - } - None => assess(&campaign, intent), - }; - assessments.insert(assessment.digest.clone(), assessment.clone()); - Ok(CommandResult::Assessed { assessment }) - } - WorldCommand::Attempt { - actor_id, - assessment_digest, - } => { - let assessment = assessments - .get(&assessment_digest) - .cloned() - .ok_or(KernelError::UnknownAssessment)?; - if assessment.intent.actor_id != actor_id { - return Err(KernelError::Invalid( - "assessment belongs to another actor".into(), - )); - } - if assessment.revision != campaign.revision || assessment.expires_at < Utc::now() { - assessments.remove(&assessment_digest); - return Err(KernelError::StaleAssessment { - intent: assessment.intent, - actual_revision: campaign.revision, - }); - } - assessments.remove(&assessment_digest); - if !assessment.admissible { - return Err(KernelError::Impossible( - assessment - .missing_permission - .unwrap_or_else(|| "not admissible".into()), - )); - } - let roll = receipt( - assessment.digest.clone(), - rand::rng().random_range(1..=20), - assessment.modifier_total, - assessment.dc, - ); - let text = match roll.outcome { - OutcomeBand::StrongSuccess => &assessment.success_stake, - OutcomeBand::Success => &assessment.success_stake, - OutcomeBand::Mixed => &assessment.mixed_stake, - OutcomeBand::Failure => &assessment.failure_stake, - }; - let effect = match roll.outcome { - OutcomeBand::StrongSuccess => assessment.strong_effect.clone(), - OutcomeBand::Success => assessment.success_effect.clone(), - OutcomeBand::Mixed => assessment.mixed_effect.clone(), - OutcomeBand::Failure => assessment.failure_effect.clone(), - }; - let transition = crate::legacy_transition::lower_foreground_effect( - &campaign, - &assessment.intent.actor_id, - &effect, - roll.outcome.clone(), - crate::transition::MutationProcedure::ForegroundAttempt, - &assessment.effect_ceiling, - &assessment.digest, - Some( - crate::legacy_transition::digest_serializable(&assessment.intent) - .map_err(|error| KernelError::Invalid(error.to_string()))?, - ), - Some( - crate::legacy_transition::digest_serializable( - &assessment.intent.intended_effect, - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?, - ), - assessment.expires_at, - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mutation_receipt = crate::legacy_transition::apply_lowered_transition( - &mut campaign, - &transition, - Utc::now(), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - refresh_materialized_member_relevance( - &mut campaign, - std::iter::once(assessment.intent.actor_id.as_str()), - ); - if is_human_controlled_actor(&campaign, &assessment.intent.actor_id) { - campaign.last_player_activity = Utc::now(); - campaign.away_ticks_processed = 0; - campaign.pending_ticks = 0; - } - campaign.transcript.push(NarrativeTurn { - revision: campaign.revision + 1, - at: Utc::now(), - speaker: "world".into(), - text: text.clone(), - persona_response_actor_ids: BTreeSet::new(), - }); - commit_mutation_transition( - store, - row, - campaign, - "attempt", - Some(roll), - transition, - mutation_receipt, - ) - } - WorldCommand::Speak { - expected_revision, - actor_id, - text, - intended_effect, - persona_response_actor_ids, - } => { - require_revision(&campaign, expected_revision)?; - validate_bounded_text("speech", &text, 4_000)?; - if let Some(effect) = &intended_effect { - validate_bounded_text("intended effect", effect, 1_000)?; - } - let speaker = campaign - .actors - .get(&actor_id) - .ok_or_else(|| KernelError::Invalid("unknown actor".into()))?; - for response_actor_id in &persona_response_actor_ids { - let eligible_present = - campaign.actors.get(response_actor_id).is_some_and(|actor| { - actor.location_id == speaker.location_id - && campaign - .agency_profiles - .get(response_actor_id) - .is_none_or(|profile| profile.simulation_eligible) - }); - let eligible_folded = - crate::resolution::dormant_member_id_for_subject(&campaign, response_actor_id) - .and_then(|member_id| { - crate::resolution::dormant_member_location(&campaign, member_id).ok() - }) - .is_some_and(|location| location == speaker.location_id); - let eligible_gestalt = campaign.gestalts.get(response_actor_id).is_some_and(|_| { - crate::resolution::validate_active_gestalt_presence_location( - &campaign, - response_actor_id, - &speaker.location_id, - ) - .is_ok() - }); - if response_actor_id == &actor_id - || !(eligible_present || eligible_folded || eligible_gestalt) - { - return Err(KernelError::Invalid( - "speech response actor is not an eligible present Persona".into(), - )); - } - } - let response_actor_ids = persona_response_actor_ids.clone(); - campaign.transcript.push(NarrativeTurn { - revision: campaign.revision + 1, - at: Utc::now(), - speaker: actor_id.clone(), - text, - persona_response_actor_ids, - }); - if let Some(effect) = intended_effect { - campaign.transcript.push(NarrativeTurn { - revision: campaign.revision + 1, - at: Utc::now(), - speaker: "system".into(), - text: format!("Intended effect requires assessment: {effect}"), - persona_response_actor_ids: BTreeSet::new(), - }); - } - refresh_materialized_member_relevance( - &mut campaign, - std::iter::once(actor_id.as_str()) - .chain(response_actor_ids.iter().map(String::as_str)), - ); - if is_human_controlled_actor(&campaign, &actor_id) { - campaign.last_player_activity = Utc::now(); - campaign.away_ticks_processed = 0; - campaign.pending_ticks = 0; - } - commit(store, row, campaign, "speak", None) - } - WorldCommand::Wait { - expected_revision, - minutes, - } => { - require_revision(&campaign, expected_revision)?; - if minutes == 0 || minutes > 1_440 { - return Err(KernelError::Invalid( - "wait duration must be between 1 and 1440 minutes".into(), - )); - } - let source_receipt_id = format!( - "direct-wait:{}:{}:{}", - campaign.id, campaign.revision, minutes - ); - let transition = crate::legacy_transition::lower_time_advance( - &campaign, - minutes, - crate::transition::MutationProcedure::DirectCommand, - &source_receipt_id, - Utc::now() + Duration::minutes(5), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mutation_receipt = crate::legacy_transition::apply_lowered_transition( - &mut campaign, - &transition, - Utc::now(), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - campaign.last_player_activity = Utc::now(); - campaign.away_ticks_processed = 0; - campaign.pending_ticks = 0; - commit_mutation_transition( - store, - row, - campaign, - "wait", - None, - transition, - mutation_receipt, - ) - } - WorldCommand::ProposeTimeAdvance { - expected_revision, - member_id, - minutes, - } => { - require_revision(&campaign, expected_revision)?; - if minutes == 0 || minutes > 1_440 { - return Err(KernelError::Invalid( - "time advance must be between 1 and 1440 minutes".into(), - )); - } - let membership = load_campaign_membership(store, campaign.id)?; - require_active_member(&membership, &member_id)?; - if store - .load_all::("time_advance_proposal.v1") - .map_err(persist)? - .into_iter() - .any(|proposal| { - !proposal.committed && proposal.expected_world_revision == campaign.revision - }) - { - return Err(KernelError::Invalid( - "a time-advance proposal is already pending at this revision".into(), - )); - } - let proposal_id = format!("time:{}", uuid::Uuid::new_v4().simple()); - let proposal = TimeAdvanceProposal { - schema: "ghostlight.time_advance_proposal.v1".into(), - id: proposal_id.clone(), - campaign_id: campaign.id, - expected_world_revision: campaign.revision, - minutes, - proposer_member_id: member_id.clone(), - approvals: BTreeSet::from([member_id]), - committed: false, - }; - let proposal_row = store - .insert( - "time_advance_proposal.v1", - "ghostlight.time_advance_proposal.v1", - &proposal_id, - &proposal, - ) - .map_err(persist)?; - if active_member_ids(&membership) == proposal.approvals { - commit_governed_time_advance(store, row, campaign, proposal_row, proposal) - } else { - Ok(CommandResult::GovernancePending { campaign, proposal }) - } - } - WorldCommand::ApproveTimeAdvance { - expected_revision, - proposal_id, - member_id, - } => { - require_revision(&campaign, expected_revision)?; - let membership = load_campaign_membership(store, campaign.id)?; - require_active_member(&membership, &member_id)?; - let (proposal_row, mut proposal) = store - .load::("time_advance_proposal.v1", &proposal_id) - .map_err(persist)? - .ok_or_else(|| KernelError::Invalid("time proposal does not exist".into()))?; - if proposal.committed - || proposal.campaign_id != campaign.id - || proposal.expected_world_revision != campaign.revision - { - return Err(KernelError::Invalid( - "time proposal is committed, stale, or belongs to another campaign".into(), - )); - } - let newly_approved = proposal.approvals.insert(member_id); - if active_member_ids(&membership) == proposal.approvals { - commit_governed_time_advance(store, row, campaign, proposal_row, proposal) - } else if !newly_approved { - Err(KernelError::Invalid( - "member already approved this time proposal".into(), - )) - } else { - store - .replace( - &proposal_row, - "ghostlight.time_advance_proposal.v1", - &proposal, - ) - .map_err(persist)?; - Ok(CommandResult::GovernancePending { campaign, proposal }) - } - } - WorldCommand::ProposeGroupTravel { - expected_revision, - member_id, - destination_location_id, - } => { - require_revision(&campaign, expected_revision)?; - let membership = load_campaign_membership(store, campaign.id)?; - let member = require_active_member(&membership, &member_id)?; - let origin_location_id = campaign - .actors - .get(&member.actor_id) - .ok_or_else(|| KernelError::Invalid("member actor is missing".into()))? - .location_id - .clone(); - if membership - .members - .values() - .filter(|item| item.active) - .any(|item| { - campaign - .actors - .get(&item.actor_id) - .is_none_or(|actor| actor.location_id != origin_location_id) - }) - { - return Err(KernelError::Invalid( - "group travel requires every player to occupy the same scene".into(), - )); - } - let route = campaign - .locations - .get(&origin_location_id) - .and_then(|location| { - location - .routes - .values() - .find(|route| route.destination_id == destination_location_id) - }) - .ok_or_else(|| { - KernelError::Invalid("destination is not directly reachable".into()) - })?; - if store - .load_all::("group_travel_proposal.v1") - .map_err(persist)? - .into_iter() - .any(|proposal| { - !proposal.committed && proposal.expected_world_revision == campaign.revision - }) - { - return Err(KernelError::Invalid( - "a group-travel proposal is already pending at this revision".into(), - )); - } - let proposal_id = format!("travel:{}", uuid::Uuid::new_v4().simple()); - let proposal = GroupTravelProposal { - schema: "ghostlight.group_travel_proposal.v1".into(), - id: proposal_id.clone(), - campaign_id: campaign.id, - expected_world_revision: campaign.revision, - origin_location_id, - destination_location_id, - travel_minutes: route.travel_minutes, - proposer_member_id: member_id.clone(), - approvals: BTreeSet::from([member_id]), - committed: false, - }; - let proposal_row = store - .insert( - "group_travel_proposal.v1", - "ghostlight.group_travel_proposal.v1", - &proposal_id, - &proposal, - ) - .map_err(persist)?; - if active_member_ids(&membership) == proposal.approvals { - commit_governed_group_travel( - store, - row, - campaign, - proposal_row, - proposal, - &membership, - ) - } else { - Ok(CommandResult::TravelGovernancePending { campaign, proposal }) - } - } - WorldCommand::ApproveGroupTravel { - expected_revision, - proposal_id, - member_id, - } => { - require_revision(&campaign, expected_revision)?; - let membership = load_campaign_membership(store, campaign.id)?; - require_active_member(&membership, &member_id)?; - let (proposal_row, mut proposal) = store - .load::("group_travel_proposal.v1", &proposal_id) - .map_err(persist)? - .ok_or_else(|| { - KernelError::Invalid("group-travel proposal does not exist".into()) - })?; - if proposal.committed - || proposal.campaign_id != campaign.id - || proposal.expected_world_revision != campaign.revision - { - return Err(KernelError::Invalid( - "group-travel proposal is committed, stale, or belongs elsewhere".into(), - )); - } - let newly_approved = proposal.approvals.insert(member_id); - if active_member_ids(&membership) == proposal.approvals { - commit_governed_group_travel( - store, - row, - campaign, - proposal_row, - proposal, - &membership, - ) - } else if !newly_approved { - Err(KernelError::Invalid( - "member already approved this group-travel proposal".into(), - )) - } else { - store - .replace( - &proposal_row, - "ghostlight.group_travel_proposal.v1", - &proposal, - ) - .map_err(persist)?; - Ok(CommandResult::TravelGovernancePending { campaign, proposal }) - } - } - WorldCommand::SetResolutionBudget { - expected_revision, - expected_resolution_epoch, - active_cell_budget, - } => { - require_revision(&campaign, expected_revision)?; - require_resolution_epoch(&campaign, expected_resolution_epoch)?; - if campaign.resolution_policy.active_cell_budget == active_cell_budget { - return Err(KernelError::Invalid( - "resolution budget command does not change the active cell budget".into(), - )); - } - let previous_epoch = campaign.resolution_policy.resolution_epoch; - campaign.resolution_policy.active_cell_budget = active_cell_budget; - campaign.resolution_policy.pending_active_cell_budget = None; - crate::resolution::validate_policy(&campaign.resolution_policy) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - campaign.resolution_policy.resolution_epoch = previous_epoch.saturating_add(1); - campaign.resolution_cover = None; - commit_resolution_control( - store, - row, - campaign, - previous_epoch, - "set_active_cell_budget", - ) - } - WorldCommand::ProposeResolutionBudget { - expected_revision, - expected_resolution_epoch, - member_id, - active_cell_budget, - } => { - require_revision(&campaign, expected_revision)?; - require_resolution_epoch(&campaign, expected_resolution_epoch)?; - let membership = load_campaign_membership(store, campaign.id)?; - require_active_member(&membership, &member_id)?; - if active_cell_budget == 0 - || active_cell_budget > membership.pooled_cell_allowance() - || active_cell_budget == campaign.resolution_policy.active_cell_budget - { - return Err(KernelError::Invalid( - "cell budget must change and remain within the pooled allowance".into(), - )); - } - if store - .load_all::("cell_budget_proposal.v1") - .map_err(persist)? - .into_iter() - .any(|proposal| { - !proposal.committed - && proposal.expected_world_revision == campaign.revision - && proposal.expected_resolution_epoch - == campaign.resolution_policy.resolution_epoch - }) - { - return Err(KernelError::Invalid( - "a cell-budget proposal is already pending at this boundary".into(), - )); - } - let proposal_id = format!("cell-budget:{}", uuid::Uuid::new_v4().simple()); - let proposal = CellBudgetProposal { - schema: "ghostlight.cell_budget_proposal.v1".into(), - id: proposal_id.clone(), - campaign_id: campaign.id, - expected_world_revision: campaign.revision, - expected_resolution_epoch: campaign.resolution_policy.resolution_epoch, - active_cell_budget, - proposer_member_id: member_id.clone(), - approvals: BTreeSet::from([member_id]), - committed: false, - }; - let proposal_row = store - .insert( - "cell_budget_proposal.v1", - "ghostlight.cell_budget_proposal.v1", - &proposal_id, - &proposal, - ) - .map_err(persist)?; - if active_member_ids(&membership) == proposal.approvals { - commit_governed_cell_budget(store, row, campaign, proposal_row, proposal) - } else { - Ok(CommandResult::ResolutionGovernancePending { campaign, proposal }) - } - } - WorldCommand::ApproveResolutionBudget { - expected_revision, - proposal_id, - member_id, - } => { - require_revision(&campaign, expected_revision)?; - let membership = load_campaign_membership(store, campaign.id)?; - require_active_member(&membership, &member_id)?; - let (proposal_row, mut proposal) = store - .load::("cell_budget_proposal.v1", &proposal_id) - .map_err(persist)? - .ok_or_else(|| { - KernelError::Invalid("cell-budget proposal does not exist".into()) - })?; - if proposal.committed - || proposal.campaign_id != campaign.id - || proposal.expected_world_revision != campaign.revision - || proposal.expected_resolution_epoch != campaign.resolution_policy.resolution_epoch - { - return Err(KernelError::Invalid( - "cell-budget proposal is committed, stale, or belongs elsewhere".into(), - )); - } - let newly_approved = proposal.approvals.insert(member_id); - if active_member_ids(&membership) == proposal.approvals { - commit_governed_cell_budget(store, row, campaign, proposal_row, proposal) - } else if !newly_approved { - Err(KernelError::Invalid( - "member already approved this cell-budget proposal".into(), - )) - } else { - store - .replace( - &proposal_row, - "ghostlight.cell_budget_proposal.v1", - &proposal, - ) - .map_err(persist)?; - Ok(CommandResult::ResolutionGovernancePending { campaign, proposal }) - } - } - WorldCommand::SetProviderParallelism { - expected_revision, - expected_provider_configuration_epoch, - provider_parallelism, - } => { - require_revision(&campaign, expected_revision)?; - if campaign.resolution_policy.provider_configuration_epoch - != expected_provider_configuration_epoch - { - return Err(KernelError::Stale { - expected: expected_provider_configuration_epoch, - actual: campaign.resolution_policy.provider_configuration_epoch, - }); - } - if campaign.resolution_policy.provider_parallelism == provider_parallelism { - return Err(KernelError::Invalid( - "provider parallelism command does not change provider configuration".into(), - )); - } - campaign.resolution_policy.provider_parallelism = provider_parallelism; - crate::resolution::validate_policy(&campaign.resolution_policy) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let previous_epoch = campaign.resolution_policy.resolution_epoch; - campaign.resolution_policy.provider_configuration_epoch = campaign - .resolution_policy - .provider_configuration_epoch - .saturating_add(1); - commit_resolution_control( - store, - row, - campaign, - previous_epoch, - "set_provider_parallelism", - ) - } - WorldCommand::ReplaceResolutionPins { - expected_revision, - expected_resolution_epoch, - pins, - } => { - require_revision(&campaign, expected_revision)?; - require_resolution_epoch(&campaign, expected_resolution_epoch)?; - let mut replacement = BTreeMap::new(); - for pin in pins { - if replacement.insert(pin.id.clone(), pin).is_some() { - return Err(KernelError::Invalid("duplicate resolution pin id".into())); - } - } - crate::resolution::validate_pins(&campaign, &replacement) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let previous_epoch = campaign.resolution_policy.resolution_epoch; - campaign.resolution_pins = replacement; - campaign.resolution_policy.resolution_epoch = previous_epoch.saturating_add(1); - campaign.resolution_cover = None; - commit_resolution_control( - store, - row, - campaign, - previous_epoch, - "replace_resolution_pins", - ) - } - WorldCommand::FissionGestalt { - expected_revision, - preview, - evidence_receipts, - model_stage_receipts, - } => { - require_revision(&campaign, expected_revision)?; - let supplied_evidence: BTreeSet<_> = evidence_receipts - .iter() - .map(|receipt| receipt.id.clone()) - .collect(); - if preview - .evidence_receipt_ids - .iter() - .any(|id| !supplied_evidence.contains(id)) - { - return Err(KernelError::Invalid( - "fission preview evidence receipts were not supplied".into(), - )); - } - let transition = crate::legacy_transition::lower_fission( - &campaign, - &preview, - Utc::now() + Duration::minutes(5), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mutation_receipt = crate::legacy_transition::apply_lowered_fission( - &mut campaign, - &preview, - &transition, - Utc::now(), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - for candidate in &preview.canon_candidates { - campaign - .canon_candidates - .insert(candidate.id.clone(), candidate.clone()); - } - commit_with_records( - store, - row, - campaign, - "fission_gestalt", - evidence_receipts, - preview.canon_candidates, - model_stage_receipts, - None, - Some((transition, mutation_receipt)), - ) - } - WorldCommand::ElaborateGestaltFission { - expected_revision, - preview, - qualification, - model_stage_receipts, - } => { - require_revision(&campaign, expected_revision)?; - if qualification.schema != "ghostlight.world_complexity_fission_qualification.v1" - || !(1..=6).contains(&qualification.target_actionable_gain) - || model_stage_receipts.is_empty() - { - return Err(KernelError::Invalid( - "elaborated fission lacks its exact qualification or model provenance".into(), - )); - } - let parent = campaign - .gestalts - .get(&preview.parent_gestalt_id) - .ok_or_else(|| KernelError::Invalid("fission parent is unknown".into()))?; - let proposal = crate::elaboration::WorldComplexityProposal::Fission { - preview: preview.clone(), - qualification: qualification.clone(), - }; - crate::resolution::validate_elaborated_fission(&campaign, &preview) - .and_then(|_| { - crate::elaboration::validate_complexity_fission_semantics( - &campaign, - parent, - &preview, - qualification.title, - &qualification.jurisdiction_location_id, - qualification.target_actionable_gain, - ) - }) - .and_then(|_| { - crate::elaboration::validate_world_complexity_semantic_provenance( - &campaign, - &proposal, - &qualification.semantic, - &model_stage_receipts, - ) - }) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let transition = crate::legacy_transition::lower_elaborated_fission( - &campaign, - &preview, - Utc::now() + Duration::minutes(5), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mutation_receipt = crate::legacy_transition::apply_lowered_elaborated_fission( - &mut campaign, - &preview, - &transition, - Utc::now(), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - commit_with_records( - store, - row, - campaign, - "elaborate_gestalt_fission", - Vec::new(), - Vec::new(), - model_stage_receipts, - None, - Some((transition, mutation_receipt)), - ) - } - WorldCommand::ReconcileFissionCivicBindings { expected_revision } => { - require_revision(&campaign, expected_revision)?; - let transition = crate::legacy_transition::lower_fission_civic_reconciliation( - &campaign, - Utc::now() + Duration::minutes(5), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))? - .ok_or_else(|| { - KernelError::Invalid("campaign has no stale fission civic bindings".into()) - })?; - let mutation_receipt = - crate::legacy_transition::apply_lowered_fission_civic_reconciliation( - &mut campaign, - &transition, - Utc::now(), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - commit_with_records( - store, - row, - campaign, - "reconcile_fission_civic_bindings", - Vec::new(), - Vec::new(), - Vec::new(), - None, - Some((transition, mutation_receipt)), - ) - } - WorldCommand::AdvanceStrategicTick { - expected_revision, - source, - plan, - model_receipt_hash, - resolution_wave, - } => { - require_revision(&campaign, expected_revision)?; - if plan.is_some() && resolution_wave.is_some() { - return Err(KernelError::Invalid( - "strategic tick has two competing plan authorities".into(), - )); - } - let resolved_plan = resolution_wave - .as_ref() - .map(|wave| crate::resolution::validate_and_resolve_wave(&campaign, wave)) - .transpose() - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let external_subject_ids = store - .load_all::( - "external_subject_authority.v1", - ) - .map_err(persist)? - .into_iter() - .map(|authority| authority.subject_id) - .collect::>(); - if resolved_plan - .as_ref() - .or(plan.as_ref()) - .is_some_and(|plan| { - strategic_plan_writes_external_subject(plan, &external_subject_ids) - }) - { - return Err(KernelError::Invalid( - "strategic resolution cannot mutate an external subject or bypass its proposal boundary".into(), - )); - } - if (plan.is_some() || resolution_wave.is_some()) - && model_receipt_hash - .as_deref() - .is_none_or(|hash| !valid_sha256(hash)) - { - return Err(KernelError::Invalid( - "model-driven strategic tick lacks an exact model receipt hash".into(), - )); - } - if let Some(wave) = &resolution_wave { - let unique_hashes: BTreeSet<_> = wave.model_receipt_hashes.iter().collect(); - let action_count = wave - .appraisals - .iter() - .map(|appraisal| appraisal.actions.len()) - .sum::(); - let outcome_digests = resolved_plan - .as_ref() - .map(crate::outcome::plan_activity_digests) - .unwrap_or_default(); - let outcome_stage_count = outcome_digests.len(); - if unique_hashes.len() != wave.model_receipt_hashes.len() - || wave.model_receipt_hashes.len() - < wave - .cover - .cells - .len() - .saturating_mul(3) - .saturating_add(action_count) - .saturating_add(outcome_stage_count) - { - return Err(KernelError::Invalid( - "resolution wave does not carry one distinct stage receipt per cell stage" - .into(), - )); - } - let mut stage_bindings = BTreeSet::new(); - for hash in &wave.model_receipt_hashes { - let Some((_, receipt)) = store - .load::("persona_stage_receipt.v1", hash) - .map_err(persist)? - else { - return Err(KernelError::Invalid( - "resolution wave references an unknown model receipt".into(), - )); - }; - if receipt.storage_key() != hash { - return Err(KernelError::Invalid( - "resolution wave contains a mismatched model receipt".into(), - )); - } - if receipt.validation_result == "valid" { - stage_bindings - .insert((receipt.stage.clone(), receipt.snapshot_binding.clone())); - } - } - if !wave.cover.causal_follow_through.is_empty() { - let expected_binding = - crate::follow_through::nemesis_admission_binding(&campaign, &wave.cover) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - if !stage_bindings.contains(&( - crate::follow_through::NEMESIS_STAGE.into(), - expected_binding, - )) { - return Err(KernelError::Invalid( - "resolution wave lacks the exact Nemesis receipt admitted for its causal agenda" - .into(), - )); - } - } - for cell in &wave.cover.cells { - let binding = format!( - "campaign:{}:revision:{}:resolution:{}:cell:{}", - campaign.id, - campaign.revision, - campaign.resolution_policy.resolution_epoch, - cell.id - ); - for stage in ["cell_projector", "cell_persona", "cell_interpreter"] { - if !stage_bindings.contains(&(stage.into(), binding.clone())) { - return Err(KernelError::Invalid(format!( - "resolution wave lacks {stage} receipt for {}", - cell.id - ))); - } - } - let actionful = wave - .appraisals - .iter() - .find(|appraisal| appraisal.cell_id == cell.id) - .is_some_and(|appraisal| !appraisal.actions.is_empty()); - if actionful { - let appraisal = wave - .appraisals - .iter() - .find(|appraisal| appraisal.cell_id == cell.id) - .expect("active cell appraisal was validated"); - for action in &appraisal.actions { - let verifier_binding = - crate::persona::cell_effect_verification_binding( - &binding, - std::slice::from_ref(action), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - if !stage_bindings - .contains(&("cell_effect_verifier".into(), verifier_binding)) - { - return Err(KernelError::Invalid(format!( - "resolution wave lacks action-bound cell_effect_verifier receipt for {} action by {}", - cell.id, action.subject_id - ))); - } - } - } - } - for binding in expected_activity_outcome_bindings(&campaign, &outcome_digests) { - if !stage_bindings.contains(&("strategic_outcome_resolver".into(), binding)) { - return Err(KernelError::Invalid( - "resolution wave lacks an activity-bound strategic outcome receipt" - .into(), - )); - } - } - for outcome in wave.activity_outcomes.iter().filter(|outcome| { - !matches!( - outcome.effect, - StrategicOutcomeEffect::NoMaterialChange { .. } - ) - }) { - let binding = crate::outcome::activity_outcome_verification_binding( - campaign.id, - campaign.revision, - campaign.resolution_policy.resolution_epoch, - std::slice::from_ref(outcome), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - if !stage_bindings.contains(&("strategic_outcome_verifier".into(), binding)) { - return Err(KernelError::Invalid( - "resolution wave lacks an outcome-bound strategic verifier receipt" - .into(), - )); - } - } - if !wave.strategic_individuations.is_empty() { - let selected_actions = resolved_plan - .as_ref() - .map(|plan| plan.selected_actions.as_slice()) - .unwrap_or_default(); - let candidate_digests = - crate::scheduler::strategic_individuation_candidate_digests( - &campaign, - selected_actions, - ); - for proposal in &wave.strategic_individuations { - let proposal_digest = - crate::scheduler::strategic_individuation_proposal_digest(proposal) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let binding = crate::scheduler::strategic_individuation_binding( - &campaign, - &candidate_digests, - Some(&proposal_digest), - ); - if !stage_bindings - .contains(&("strategic_individuation_selector".into(), binding)) - { - return Err(KernelError::Invalid( - "strategic individuation lacks a payload-bound selector receipt" - .into(), - )); - } - } - } - } - if let Some(wave) = &resolution_wave { - for proposal in &wave.strategic_individuations { - apply_individuation(&mut campaign, &proposal.individuation)?; - } - } - let individuation_public_channels = resolved_plan - .as_ref() - .or(plan.as_ref()) - .map(|plan| { - plan.selected_actions - .iter() - .map(|action| { - crate::resolution::cell_action_digest(action) - .map(|digest| (digest, action.public_channels.clone())) - .map_err(|error| KernelError::Invalid(error.to_string())) - }) - .collect::, _>>() - }) - .transpose()? - .unwrap_or_default(); - let applied_tick = match resolved_plan.or(plan) { - Some(plan) => apply_strategic_tick_plan(&mut campaign, plan)?, - None => { - let plan = deterministic_strategic_tick_plan(); - apply_strategic_tick_plan(&mut campaign, plan)? - } - }; - let AppliedStrategicTickPlan { - events: mut tick_events, - mutation, - } = applied_tick; - if let Some(wave) = &resolution_wave { - for proposal in &wave.strategic_individuations { - let member = &proposal.individuation.member; - let gestalt_name = campaign - .gestalts - .get(&proposal.individuation.gestalt_id) - .map(|gestalt| gestalt.name.as_str()) - .unwrap_or("their community"); - let undertaking = member - .goals - .first() - .map(String::as_str) - .or_else(|| member.obligations.iter().next().map(String::as_str)); - let summary = undertaking.map_or_else( - || format!("{} steps forward within {gestalt_name}.", member.name), - |undertaking| { - format!( - "{} steps forward within {gestalt_name} to {undertaking}.", - member.name - ) - }, - ); - tick_events.push(crate::domain::Event { - id: format!( - "strategic:{}:individuation:{}", - campaign.strategic_tick_count.saturating_add(1), - crate::domain::canonical_gestalt_member_local_id(&member.id) - ), - at: campaign.world_time, - kind: "gestalt_individuation".into(), - summary: summary - .chars() - .take(MAX_PUBLIC_EVENT_SUMMARY_CHARS) - .collect(), - actor_ids: vec![crate::domain::gestalt_member_subject_id(&member.id)], - institution_ids: vec![], - gestalt_ids: vec![proposal.individuation.gestalt_id.clone()], - location_ids: vec![proposal.individuation.location_id.clone()], - public_channels: individuation_public_channels - .get(&proposal.action_digest) - .cloned() - .unwrap_or_default(), - }); - } - } - if let Some(wave) = &resolution_wave { - crate::resolution::advance_detail_debt(&mut campaign, &wave.cover); - campaign.resolution_cover = Some(wave.cover.clone()); - } - campaign.strategic_tick_count = campaign.strategic_tick_count.saturating_add(1); - let event_ids = mutation - .as_ref() - .into_iter() - .flat_map(|(_, receipt)| receipt.derived_event_ids.iter().cloned()) - .chain(tick_events.iter().map(|event| event.id.clone())) - .collect(); - for event in tick_events { - crate::domain::append_event_with_publications(&mut campaign, event); - } - if source == TickSource::PlayerWait { - campaign.last_player_activity = Utc::now(); - campaign.away_ticks_processed = 0; - campaign.pending_ticks = 0; - } else { - campaign.away_ticks_processed = - campaign.away_ticks_processed.saturating_add(1).min(8); - campaign.pending_ticks = campaign.pending_ticks.saturating_sub(1); - } - commit_strategic_tick( - store, - row, - campaign, - source, - model_receipt_hash, - event_ids, - resolution_wave, - mutation, - ) - } - WorldCommand::ExpandRegion { - expected_revision, - expansion, - evidence_receipts, - canon_candidates, - model_stage_receipts, - } => { - require_revision(&campaign, expected_revision)?; - validate_region_admission_evidence(&expansion, &evidence_receipts, &canon_candidates)?; - crate::compiler::validate_new_destination_expansion(&campaign, &expansion) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - crate::compiler::validate_civic_admission_receipts( - &campaign, - &expansion, - &model_stage_receipts, - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let transition = crate::legacy_transition::lower_region_expansion( - &campaign, - &expansion, - Utc::now() + Duration::minutes(5), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mutation_receipt = crate::legacy_transition::apply_lowered_region_expansion( - &mut campaign, - &expansion, - &transition, - Utc::now(), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - for candidate in &canon_candidates { - campaign - .canon_candidates - .insert(candidate.id.clone(), candidate.clone()); - } - commit_with_records( - store, - row, - campaign, - "expand_region", - evidence_receipts, - canon_candidates, - model_stage_receipts, - None, - Some((transition, mutation_receipt)), - ) - } - WorldCommand::ElaborateLocality { - expected_revision, - elaboration, - evidence_receipts, - canon_candidates, - model_stage_receipts, - } => { - require_revision(&campaign, expected_revision)?; - validate_region_admission_evidence( - &elaboration.expansion, - &evidence_receipts, - &canon_candidates, - )?; - crate::compiler::validate_locality_elaboration(&campaign, &elaboration) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - crate::compiler::validate_civic_admission_receipts( - &campaign, - &elaboration.expansion, - &model_stage_receipts, - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let transition = crate::legacy_transition::lower_region_expansion( - &campaign, - &elaboration.expansion, - Utc::now() + Duration::minutes(5), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mutation_receipt = crate::legacy_transition::apply_lowered_region_expansion( - &mut campaign, - &elaboration.expansion, - &transition, - Utc::now(), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - for candidate in &canon_candidates { - campaign - .canon_candidates - .insert(candidate.id.clone(), candidate.clone()); - } - commit_with_records( - store, - row, - campaign, - "elaborate_locality", - evidence_receipts, - canon_candidates, - model_stage_receipts, - None, - Some((transition, mutation_receipt)), - ) - } - WorldCommand::MaterializeGestaltMember { - expected_revision, - gestalt_id, - expected_gestalt_version, - member_id, - expected_member_version, - location_id, - } => { - require_revision(&campaign, expected_revision)?; - let before = campaign.clone(); - apply_promotion( - &mut campaign, - &GestaltPromotion { - gestalt_id, - expected_gestalt_version, - member_id, - expected_member_version, - location_id, - }, - )?; - commit_gestalt_presence( - store, - row, - before, - campaign, - "materialize_gestalt_member", - "direct materialization command", - Vec::new(), - ) - } - WorldCommand::IndividuateGestaltMember { - expected_revision, - individuation, - } => { - require_revision(&campaign, expected_revision)?; - let before = campaign.clone(); - apply_individuation(&mut campaign, &individuation)?; - commit_gestalt_presence( - store, - row, - before, - campaign, - "individuate_gestalt_member", - "direct individuation command", - Vec::new(), - ) - } - WorldCommand::ElaborateGestaltIndividuation { - expected_revision, - individuation, - qualification, - model_stage_receipts, - } => { - require_revision(&campaign, expected_revision)?; - if qualification.schema != "ghostlight.world_complexity_individuation_qualification.v1" - || model_stage_receipts.is_empty() - { - return Err(KernelError::Invalid( - "elaborated individuation lacks its exact qualification or model provenance" - .into(), - )); - } - let proposal = crate::elaboration::WorldComplexityProposal::Individuate { - individuation: individuation.clone(), - qualification: qualification.clone(), - }; - if crate::elaboration::unique_containing_jurisdiction( - &campaign, - &BTreeSet::from([individuation.location_id.clone()]), - &BTreeSet::from([qualification.jurisdiction_location_id.clone()]), - ) - .as_deref() - != Some(qualification.jurisdiction_location_id.as_str()) - { - return Err(KernelError::Invalid( - "elaborated individuation escaped its qualified jurisdiction".into(), - )); - } - crate::resolution::validate_gestalt_individuation(&campaign, &individuation) - .and_then(|_| { - crate::elaboration::validate_complexity_individuation_semantics( - &campaign, - qualification.title, - &individuation, - ) - }) - .and_then(|_| { - crate::elaboration::validate_world_complexity_semantic_provenance( - &campaign, - &proposal, - &qualification.semantic, - &model_stage_receipts, - ) - }) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let before = campaign.clone(); - apply_individuation(&mut campaign, &individuation)?; - commit_gestalt_presence( - store, - row, - before, - campaign, - "elaborate_gestalt_individuation", - "model-qualified world-complexity individuation", - model_stage_receipts, - ) - } - WorldCommand::DematerializeGestaltMember { - expected_revision, - actor_id, - } => { - require_revision(&campaign, expected_revision)?; - let before = campaign.clone(); - apply_demotion(&mut campaign, &GestaltDemotion { actor_id })?; - commit_gestalt_presence( - store, - row, - before, - campaign, - "dematerialize_gestalt_member", - "direct dematerialization command", - Vec::new(), - ) - } - WorldCommand::ReconcileGestaltPresence { - expected_revision, - reason, - plan, - } => { - require_revision(&campaign, expected_revision)?; - if reason.trim().is_empty() { - return Err(KernelError::Invalid("presence plan has no reason".into())); - } - if !plan.individuations.is_empty() - && crate::gestalt::automatic_individuation_stimulus(&campaign).as_deref() - != Some(reason.as_str()) - { - return Err(KernelError::Invalid( - "automatic individuation is admitted only by the exact immediately committed player speech" - .into(), - )); - } - if plan.individuations.len() > 1 { - return Err(KernelError::Invalid( - "one player speech can admit at most one first-relevance person".into(), - )); - } - let addressed_public_identities = - crate::gestalt::automatic_individuation_addressed_actor_ids(&campaign) - .iter() - .filter_map(|actor_id| campaign.actors.get(actor_id)) - .map(|actor| actor.name.trim().to_lowercase()) - .collect::>(); - if plan.individuations.iter().any(|individuation| { - addressed_public_identities - .contains(&individuation.member.name.trim().to_lowercase()) - }) { - return Err(KernelError::Invalid( - "presence individuation duplicates an already-addressed actor".into(), - )); - } - let player_location = &campaign.actors[&campaign.player_actor_id].location_id; - if plan - .individuations - .iter() - .any(|entry| &entry.location_id != player_location) - || plan - .promotions - .iter() - .any(|entry| &entry.location_id != player_location) - { - return Err(KernelError::Invalid( - "automatic presence reconciliation is confined to the player's active location" - .into(), - )); - } - let before = campaign.clone(); - let mut candidate = campaign.clone(); - for demotion in &plan.demotions { - apply_demotion(&mut candidate, demotion)?; - } - for individuation in &plan.individuations { - apply_individuation(&mut candidate, individuation)?; - } - for promotion in &plan.promotions { - apply_promotion(&mut candidate, promotion)?; - } - commit_gestalt_presence( - store, - row, - before, - candidate, - "reconcile_gestalt_presence", - &reason, - Vec::new(), - ) - } - WorldCommand::ResolveReactionWave { - expected_revision, - event_summary, - reactions, - gestalt_reactions, - } => { - require_revision(&campaign, expected_revision)?; - let witnessed_turn = canonical_witnessed_turn(&campaign, &event_summary)?; - let response_expected_actor_ids = witnessed_turn.persona_response_actor_ids.clone(); - let witnessed_memory = format!("Witnessed: {}", canonical_turn_text(witnessed_turn)); - let player_location = campaign.actors[&campaign.player_actor_id] - .location_id - .clone(); - let mut seen = BTreeSet::new(); - for reaction in &reactions { - if !seen.insert(reaction.actor_id.clone()) { - return Err(KernelError::Invalid( - "actor reacted twice in one wave".into(), - )); - } - let actor = campaign - .actors - .get(&reaction.actor_id) - .ok_or_else(|| KernelError::Invalid("reaction actor is unknown".into()))?; - if actor.location_id != player_location { - return Err(KernelError::Invalid("reaction actor is not present".into())); - } - if !reaction.private_delta.memories_add.is_empty() { - return Err(KernelError::Invalid( - "reaction Interpreter cannot write actor memory".into(), - )); - } - if let Some(identity) = reaction.private_delta.identity_adoption.as_deref() { - validate_bounded_text("reaction identity adoption", identity, 160)?; - let speech = reaction.speech.as_deref().ok_or_else(|| { - KernelError::Invalid( - "reaction identity adoption requires public speech".into(), - ) - })?; - if !speech.to_lowercase().contains(&identity.to_lowercase()) { - return Err(KernelError::Invalid( - "reaction identity adoption must copy an exact spoken handle".into(), - )); - } - validate_reaction_identity_adoption(&campaign, &reaction.actor_id, identity)?; - } - if let Some(speech) = &reaction.speech { - validate_bounded_text("reaction speech", speech, 1_000)?; - } - for proposal in &reaction.action_proposals { - validate_world_proposal(actor, proposal)?; - } - } - let mut seen_gestalts = BTreeSet::new(); - for reaction in &gestalt_reactions { - if !seen_gestalts.insert(reaction.gestalt_id.clone()) { - return Err(KernelError::Invalid( - "Gestalt reacted twice in one wave".into(), - )); - } - if seen.contains(&reaction.gestalt_id) { - return Err(KernelError::Invalid( - "reaction subject appeared as both actor and Gestalt".into(), - )); - } - crate::resolution::validate_active_gestalt_presence_location( - &campaign, - &reaction.gestalt_id, - &player_location, - ) - .map_err(|_| KernelError::Invalid("reaction Gestalt is not present".into()))?; - if let Some(speech) = &reaction.speech { - validate_bounded_text("Gestalt reaction speech", speech, 1_000)?; - } - } - for response_actor_id in &response_expected_actor_ids { - let actor_reaction = reactions - .iter() - .find(|reaction| &reaction.actor_id == response_actor_id); - let gestalt_reaction = gestalt_reactions - .iter() - .find(|reaction| &reaction.gestalt_id == response_actor_id); - let observable = actor_reaction.is_some_and(|reaction| { - reaction - .speech - .as_deref() - .is_some_and(|value| !value.trim().is_empty()) - || reaction.deliberate_silence - }) || gestalt_reaction.is_some_and(|reaction| { - reaction - .speech - .as_deref() - .is_some_and(|value| !value.trim().is_empty()) - || reaction.deliberate_silence - }); - if !observable { - return Err(KernelError::Invalid( - "directly addressed Persona is absent or produced no observable response" - .into(), - )); - } - } - let source_receipt_id = format!( - "reaction-input:{}", - crate::legacy_transition::digest_serializable(&(&reactions, &gestalt_reactions)) - .map_err(|error| KernelError::Invalid(error.to_string()))? - ); - let transition = crate::legacy_transition::lower_reaction_wave( - &campaign, - &witnessed_memory, - &reactions, - &source_receipt_id, - Utc::now() + Duration::minutes(5), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mutation_receipt = crate::legacy_transition::apply_lowered_transition( - &mut campaign, - &transition, - Utc::now(), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - campaign.pending_world_proposals.clear(); - for reaction in reactions { - if let Some(speech) = reaction.speech { - campaign.transcript.push(NarrativeTurn { - revision: campaign.revision + 1, - at: Utc::now(), - speaker: reaction.actor_id.clone(), - text: speech, - persona_response_actor_ids: BTreeSet::new(), - }); - } - if reaction.deliberate_silence { - campaign.transcript.push(NarrativeTurn { - revision: campaign.revision + 1, - at: Utc::now(), - speaker: reaction.actor_id.clone(), - text: "deliberately does not answer.".into(), - persona_response_actor_ids: BTreeSet::new(), - }); - } - campaign - .pending_world_proposals - .extend(reaction.action_proposals); - } - for reaction in gestalt_reactions { - if let Some(speech) = reaction.speech { - campaign.transcript.push(NarrativeTurn { - revision: campaign.revision + 1, - at: Utc::now(), - speaker: reaction.gestalt_id.clone(), - text: speech, - persona_response_actor_ids: BTreeSet::new(), - }); - } - if reaction.deliberate_silence { - campaign.transcript.push(NarrativeTurn { - revision: campaign.revision + 1, - at: Utc::now(), - speaker: reaction.gestalt_id, - text: "deliberately does not answer.".into(), - persona_response_actor_ids: BTreeSet::new(), - }); - } - } - refresh_materialized_member_relevance(&mut campaign, seen.iter().map(String::as_str)); - campaign.events.push(Event { - id: format!("reaction-wave:{}", campaign.revision + 1), - at: campaign.world_time, - kind: "reaction_wave".into(), - summary: event_summary, - actor_ids: seen.into_iter().collect(), - institution_ids: vec![], - gestalt_ids: seen_gestalts.into_iter().collect(), - location_ids: vec![player_location], - public_channels: vec![], - }); - commit_mutation_transition( - store, - row, - campaign, - "reaction_wave", - None, - transition, - mutation_receipt, - ) - } - WorldCommand::ResolveNpcAction { - expected_revision, - proposal, - assessment, - } => { - require_revision(&campaign, expected_revision)?; - let current_window_id = format!("reaction-wave:{}", campaign.revision); - if campaign - .events - .last() - .is_none_or(|event| event.kind != "reaction_wave" || event.id != current_window_id) - { - return Err(KernelError::Invalid( - "pending NPC initiative does not belong to the current reaction wave".into(), - )); - } - let selected = crate::initiative::winner(&campaign.pending_world_proposals) - .ok_or_else(|| KernelError::Invalid("there is no pending NPC action".into()))?; - if proposal != selected { - return Err(KernelError::Invalid( - "proposal does not own the current initiative opportunity".into(), - )); - } - let actor = campaign - .actors - .get(&proposal.actor_id) - .ok_or_else(|| KernelError::Invalid("initiative actor is unknown".into()))?; - validate_world_proposal(actor, &proposal)?; - let intent = ActionIntent { - actor_id: proposal.actor_id.clone(), - description: proposal.intent.clone(), - intended_effect: proposal.intended_effect.clone(), - }; - if assessment.campaign_id != campaign.id - || assessment.revision != campaign.revision - || assessment.intent != intent - || assessment.expires_at < Utc::now() - || crate::assessor::assessment_digest(&assessment) - .map_err(|error| KernelError::Invalid(error.to_string()))? - != assessment.digest - { - return Err(KernelError::Invalid( - "NPC assessment is stale or invalid".into(), - )); - } - for (effect, stake) in [ - (&assessment.strong_effect, &assessment.success_stake), - (&assessment.success_effect, &assessment.success_stake), - (&assessment.mixed_effect, &assessment.mixed_stake), - (&assessment.failure_effect, &assessment.failure_stake), - ] { - crate::assessor::validate_effect(&campaign, actor, effect, stake) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - validate_bounded_coop_effect(store, &campaign, &proposal.actor_id, effect)?; - } - let actor_name = actor.name.clone(); - let actor_location = actor.location_id.clone(); - campaign.pending_world_proposals.clear(); - let roll = if assessment.admissible { - let roll = receipt( - assessment.digest.clone(), - rand::rng().random_range(1..=20), - assessment.modifier_total, - assessment.dc, - ); - let (text, effect) = match roll.outcome { - OutcomeBand::StrongSuccess => { - (&assessment.success_stake, &assessment.strong_effect) - } - OutcomeBand::Success => (&assessment.success_stake, &assessment.success_effect), - OutcomeBand::Mixed => (&assessment.mixed_stake, &assessment.mixed_effect), - OutcomeBand::Failure => (&assessment.failure_stake, &assessment.failure_effect), - }; - let transition = crate::legacy_transition::lower_foreground_effect( - &campaign, - &proposal.actor_id, - effect, - roll.outcome.clone(), - crate::transition::MutationProcedure::NpcAttempt, - &assessment.effect_ceiling, - &assessment.digest, - Some( - crate::legacy_transition::digest_serializable(&intent) - .map_err(|error| KernelError::Invalid(error.to_string()))?, - ), - Some( - crate::legacy_transition::digest_serializable(&intent.intended_effect) - .map_err(|error| KernelError::Invalid(error.to_string()))?, - ), - assessment.expires_at, - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mutation_receipt = crate::legacy_transition::apply_lowered_transition( - &mut campaign, - &transition, - Utc::now(), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - campaign.transcript.push(NarrativeTurn { - revision: campaign.revision + 1, - at: Utc::now(), - speaker: "world".into(), - text: text.clone(), - persona_response_actor_ids: BTreeSet::new(), - }); - Some((roll, transition, mutation_receipt)) - } else { - None - }; - campaign.events.push(Event { - id: format!("npc-action-resolved:{}", campaign.revision + 1), - at: campaign.world_time, - kind: "npc_action_resolved".into(), - summary: if assessment.admissible { - format!("{} attempts {}", actor_name, proposal.intent) - } else { - format!("{} cannot yet attempt {}", actor_name, proposal.intent) - }, - actor_ids: vec![proposal.actor_id.clone()], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec![actor_location], - public_channels: vec![], - }); - refresh_materialized_member_relevance( - &mut campaign, - std::iter::once(proposal.actor_id.as_str()), - ); - if let Some((roll, transition, mutation_receipt)) = roll { - commit_mutation_transition( - store, - row, - campaign, - "resolve_npc_action", - Some(roll), - transition, - mutation_receipt, - ) - } else { - commit(store, row, campaign, "resolve_npc_action", None) - } - } - WorldCommand::BindClockConsequences { - expected_revision, - admission, - model_stage_receipts, - } => { - require_revision(&campaign, expected_revision)?; - crate::clock::validate_binding_receipts(&campaign, &admission, &model_stage_receipts) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let news_count_before = campaign.news.len(); - let next_wave_index = campaign.strategic_tick_count.saturating_add(1) as usize; - let emitted_event_ids = - crate::clock::apply_clock_consequence_bindings(&mut campaign, &admission.bindings) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - commit_with_records( - store, - row, - campaign, - "bind_clock_consequences", - Vec::new(), - Vec::new(), - model_stage_receipts, - Some(ClockBindingCommitData { - admission, - emitted_event_ids, - news_count_before, - next_wave_index, - }), - None, - ) - } - WorldCommand::CreateCampaign { .. } => unreachable!(), - } -} - -fn external_outcome_writes_subject( - effect: &StrategicOutcomeEffect, - external_subject_ids: &BTreeSet, -) -> bool { - match effect { - StrategicOutcomeEffect::ResourceCreated { - owner_subject_id, .. - } - | StrategicOutcomeEffect::ResourceConsumed { - owner_subject_id, .. - } - | StrategicOutcomeEffect::KnowledgeLearned { - owner_subject_id, .. - } => external_subject_ids.contains(owner_subject_id), - StrategicOutcomeEffect::ResourceTransferred { - from_subject_id, - to_subject_id, - .. - } => { - external_subject_ids.contains(from_subject_id) - || external_subject_ids.contains(to_subject_id) - } - StrategicOutcomeEffect::KnowledgeCommunicated { to_subject_ids, .. } => to_subject_ids - .iter() - .any(|subject_id| external_subject_ids.contains(subject_id)), - StrategicOutcomeEffect::NoMaterialChange { .. } - | StrategicOutcomeEffect::GestaltPressure { .. } - | StrategicOutcomeEffect::AgencyRelationShift { .. } - | StrategicOutcomeEffect::MemberMemory { .. } - | StrategicOutcomeEffect::MemberObligation { .. } - | StrategicOutcomeEffect::MemberRelationship { .. } => false, - } -} - -fn strategic_plan_writes_external_subject( - plan: &StrategicTickPlan, - external_subject_ids: &BTreeSet, -) -> bool { - plan.selected_actions.iter().any(|action| { - crate::consumer::proposal_targets(action) - .iter() - .any(|target| external_subject_ids.contains(*target)) - }) || plan - .institution_actions - .iter() - .any(|action| external_subject_ids.contains(&action.institution_id)) - || plan - .activity_outcomes - .iter() - .any(|outcome| external_outcome_writes_subject(&outcome.effect, external_subject_ids)) -} - -fn expected_activity_outcome_bindings( - campaign: &Campaign, - action_digests: &[String], -) -> Vec { - action_digests - .iter() - .map(|digest| { - crate::outcome::activity_outcome_binding( - campaign.id, - campaign.revision, - campaign.resolution_policy.resolution_epoch, - std::slice::from_ref(digest), - ) - }) - .collect() -} - -fn validate_intent_text(intent: &ActionIntent) -> Result<(), KernelError> { - validate_bounded_text("action description", &intent.description, 4_000)?; - validate_bounded_text("intended effect", &intent.intended_effect, 1_000) -} - -fn validate_bounded_text(label: &str, value: &str, max_chars: usize) -> Result<(), KernelError> { - if value.trim().is_empty() - || value.chars().count() > max_chars - || value - .chars() - .any(|character| character.is_control() && !matches!(character, '\n' | '\r' | '\t')) - { - return Err(KernelError::Invalid(format!( - "{label} must contain 1 to {max_chars} readable characters" - ))); - } - Ok(()) -} - -fn apply_individuation( - campaign: &mut Campaign, - individuation: &GestaltIndividuation, -) -> Result<(), KernelError> { - let mut member = individuation.member.clone(); - member.id = crate::domain::canonical_gestalt_member_local_id(&member.id); - let canonical = GestaltIndividuation { - member: member.clone(), - ..individuation.clone() - }; - crate::resolution::validate_gestalt_individuation(campaign, &canonical) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - campaign - .gestalt_members - .insert(member.id.clone(), member.clone()); - apply_promotion( - campaign, - &GestaltPromotion { - gestalt_id: individuation.gestalt_id.clone(), - expected_gestalt_version: individuation.expected_gestalt_version, - member_id: member.id.clone(), - expected_member_version: 0, - location_id: individuation.location_id.clone(), - }, - ) -} - -fn apply_promotion( - campaign: &mut Campaign, - promotion: &GestaltPromotion, -) -> Result<(), KernelError> { - if !campaign.locations.contains_key(&promotion.location_id) { - return Err(KernelError::Invalid( - "materialization location is unknown".into(), - )); - } - crate::resolution::validate_active_gestalt_presence_location( - campaign, - &promotion.gestalt_id, - &promotion.location_id, - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let gestalt = campaign - .gestalts - .get(&promotion.gestalt_id) - .ok_or_else(|| KernelError::Invalid("gestalt is unknown".into()))? - .clone(); - if gestalt.version != promotion.expected_gestalt_version { - return Err(KernelError::Invalid("gestalt snapshot is stale".into())); - } - let member_location = - crate::resolution::dormant_member_location(campaign, &promotion.member_id) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - if member_location != promotion.location_id { - return Err(KernelError::Invalid( - "gestalt member cannot materialize outside their exact location".into(), - )); - } - let member = campaign - .gestalt_members - .get(&promotion.member_id) - .ok_or_else(|| KernelError::Invalid("gestalt member is unknown".into()))?; - if member.gestalt_id != promotion.gestalt_id - || member.version != promotion.expected_member_version - { - return Err(KernelError::Invalid( - "member snapshot is stale or belongs to another gestalt".into(), - )); - } - if member.materialized_actor_id.is_some() { - return Err(KernelError::Invalid( - "gestalt member is already materialized".into(), - )); - } - let actor_id = crate::domain::gestalt_member_subject_id(&member.id); - if crate::resolution::canonical_subject_id_is_occupied_except_member( - campaign, - &actor_id, - Some(&promotion.member_id), - ) { - return Err(KernelError::Invalid( - "materialized actor id collides with an established canonical subject identity".into(), - )); - } - let member = campaign - .gestalt_members - .get_mut(&promotion.member_id) - .ok_or_else(|| KernelError::Invalid("gestalt member is unknown".into()))?; - let actor = materialize_actor(&gestalt, member, &actor_id, &promotion.location_id); - member.materialized_actor_id = Some(actor_id.clone()); - member.last_location_id = Some(promotion.location_id.clone()); - member.last_relevant_revision = campaign.revision; - member.relevance_lease_until_revision = campaign - .revision - .saturating_add(GESTALT_RELEVANCE_LEASE_REVISIONS); - member.version += 1; - campaign.actors.insert(actor_id, actor); - Ok(()) -} - -fn apply_demotion(campaign: &mut Campaign, demotion: &GestaltDemotion) -> Result<(), KernelError> { - let actor = campaign - .actors - .get(&demotion.actor_id) - .ok_or_else(|| KernelError::Invalid("materialized actor is unknown".into()))? - .clone(); - let member_id = campaign - .gestalt_members - .values() - .find(|member| member.materialized_actor_id.as_deref() == Some(demotion.actor_id.as_str())) - .map(|member| member.id.clone()) - .ok_or_else(|| KernelError::Invalid("actor is not a materialized gestalt member".into()))?; - if actor.location_id == campaign.actors[&campaign.player_actor_id].location_id { - return Err(KernelError::Invalid( - "a visible gestalt member remains individually relevant".into(), - )); - } - if campaign.gestalt_members[&member_id].relevance_lease_until_revision > campaign.revision { - return Err(KernelError::Invalid( - "gestalt member relevance lease has not expired".into(), - )); - } - let gestalt_id = campaign.gestalt_members[&member_id].gestalt_id.clone(); - let gestalt = campaign - .gestalts - .get(&gestalt_id) - .ok_or_else(|| KernelError::Invalid("gestalt is missing".into()))?; - let member = campaign - .gestalt_members - .get_mut(&member_id) - .expect("member exists"); - fold_actor_delta(&actor, gestalt, member); - member.materialized_actor_id = None; - member.version += 1; - campaign.actors.remove(&demotion.actor_id); - Ok(()) -} - -fn refresh_materialized_member_relevance<'a>( - campaign: &mut Campaign, - actor_ids: impl IntoIterator, -) { - let actor_ids = actor_ids.into_iter().collect::>(); - for member in campaign.gestalt_members.values_mut() { - if member - .materialized_actor_id - .as_deref() - .is_some_and(|actor_id| actor_ids.contains(actor_id)) - { - member.last_relevant_revision = campaign.revision; - member.relevance_lease_until_revision = campaign - .revision - .saturating_add(GESTALT_RELEVANCE_LEASE_REVISIONS); - member.version = member.version.saturating_add(1); - } - } -} - -fn validate_world_proposal( - actor: &ActorState, - proposal: &WorldActionProposal, -) -> Result<(), KernelError> { - if proposal.actor_id != actor.id - || proposal.intent.trim().is_empty() - || proposal.intended_effect.trim().is_empty() - { - return Err(KernelError::Invalid( - "world action proposal is malformed".into(), - )); - } - let allowed: BTreeSet = actor - .capabilities - .iter() - .map(|x| format!("capability:{x}")) - .chain(actor.knowledge.iter().map(|x| format!("knowledge:{x}"))) - .chain(actor.equipment.iter().map(|x| format!("equipment:{x}"))) - .chain(std::iter::once(format!("location:{}", actor.location_id))) - .collect(); - if proposal - .state_references - .iter() - .any(|reference| !allowed.contains(reference)) - { - return Err(KernelError::Invalid( - "world action proposal cites unearned state".into(), - )); - } - Ok(()) -} - -fn validate_reaction_identity_adoption( - campaign: &Campaign, - actor_id: &str, - identity: &str, -) -> Result<(), KernelError> { - let actor = campaign - .actors - .get(actor_id) - .ok_or_else(|| KernelError::Invalid("reaction actor is unknown".into()))?; - let identity = identity.trim().to_lowercase(); - if actor.name.trim().to_lowercase() == identity { - return Ok(()); - } - let local_collision = campaign.actors.values().any(|peer| { - peer.id != actor_id - && peer.location_id == actor.location_id - && peer.name.trim().to_lowercase() == identity - }); - let population_collision = campaign - .gestalt_members - .values() - .find(|member| member.materialized_actor_id.as_deref() == Some(actor_id)) - .is_some_and(|member| { - campaign.gestalt_members.values().any(|peer| { - peer.id != member.id - && peer.gestalt_id == member.gestalt_id - && peer.name.trim().to_lowercase() == identity - }) - }); - if local_collision || population_collision { - return Err(KernelError::Invalid( - "reaction identity adoption conflicts with an established local or population identity" - .into(), - )); - } - Ok(()) -} - -fn canonical_witnessed_turn<'a>( - campaign: &'a Campaign, - event_summary: &str, -) -> Result<&'a NarrativeTurn, KernelError> { - let event_summary = event_summary.trim(); - campaign - .transcript - .iter() - .rev() - .find(|turn| canonical_turn_text(turn) == event_summary) - .ok_or_else(|| { - KernelError::Invalid( - "reaction stimulus does not match a committed transcript turn".into(), - ) - }) -} - -fn canonical_turn_text(turn: &NarrativeTurn) -> String { - if turn.speaker == "world" { - turn.text.trim().to_owned() - } else { - format!("{} says: {}", turn.speaker, turn.text.trim()) - } -} - -fn overlay( - base: &BTreeSet, - add: &BTreeSet, - remove: &BTreeSet, -) -> BTreeSet { - base.difference(remove) - .cloned() - .chain(add.iter().cloned()) - .collect() -} -fn materialize_actor( - gestalt: &GestaltPersonaState, - member: &GestaltMemberDelta, - actor_id: &str, - location_id: &str, -) -> ActorState { - ActorState { - id: actor_id.into(), - name: member.name.clone(), - location_id: location_id.into(), - capabilities: overlay( - &gestalt.shared_capabilities, - &member.capability_additions, - &member.capability_removals, - ), - knowledge: overlay( - &gestalt.shared_knowledge, - &member.knowledge_additions, - &member.knowledge_removals, - ), - equipment: member.equipment.clone(), - conditions: member.conditions.clone(), - obligations: member.obligations.clone(), - relationships: member.relationships.clone(), - goals: if member.goals.is_empty() { - gestalt.goals.clone() - } else { - member.goals.clone() - }, - memories: member.memories.clone(), - } -} -fn fold_actor_delta( - actor: &ActorState, - gestalt: &GestaltPersonaState, - member: &mut GestaltMemberDelta, -) { - member.capability_additions = actor - .capabilities - .difference(&gestalt.shared_capabilities) - .cloned() - .collect(); - member.capability_removals = gestalt - .shared_capabilities - .difference(&actor.capabilities) - .cloned() - .collect(); - member.knowledge_additions = actor - .knowledge - .difference(&gestalt.shared_knowledge) - .cloned() - .collect(); - member.knowledge_removals = gestalt - .shared_knowledge - .difference(&actor.knowledge) - .cloned() - .collect(); - member.equipment = actor.equipment.clone(); - member.conditions = actor.conditions.clone(); - member.obligations = actor.obligations.clone(); - member.relationships = actor.relationships.clone(); - member.goals = actor.goals.clone(); - member.memories = actor.memories.clone(); - member.last_location_id = Some(actor.location_id.clone()); -} - -fn single_campaign_id(store: &CampaignStore) -> Result { - let keys = store.keys("campaign.v1").map_err(persist)?; - match keys.as_slice() { - [id] => Ok(id.clone()), - [] => Err(KernelError::NotFound), - _ => Err(KernelError::Invalid( - "a campaign store must contain exactly one campaign".into(), - )), - } -} - -fn require_revision(c: &Campaign, expected: u64) -> Result<(), KernelError> { - if c.revision == expected { - Ok(()) - } else { - Err(KernelError::Stale { - expected, - actual: c.revision, - }) - } -} - -fn validate_region_admission_evidence( - expansion: &RegionExpansion, - evidence_receipts: &[VaultEvidenceReceipt], - canon_candidates: &[CanonCandidate], -) -> Result<(), KernelError> { - let supplied_evidence = evidence_receipts - .iter() - .map(|receipt| receipt.id.as_str()) - .collect::>(); - let missing_profile_evidence = expansion - .population_profiles - .iter() - .chain(expansion.institution_profiles.iter()) - .any(|profile| { - profile - .evidence_receipt_ids - .iter() - .any(|id| !supplied_evidence.contains(id.as_str())) - }); - let missing_relation_evidence = expansion - .migration_relations - .iter() - .chain(expansion.local_relations.iter()) - .any(|relation| { - relation - .evidence_receipt_ids - .iter() - .any(|id| !supplied_evidence.contains(id.as_str())) - }); - if expansion.facts.iter().any(|fact| { - fact.evidence_receipt_ids - .iter() - .any(|id| !supplied_evidence.contains(id.as_str())) - }) || missing_profile_evidence - || missing_relation_evidence - || canon_candidates.iter().any(|candidate| { - candidate - .evidence_receipt_ids - .iter() - .any(|id| !supplied_evidence.contains(id.as_str())) - }) - { - return Err(KernelError::Invalid( - "region admission evidence receipts were not supplied".into(), - )); - } - Ok(()) -} - -fn is_human_controlled_actor(campaign: &Campaign, actor_id: &str) -> bool { - actor_id == campaign.player_actor_id - || campaign - .agency_profiles - .get(actor_id) - .is_some_and(|profile| !profile.simulation_eligible) -} - -fn require_resolution_epoch(c: &Campaign, expected: u64) -> Result<(), KernelError> { - if c.resolution_policy.resolution_epoch != expected { - return Err(KernelError::Invalid(format!( - "stale resolution epoch: expected {expected}, actual {}", - c.resolution_policy.resolution_epoch - ))); - } - Ok(()) -} - -fn assess(c: &Campaign, intent: ActionIntent) -> ActionAssessment { - let actor = c.actors.get(&intent.actor_id); - let admissible = actor.is_some() && !intent.description.trim().is_empty(); - let missing = if actor.is_none() { - Some("actor does not exist in this branch".into()) - } else if intent.description.trim().is_empty() { - Some("no attempt was described".into()) - } else { - None - }; - let modifiers = vec![]; - let modifier_total = capped_modifier(modifiers.iter().map(|m: &ContextModifier| m.value)); - let mut a = ActionAssessment { - schema: "ghostlight.player_action_assessment.v1".into(), - campaign_id: c.id, - revision: c.revision, - intent, - admissible, - missing_permission: missing, - dc: 15, - modifiers, - modifier_total, - effect_ceiling: - "A bounded local consequence; no unsupported world fact or custody transfer.".into(), - success_stake: "The intended local effect succeeds and the world reacts.".into(), - mixed_stake: "The effect lands with the previewed cost or complication.".into(), - failure_stake: "Opposition holds and gains a concrete advantage.".into(), - strong_effect: WorldEffectDelta::default(), - success_effect: WorldEffectDelta::default(), - mixed_effect: WorldEffectDelta::default(), - failure_effect: WorldEffectDelta::default(), - bargains: if admissible { - vec![] - } else { - vec![ - "Narrow the effect, obtain access, recruit help, or accept a concrete sacrifice." - .into(), - ] - }, - expires_at: Utc::now() + Duration::minutes(10), - digest: String::new(), - }; - let bytes = rmp_serde::to_vec_named(&a).expect("assessment serializes"); - a.digest = format!("sha256:{:x}", Sha256::digest(bytes)); - a -} - -#[derive(Debug)] -struct AppliedStrategicTickPlan { - events: Vec, - mutation: Option<( - crate::legacy_transition::LoweredLegacyTransition, - crate::transition::WorldMutationReceipt, - )>, -} - -impl std::ops::Deref for AppliedStrategicTickPlan { - type Target = [Event]; - - fn deref(&self) -> &Self::Target { - &self.events - } -} - -fn merge_strategic_outcome_event_context( - contexts: &mut BTreeMap, Vec)>, - action_digest: &str, - subject_id: &str, - location_ids: &[String], - public_channels: &[String], -) -> Result<(), KernelError> { - let entry = contexts - .entry(action_digest.to_owned()) - .or_insert_with(|| (subject_id.to_owned(), Vec::new(), Vec::new())); - if entry.0 != subject_id { - return Err(KernelError::Invalid( - "one strategic action digest cannot belong to multiple subjects".into(), - )); - } - entry.1.extend(location_ids.iter().cloned()); - entry.1.sort(); - entry.1.dedup(); - entry.2.extend(public_channels.iter().cloned()); - entry.2.sort(); - entry.2.dedup(); - Ok(()) -} - -fn strategic_activity_phase( - campaign: &Campaign, - prospective_actor_locations: &BTreeMap, - prospective_gestalt_locations: &BTreeMap, - prospective_member_locations: &BTreeMap, - subject_id: &str, - location_ids: &[String], -) -> Result { - let (origin, destination) = if let Some(actor) = campaign.actors.get(subject_id) { - ( - actor.location_id.as_str(), - prospective_actor_locations - .get(subject_id) - .map(String::as_str), - ) - } else if let Some(gestalt) = campaign.gestalts.get(subject_id) { - ( - gestalt.home_location_id.as_str(), - prospective_gestalt_locations - .get(subject_id) - .map(String::as_str), - ) - } else if let Some(member_id) = subject_id.strip_prefix("member:") { - let origin = crate::resolution::dormant_member_location(campaign, member_id) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - return Ok(relative_activity_phase( - &origin, - prospective_member_locations - .get(member_id) - .map(String::as_str), - location_ids, - )); - } else { - return Ok(1); - }; - Ok(relative_activity_phase(origin, destination, location_ids)) -} - -fn relative_activity_phase(origin: &str, destination: Option<&str>, location_ids: &[String]) -> u8 { - let Some(destination) = destination.filter(|destination| *destination != origin) else { - return 1; - }; - if location_ids.is_empty() || location_ids.iter().all(|location| location == origin) { - 0 - } else if location_ids.iter().all(|location| location == destination) { - 2 - } else { - 1 - } -} - -fn apply_strategic_tick_plan( - campaign: &mut Campaign, - plan: crate::domain::StrategicTickPlan, -) -> Result { - let plan = if plan.selected_actions.is_empty() { - plan - } else { - let activity_outcomes = plan.activity_outcomes; - let mut projected = - crate::resolution::project_selected_actions(campaign, plan.selected_actions) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - projected.activity_outcomes = activity_outcomes; - projected - }; - crate::outcome::validate_plan_activity_outcomes(campaign, &plan) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let canonical_composition = !plan.selected_actions.is_empty(); - let activity_means = plan - .selected_actions - .iter() - .map(|action| { - crate::resolution::cell_action_digest(action) - .map(|digest| (digest, action.intended_effect.clone())) - .map_err(|error| KernelError::Invalid(error.to_string())) - }) - .collect::, _>>()?; - let prospective_actor_locations = plan - .actor_moves - .iter() - .map(|action| (action.actor_id.clone(), action.destination_id.clone())) - .collect::>(); - let prospective_gestalt_locations = plan - .gestalt_migrations - .iter() - .map(|action| { - ( - action.gestalt_id.clone(), - action.destination_location_id.clone(), - ) - }) - .collect::>(); - let prospective_member_locations = plan - .member_migrations - .iter() - .map(|action| { - ( - action.member_id.clone(), - action.destination_location_id.clone(), - ) - }) - .collect::>(); - let lowering_plan = plan.clone(); - let activity_outcomes = plan.activity_outcomes.clone(); - let mut outcome_event_context: BTreeMap, Vec)> = - BTreeMap::new(); - for activity in &plan.gestalt_activities { - merge_strategic_outcome_event_context( - &mut outcome_event_context, - &activity.action_digest, - &activity.gestalt_id, - &activity.location_ids, - &activity.public_channels, - )?; - } - for activity in &plan.actor_activities { - merge_strategic_outcome_event_context( - &mut outcome_event_context, - &activity.action_digest, - &activity.actor_id, - &activity.location_ids, - &activity.public_channels, - )?; - } - for activity in &plan.member_activities { - merge_strategic_outcome_event_context( - &mut outcome_event_context, - &activity.action_digest, - &crate::domain::gestalt_member_subject_id(&activity.member_id), - &activity.location_ids, - &activity.public_channels, - )?; - } - // Every action in a strategic wave was chosen against the same committed - // snapshot. Keep that snapshot immutable while applying to a private copy - // so action ordering cannot rewrite another action's permissions and an - // invalid late action cannot leave this primitive partially mutated. - let mut next = campaign.clone(); - let revision = campaign.revision + 1; - let at = campaign.world_time + Duration::hours(i64::from(campaign.tick_hours)); - let mut events = Vec::new(); - let mut event_phases = BTreeMap::new(); - let mut seen_institutions = BTreeSet::new(); - for action in plan.institution_actions { - if !seen_institutions.insert(action.institution_id.clone()) { - return Err(KernelError::Invalid( - "institution acts twice in one strategic tick".into(), - )); - } - if action.posture.trim().is_empty() { - return Err(KernelError::Invalid( - "strategic institution posture is empty".into(), - )); - } - if action.posture.chars().count() > MAX_POSTURE_CHARS { - return Err(KernelError::Invalid(format!( - "strategic institution posture exceeds {MAX_POSTURE_CHARS} characters" - ))); - } - if action - .location_ids - .iter() - .any(|id| !campaign.locations.contains_key(id)) - { - return Err(KernelError::Invalid( - "strategic institution action invented a location".into(), - )); - } - validate_public_channels(&action.public_channels)?; - let institution = campaign - .institutions - .get(&action.institution_id) - .ok_or_else(|| KernelError::Invalid("strategic plan invented an institution".into()))?; - if !crate::resolution::substantive_text_change(&institution.posture, &action.posture) { - return Err(KernelError::Invalid( - "strategic institution action would not change its posture".into(), - )); - } - let summary = format!( - "{} announces a new course: {}", - institution.name, action.posture - ); - events.push(crate::domain::Event { - id: format!("strategic:{revision}:institution:{}", institution.id), - at, - kind: "institution_action".into(), - summary, - actor_ids: vec![], - institution_ids: vec![institution.id.clone()], - gestalt_ids: vec![], - location_ids: action.location_ids, - public_channels: action.public_channels, - }); - } - - let mut legacy_seen_gestalts = BTreeSet::new(); - let mut seen_gestalt_pressures = BTreeSet::new(); - for action in plan.gestalt_actions { - if !seen_gestalt_pressures.insert(action.gestalt_id.clone()) - || (!canonical_composition && !legacy_seen_gestalts.insert(action.gestalt_id.clone())) - { - return Err(KernelError::Invalid( - "gestalt acts twice in one strategic tick".into(), - )); - } - validate_public_channels(&action.public_channels)?; - let gestalt = campaign - .gestalts - .get(&action.gestalt_id) - .ok_or_else(|| KernelError::Invalid("strategic plan invented a gestalt".into()))?; - crate::resolution::validate_gestalt_pressure_transition( - &gestalt.pressures, - &action.pressure_additions, - &action.pressure_resolutions, - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mut summary_parts = Vec::new(); - if !action.pressure_resolutions.is_empty() { - summary_parts.push(format!( - "A declaration from {} marks this matter settled: {}", - gestalt.name, - action.pressure_resolutions.join("; ") - )); - } - if !action.pressure_additions.is_empty() { - summary_parts.push(format!( - "New public demand from {}: {}", - gestalt.name, - action.pressure_additions.join("; ") - )); - } - events.push(crate::domain::Event { - id: format!("strategic:{revision}:gestalt:{}", gestalt.id), - at, - kind: "gestalt_action".into(), - summary: summary_parts.join("; "), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![gestalt.id.clone()], - location_ids: vec![gestalt.home_location_id.clone()], - public_channels: action.public_channels, - }); - } - - let mut seen_gestalt_migrations = BTreeSet::new(); - for action in &plan.gestalt_migrations { - if !seen_gestalt_migrations.insert(action.gestalt_id.clone()) - || (!canonical_composition && !legacy_seen_gestalts.insert(action.gestalt_id.clone())) - { - return Err(KernelError::Invalid( - "gestalt acts twice in one strategic tick".into(), - )); - } - validate_public_channels(&action.public_channels)?; - crate::resolution::validate_gestalt_migration( - campaign, - &action.gestalt_id, - &action.destination_gestalt_id, - &action.destination_location_id, - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - } - for action in plan.gestalt_migrations { - let origin = campaign.gestalts[&action.gestalt_id] - .home_location_id - .clone(); - let origin_name = campaign - .locations - .get(&origin) - .ok_or_else(|| KernelError::Invalid("gestalt migration origin is missing".into()))? - .name - .clone(); - let gestalt_name = campaign.gestalts[&action.gestalt_id].name.clone(); - let destination_location_name = campaign - .locations - .get(&action.destination_location_id) - .ok_or_else(|| KernelError::Invalid("gestalt migration destination is missing".into()))? - .name - .clone(); - let destination_name = campaign.gestalts[&action.destination_gestalt_id] - .name - .clone(); - events.push(crate::domain::Event { - id: format!( - "strategic:{revision}:gestalt-migration:{}", - action.gestalt_id - ), - at, - kind: "gestalt_migration".into(), - summary: format!( - "{gestalt_name} relocates from {origin_name} to {destination_location_name} near {destination_name}." - ), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![action.gestalt_id, action.destination_gestalt_id], - location_ids: vec![origin, action.destination_location_id], - public_channels: action.public_channels, - }); - } - - let mut seen_gestalt_activities = BTreeSet::new(); - for action in plan.gestalt_activities { - let gestalt = campaign - .gestalts - .get(&action.gestalt_id) - .ok_or_else(|| KernelError::Invalid("strategic plan invented a gestalt".into()))?; - let locations = if action.location_ids.is_empty() { - vec![gestalt.home_location_id.clone()] - } else { - action.location_ids.clone() - }; - if !seen_gestalt_activities.insert(( - action.gestalt_id.clone(), - strategic_activity_scope_key(&action.activity, &action.target_subject_ids, &locations), - )) || (!canonical_composition && !legacy_seen_gestalts.insert(action.gestalt_id.clone())) - { - return Err(KernelError::Invalid( - "gestalt acts twice in one strategic tick".into(), - )); - } - validate_public_channels(&action.public_channels)?; - let profile = campaign - .agency_profiles - .get(&action.gestalt_id) - .ok_or_else(|| KernelError::Invalid("strategic gestalt lacks agency scope".into()))?; - let allowed_targets = - crate::resolution::strategic_activity_targets(campaign, &action.gestalt_id); - let unique_targets = action.target_subject_ids.iter().collect::>(); - let unique_locations = action.location_ids.iter().collect::>(); - let needs_target = action.activity.requires_explicit_target_for_gestalt(); - if action.target_subject_ids.len() > 4 - || unique_targets.len() != action.target_subject_ids.len() - || action - .target_subject_ids - .iter() - .any(|target| !allowed_targets.contains(target)) - || (needs_target && action.target_subject_ids.is_empty()) - || action.location_ids.len() > 4 - || unique_locations.len() != action.location_ids.len() - || action.location_ids.iter().any(|location| { - !profile.location_ids.contains(location) - && prospective_gestalt_locations.get(&action.gestalt_id) != Some(location) - }) - { - return Err(KernelError::Invalid( - "strategic gestalt activity exceeds exact graph or location scope".into(), - )); - } - let target_names = action - .target_subject_ids - .iter() - .map(|target| agency_subject_name(campaign, target)) - .collect::, _>>()?; - let institution_ids = action - .target_subject_ids - .iter() - .filter(|target| campaign.institutions.contains_key(*target)) - .cloned() - .collect(); - let actor_ids = action - .target_subject_ids - .iter() - .filter(|target| { - campaign.actors.contains_key(*target) - || target - .strip_prefix("member:") - .is_some_and(|member_id| campaign.gestalt_members.contains_key(member_id)) - }) - .cloned() - .collect(); - let mut gestalt_ids = vec![action.gestalt_id.clone()]; - gestalt_ids.extend( - action - .target_subject_ids - .iter() - .filter(|target| campaign.gestalts.contains_key(*target)) - .cloned(), - ); - let phase = strategic_activity_phase( - campaign, - &prospective_actor_locations, - &prospective_gestalt_locations, - &prospective_member_locations, - &action.gestalt_id, - &locations, - )?; - let scope_digest = strategic_activity_scope_digest( - &action.activity, - &action.target_subject_ids, - &locations, - ); - let event = crate::domain::Event { - id: format!( - "strategic:{revision}:gestalt-activity:{}:{}:{scope_digest}", - action.gestalt_id, - strategic_activity_id(&action.activity), - ), - at, - kind: "gestalt_activity".into(), - summary: strategic_activity_summary( - &gestalt.name, - &action.activity, - &target_names, - activity_means - .get(&action.action_digest) - .map(String::as_str), - &action.public_channels, - ), - actor_ids, - institution_ids, - gestalt_ids, - location_ids: locations, - public_channels: action.public_channels, - }; - event_phases.insert(event.id.clone(), phase); - events.push(event); - } - - let mut legacy_seen_actors = BTreeSet::new(); - let mut seen_actor_moves = BTreeSet::new(); - for action in plan.actor_moves { - if !seen_actor_moves.insert(action.actor_id.clone()) - || (!canonical_composition && !legacy_seen_actors.insert(action.actor_id.clone())) - { - return Err(KernelError::Invalid( - "actor moves twice in one strategic tick".into(), - )); - } - if is_human_controlled_actor(campaign, &action.actor_id) { - return Err(KernelError::Invalid( - "strategic simulation cannot puppet a human-controlled actor".into(), - )); - } - validate_public_channels(&action.public_channels)?; - let actor = campaign - .actors - .get(&action.actor_id) - .ok_or_else(|| KernelError::Invalid("strategic plan invented an actor".into()))?; - let route = campaign - .locations - .get(&actor.location_id) - .and_then(|location| { - location - .routes - .values() - .find(|route| route.destination_id == action.destination_id) - }) - .ok_or_else(|| { - KernelError::Invalid("strategic actor movement has no direct route".into()) - })?; - if route.travel_minutes > campaign.tick_hours.saturating_mul(60) { - return Err(KernelError::Invalid( - "strategic actor movement exceeds the tick duration".into(), - )); - } - let origin = actor.location_id.clone(); - let actor_name = actor.name.clone(); - let origin_name = campaign - .locations - .get(&origin) - .ok_or_else(|| KernelError::Invalid("actor movement origin is missing".into()))? - .name - .clone(); - let destination_name = campaign - .locations - .get(&action.destination_id) - .ok_or_else(|| KernelError::Invalid("actor movement destination is missing".into()))? - .name - .clone(); - events.push(crate::domain::Event { - id: format!("strategic:{revision}:actor:{}", action.actor_id), - at, - kind: "actor_movement".into(), - summary: format!("{actor_name} moves from {origin_name} to {destination_name}."), - actor_ids: vec![action.actor_id], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec![origin, action.destination_id], - public_channels: action.public_channels, - }); - } - - let mut seen_actor_activities = BTreeSet::new(); - for action in plan.actor_activities { - if !seen_actor_activities.insert(( - action.actor_id.clone(), - strategic_activity_scope_key( - &action.activity, - &action.target_subject_ids, - &action.location_ids, - ), - )) || (!canonical_composition && !legacy_seen_actors.insert(action.actor_id.clone())) - { - return Err(KernelError::Invalid( - "actor acts twice in one strategic tick".into(), - )); - } - if is_human_controlled_actor(campaign, &action.actor_id) { - return Err(KernelError::Invalid( - "strategic simulation cannot puppet a human-controlled actor".into(), - )); - } - validate_public_channels(&action.public_channels)?; - let actor = campaign - .actors - .get(&action.actor_id) - .ok_or_else(|| KernelError::Invalid("strategic plan invented an actor".into()))?; - let allowed_targets = - crate::resolution::strategic_activity_targets(campaign, &action.actor_id); - let unique_targets = action.target_subject_ids.iter().collect::>(); - let needs_target = !action.activity.allows_targetless_local_attempt(); - if action.target_subject_ids.len() > 4 - || unique_targets.len() != action.target_subject_ids.len() - || action - .target_subject_ids - .iter() - .any(|target| !allowed_targets.contains(target)) - || (needs_target && action.target_subject_ids.is_empty()) - || action.location_ids.len() != 1 - || (action.location_ids[0] != actor.location_id - && prospective_actor_locations.get(&action.actor_id) != action.location_ids.first()) - { - return Err(KernelError::Invalid( - "strategic actor activity exceeds exact graph or location scope".into(), - )); - } - let target_names = action - .target_subject_ids - .iter() - .map(|target| agency_subject_name(campaign, target)) - .collect::, _>>()?; - let institution_ids = action - .target_subject_ids - .iter() - .filter(|target| campaign.institutions.contains_key(*target)) - .cloned() - .collect(); - let mut actor_ids = vec![action.actor_id.clone()]; - actor_ids.extend( - action - .target_subject_ids - .iter() - .filter(|target| { - campaign.actors.contains_key(*target) - || target.strip_prefix("member:").is_some_and(|member_id| { - campaign.gestalt_members.contains_key(member_id) - }) - }) - .cloned(), - ); - actor_ids.sort(); - actor_ids.dedup(); - let mut gestalt_ids = action - .target_subject_ids - .iter() - .filter(|target| campaign.gestalts.contains_key(*target)) - .cloned() - .collect::>(); - gestalt_ids.sort(); - gestalt_ids.dedup(); - let phase = strategic_activity_phase( - campaign, - &prospective_actor_locations, - &prospective_gestalt_locations, - &prospective_member_locations, - &action.actor_id, - &action.location_ids, - )?; - let scope_digest = strategic_activity_scope_digest( - &action.activity, - &action.target_subject_ids, - &action.location_ids, - ); - let event = Event { - id: format!( - "strategic:{revision}:actor-activity:{}:{}:{scope_digest}", - action.actor_id, - strategic_activity_id(&action.activity), - ), - at, - kind: "actor_activity".into(), - summary: strategic_activity_summary( - &actor.name, - &action.activity, - &target_names, - activity_means - .get(&action.action_digest) - .map(String::as_str), - &action.public_channels, - ), - actor_ids, - institution_ids, - gestalt_ids, - location_ids: action.location_ids, - public_channels: action.public_channels, - }; - event_phases.insert(event.id.clone(), phase); - events.push(event); - } - - let mut legacy_seen_members = BTreeSet::new(); - let mut seen_member_activities = BTreeSet::new(); - for action in plan.member_activities { - if !seen_member_activities.insert(( - action.member_id.clone(), - strategic_activity_scope_key( - &action.activity, - &action.target_subject_ids, - &action.location_ids, - ), - )) || (!canonical_composition && !legacy_seen_members.insert(action.member_id.clone())) - { - return Err(KernelError::Invalid( - "gestalt member acts twice in one strategic tick".into(), - )); - } - validate_public_channels(&action.public_channels)?; - let member = campaign - .gestalt_members - .get(&action.member_id) - .filter(|member| { - member.materialized_actor_id.is_none() - && member.gestalt_id == action.source_gestalt_id - }) - .ok_or_else(|| { - KernelError::Invalid("strategic member activity has stale identity scope".into()) - })?; - let allowed_targets = - crate::resolution::member_activity_targets(campaign, &action.member_id) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let exact_location = - crate::resolution::dormant_member_location(campaign, &action.member_id) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let unique_targets = action.target_subject_ids.iter().collect::>(); - let needs_target = !action.activity.allows_targetless_local_attempt(); - if action.target_subject_ids.len() > 4 - || unique_targets.len() != action.target_subject_ids.len() - || action - .target_subject_ids - .iter() - .any(|target| !allowed_targets.contains(target)) - || (needs_target && action.target_subject_ids.is_empty()) - || action.location_ids.len() != 1 - || (action.location_ids[0] != exact_location - && prospective_member_locations.get(&action.member_id) - != action.location_ids.first()) - { - return Err(KernelError::Invalid( - "strategic member activity exceeds exact graph or location scope".into(), - )); - } - let target_names = action - .target_subject_ids - .iter() - .map(|target| agency_subject_name(campaign, target)) - .collect::, _>>()?; - let institution_ids = action - .target_subject_ids - .iter() - .filter(|target| campaign.institutions.contains_key(*target)) - .cloned() - .collect(); - let mut actor_ids = vec![crate::domain::gestalt_member_subject_id(&action.member_id)]; - actor_ids.extend( - action - .target_subject_ids - .iter() - .filter(|target| { - campaign.actors.contains_key(*target) - || target.strip_prefix("member:").is_some_and(|member_id| { - campaign.gestalt_members.contains_key(member_id) - }) - }) - .cloned(), - ); - actor_ids.sort(); - actor_ids.dedup(); - let mut gestalt_ids = vec![action.source_gestalt_id.clone()]; - gestalt_ids.extend( - action - .target_subject_ids - .iter() - .filter(|target| campaign.gestalts.contains_key(*target)) - .cloned(), - ); - gestalt_ids.sort(); - gestalt_ids.dedup(); - let phase = strategic_activity_phase( - campaign, - &prospective_actor_locations, - &prospective_gestalt_locations, - &prospective_member_locations, - &crate::domain::gestalt_member_subject_id(&action.member_id), - &action.location_ids, - )?; - let scope_digest = strategic_activity_scope_digest( - &action.activity, - &action.target_subject_ids, - &action.location_ids, - ); - let event = Event { - id: format!( - "strategic:{revision}:member-activity:{}:{}:{scope_digest}", - action.member_id, - strategic_activity_id(&action.activity), - ), - at, - kind: "gestalt_member_activity".into(), - summary: strategic_activity_summary( - &member.name, - &action.activity, - &target_names, - activity_means - .get(&action.action_digest) - .map(String::as_str), - &action.public_channels, - ), - actor_ids, - institution_ids, - gestalt_ids, - location_ids: action.location_ids, - public_channels: action.public_channels, - }; - event_phases.insert(event.id.clone(), phase); - events.push(event); - } - let mut seen_member_migrations = BTreeSet::new(); - for action in plan.member_migrations { - if !seen_member_migrations.insert(action.member_id.clone()) - || (!canonical_composition && !legacy_seen_members.insert(action.member_id.clone())) - { - return Err(KernelError::Invalid( - "gestalt member migrates twice in one strategic tick".into(), - )); - } - validate_public_channels(&action.public_channels)?; - crate::resolution::validate_member_migration( - campaign, - &action.member_id, - &action.source_gestalt_id, - &action.destination_gestalt_id, - &action.destination_location_id, - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let origin = campaign.gestalt_members[&action.member_id] - .last_location_id - .clone() - .unwrap_or_else(|| { - campaign.gestalts[&action.source_gestalt_id] - .home_location_id - .clone() - }); - let member_name = campaign.gestalt_members[&action.member_id].name.clone(); - let origin_name = campaign - .locations - .get(&origin) - .ok_or_else(|| KernelError::Invalid("member migration origin is missing".into()))? - .name - .clone(); - let destination_location_name = campaign - .locations - .get(&action.destination_location_id) - .ok_or_else(|| KernelError::Invalid("member migration destination is missing".into()))? - .name - .clone(); - let destination_gestalt_name = campaign.gestalts[&action.destination_gestalt_id] - .name - .clone(); - events.push(crate::domain::Event { - id: format!("strategic:{revision}:member:{}", action.member_id), - at, - kind: "gestalt_member_migration".into(), - summary: format!( - "{member_name} moves from {origin_name} to {destination_location_name} and joins {destination_gestalt_name}." - ), - actor_ids: vec![crate::domain::gestalt_member_subject_id(&action.member_id)], - institution_ids: vec![], - gestalt_ids: vec![action.source_gestalt_id, action.destination_gestalt_id], - location_ids: vec![origin, action.destination_location_id], - public_channels: action.public_channels, - }); - } - let plan_digest = crate::legacy_transition::digest_serializable(&lowering_plan) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mutation = crate::legacy_transition::lower_strategic_wave( - campaign, - &lowering_plan, - &format!("strategic-wave:{plan_digest}"), - Utc::now() + Duration::minutes(5), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))? - .map(|transition| { - let receipt = - crate::legacy_transition::apply_lowered_transition(&mut next, &transition, Utc::now()) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - Ok::<_, KernelError>((transition, receipt)) - }) - .transpose()?; - for outcome in activity_outcomes { - let (source_subject_id, locations, public_channels) = outcome_event_context - .remove(&outcome.action_digest) - .ok_or_else(|| { - KernelError::Invalid("strategic outcome lost its activity context".into()) - })?; - if matches!( - &outcome.effect, - crate::domain::StrategicOutcomeEffect::NoMaterialChange { .. } - ) { - continue; - } - let mut subject_ids = BTreeSet::from([source_subject_id.clone()]); - collect_outcome_subject_ids(&outcome.effect, &mut subject_ids); - let mut actor_ids = Vec::new(); - let mut institution_ids = Vec::new(); - let mut gestalt_ids = Vec::new(); - for subject_id in subject_ids { - if let Some(member_id) = subject_id.strip_prefix("member:") { - actor_ids.push(subject_id.clone()); - if let Some(member) = next.gestalt_members.get(member_id) { - gestalt_ids.push(member.gestalt_id.clone()); - } - } else if next.actors.contains_key(&subject_id) { - actor_ids.push(subject_id); - } else if next.institutions.contains_key(&subject_id) { - institution_ids.push(subject_id); - } else if next.gestalts.contains_key(&subject_id) { - gestalt_ids.push(subject_id); - } - } - actor_ids.sort(); - actor_ids.dedup(); - institution_ids.sort(); - institution_ids.dedup(); - gestalt_ids.sort(); - gestalt_ids.dedup(); - let digest_suffix = outcome - .action_digest - .strip_prefix("sha256:") - .unwrap_or(&outcome.action_digest) - .chars() - .take(16) - .collect::(); - let phase = strategic_activity_phase( - campaign, - &prospective_actor_locations, - &prospective_gestalt_locations, - &prospective_member_locations, - &source_subject_id, - &locations, - )?; - let event = Event { - id: format!("strategic:{revision}:activity-outcome:{digest_suffix}"), - at, - kind: "strategic_activity_outcome".into(), - summary: outcome.summary, - actor_ids, - institution_ids, - gestalt_ids, - location_ids: locations, - public_channels, - }; - event_phases.insert(event.id.clone(), phase); - events.push(event); - } - events.sort_by_key(|event| event_phases.get(&event.id).copied().unwrap_or(1)); - *campaign = next; - Ok(AppliedStrategicTickPlan { events, mutation }) -} - -fn collect_outcome_subject_ids( - effect: &crate::domain::StrategicOutcomeEffect, - subjects: &mut BTreeSet, -) { - use crate::domain::StrategicOutcomeEffect; - match effect { - StrategicOutcomeEffect::NoMaterialChange { .. } => {} - StrategicOutcomeEffect::ResourceCreated { - owner_subject_id, .. - } - | StrategicOutcomeEffect::ResourceConsumed { - owner_subject_id, .. - } - | StrategicOutcomeEffect::KnowledgeLearned { - owner_subject_id, .. - } => { - subjects.insert(owner_subject_id.clone()); - } - StrategicOutcomeEffect::ResourceTransferred { - from_subject_id, - to_subject_id, - .. - } => { - subjects.insert(from_subject_id.clone()); - subjects.insert(to_subject_id.clone()); - } - StrategicOutcomeEffect::KnowledgeCommunicated { - from_subject_id, - to_subject_ids, - .. - } => { - subjects.insert(from_subject_id.clone()); - subjects.extend(to_subject_ids.iter().cloned()); - } - StrategicOutcomeEffect::GestaltPressure { gestalt_id, .. } => { - subjects.insert(gestalt_id.clone()); - } - StrategicOutcomeEffect::AgencyRelationShift { .. } => {} - StrategicOutcomeEffect::MemberMemory { member_id, .. } - | StrategicOutcomeEffect::MemberObligation { member_id, .. } - | StrategicOutcomeEffect::MemberRelationship { member_id, .. } => { - subjects.insert(crate::domain::gestalt_member_subject_id(member_id)); - if let StrategicOutcomeEffect::MemberRelationship { - other_subject_id, .. - } = effect - { - subjects.insert(other_subject_id.clone()); - } - } - } -} - -fn strategic_activity_summary( - source_name: &str, - activity: &StrategicActivityKind, - target_names: &[String], - admitted_means: Option<&str>, - public_channels: &[String], -) -> String { - if let Some(means) = admitted_means - .map(str::trim) - .filter(|means| !means.is_empty()) - { - let means = means.trim_end_matches(['.', '!', '?']); - if !public_channels.is_empty() { - return format!("Public statement from {source_name}: {means}."); - } - let mut characters = means.chars(); - let lowered = characters - .next() - .map(|first| first.to_lowercase().chain(characters).collect::()) - .unwrap_or_default(); - if let Some(rest) = lowered.strip_prefix("attempt to ") { - return format!("{source_name} attempts to {rest}."); - } - if let Some(rest) = lowered.strip_prefix("attempt ") { - return format!("{source_name} attempts {rest}."); - } - return format!("{source_name} attempts to {lowered}."); - } - let targets = target_names.join(", "); - match (activity, target_names.is_empty()) { - (StrategicActivityKind::Prepare, true) => { - format!("{source_name} undertakes preparations.") - } - (StrategicActivityKind::Prepare, false) => { - format!("{source_name} undertakes preparations concerning {targets}.") - } - (StrategicActivityKind::Coordinate, false) => { - format!("{source_name} attempts to coordinate with {targets}.") - } - (StrategicActivityKind::Coordinate, true) => { - format!("{source_name} attempts internal coordination.") - } - (StrategicActivityKind::Investigate, true) => { - format!("{source_name} begins a local investigation.") - } - (StrategicActivityKind::Investigate, false) => { - format!("{source_name} begins investigating {targets}.") - } - (StrategicActivityKind::Recruit, false) => { - format!("{source_name} attempts recruitment involving {targets}.") - } - (StrategicActivityKind::Obstruct, false) => { - format!("{source_name} attempts to obstruct {targets}.") - } - (StrategicActivityKind::Obstruct, true) => { - format!("{source_name} attempts local interference.") - } - (StrategicActivityKind::Trade, false) => { - format!("{source_name} offers a trade to {targets}.") - } - (StrategicActivityKind::Communicate, true) => { - format!("{source_name} attempts a local communication.") - } - (StrategicActivityKind::Communicate, false) => { - format!("{source_name} sends a communication to {targets}.") - } - _ => unreachable!("validated strategic activity requires a target"), - } -} - -fn strategic_activity_id(activity: &StrategicActivityKind) -> &'static str { - match activity { - StrategicActivityKind::Prepare => "prepare", - StrategicActivityKind::Coordinate => "coordinate", - StrategicActivityKind::Investigate => "investigate", - StrategicActivityKind::Recruit => "recruit", - StrategicActivityKind::Obstruct => "obstruct", - StrategicActivityKind::Trade => "trade", - StrategicActivityKind::Communicate => "communicate", - } -} - -fn strategic_activity_scope_key( - activity: &StrategicActivityKind, - target_subject_ids: &[String], - location_ids: &[String], -) -> (&'static str, Vec, Vec) { - let mut targets = target_subject_ids.to_vec(); - let mut locations = location_ids.to_vec(); - targets.sort(); - locations.sort(); - (strategic_activity_id(activity), targets, locations) -} - -fn strategic_activity_scope_digest( - activity: &StrategicActivityKind, - target_subject_ids: &[String], - location_ids: &[String], -) -> String { - let scope = strategic_activity_scope_key(activity, target_subject_ids, location_ids); - let bytes = rmp_serde::to_vec_named(&scope) - .expect("serializing a strategic activity scope made only of strings cannot fail"); - format!("{:x}", Sha256::digest(bytes)) -} - -fn agency_subject_name(campaign: &Campaign, subject_id: &str) -> Result { - campaign - .actors - .get(subject_id) - .map(|value| value.name.clone()) - .or_else(|| { - campaign - .institutions - .get(subject_id) - .map(|value| value.name.clone()) - }) - .or_else(|| { - campaign - .gestalts - .get(subject_id) - .map(|value| value.name.clone()) - }) - .or_else(|| { - crate::resolution::dormant_member_id_for_subject(campaign, subject_id).and_then( - |member_id| { - campaign - .gestalt_members - .get(member_id) - .map(|value| value.name.clone()) - }, - ) - }) - .ok_or_else(|| KernelError::Invalid("strategic activity target vanished".into())) -} - -fn deterministic_strategic_tick_plan() -> StrategicTickPlan { - // Deterministic time and clock obligations are lowered by the same wave - // transition. Without an admitted Persona wave there is no authority to - // invent actor or institution activity. - StrategicTickPlan::default() -} - -fn validate_public_channels(channels: &[String]) -> Result<(), KernelError> { - if channels.len() > 8 - || channels - .iter() - .any(|channel| !crate::resolution::information_channel_is_concrete(channel)) - { - return Err(KernelError::Invalid( - "strategic action has invalid information channels".into(), - )); - } - Ok(()) -} - -fn valid_sha256(value: &str) -> bool { - value - .strip_prefix("sha256:") - .is_some_and(|digest| digest.len() == 64 && digest.bytes().all(|b| b.is_ascii_hexdigit())) -} - -fn commit_gestalt_presence( - store: &CampaignStore, - row: cultcache_legacy::CultCacheEnvelope, - before: Campaign, - mut campaign: Campaign, - kind: &str, - reason: &str, - model_receipts: Vec, -) -> Result { - let previous_resolution_epoch = campaign.resolution_policy.resolution_epoch; - crate::resolution::ensure_agency_profiles(&mut campaign); - let mut changes = Vec::new(); - for (member_id, member) in &campaign.gestalt_members { - let previous_actor = before - .gestalt_members - .get(member_id) - .and_then(|value| value.materialized_actor_id.as_deref()); - let current_actor = member.materialized_actor_id.as_deref(); - if previous_actor == current_actor { - continue; - } - let (operation, actor_id) = match (previous_actor, current_actor) { - (None, Some(actor)) => ("materialized", actor), - (Some(actor), None) => ("dematerialized", actor), - (Some(_), Some(actor)) => ("rematerialized", actor), - (None, None) => unreachable!(), - }; - let gestalt = campaign - .gestalts - .get(&member.gestalt_id) - .ok_or_else(|| KernelError::Invalid("gestalt receipt lost its baseline".into()))?; - changes.push(crate::domain::GestaltPresenceChange { - operation: operation.into(), - gestalt_id: member.gestalt_id.clone(), - member_id: member_id.clone(), - actor_id: actor_id.into(), - gestalt_version: gestalt.version, - member_version: member.version, - }); - } - if changes.is_empty() { - return Err(KernelError::Invalid( - "gestalt presence command produced no presence change".into(), - )); - } - let previous_revision = campaign.revision; - campaign.revision += 1; - campaign.resolution_policy.resolution_epoch = previous_resolution_epoch.saturating_add(1); - campaign.resolution_cover = None; - let committed_at = Utc::now(); - let player_location = campaign.actors[&campaign.player_actor_id] - .location_id - .clone(); - let visible_arrivals = changes - .iter() - .filter(|change| change.operation != "dematerialized") - .filter_map(|change| { - let actor = campaign.actors.get(&change.actor_id)?; - (actor.location_id == player_location).then(|| { - format!( - "{} is here with {} at {}.", - actor.name, - campaign.gestalts[&change.gestalt_id].name, - campaign.locations[&actor.location_id].name - ) - }) - }) - .collect::>(); - campaign - .transcript - .extend(visible_arrivals.into_iter().map(|text| NarrativeTurn { - revision: campaign.revision, - at: committed_at, - speaker: "world".into(), - text, - persona_response_actor_ids: BTreeSet::new(), - })); - let receipt = WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision, - revision: campaign.revision, - command_kind: kind.into(), - committed_at, - roll: None, - }; - let gestalt_receipt = crate::domain::GestaltMaterializationReceipt { - schema: "ghostlight.gestalt_materialization_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision, - revision: campaign.revision, - previous_resolution_epoch, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - reason: reason.into(), - changes, - committed_at, - }; - let key = format!("{}-{}", campaign.id, campaign.revision); - store - .append_gestalt_presence( - &row, - &campaign, - &key, - &receipt, - &gestalt_receipt, - &model_receipts, - ) - .map_err(persist)?; - Ok(CommandResult::Committed { campaign, receipt }) -} - -fn commit_strategic_tick( - store: &CampaignStore, - row: cultcache_legacy::CultCacheEnvelope, - mut campaign: Campaign, - source: TickSource, - model_receipt_hash: Option, - event_ids: Vec, - resolution_wave: Option, - mutation: Option<( - crate::legacy_transition::LoweredLegacyTransition, - crate::transition::WorldMutationReceipt, - )>, -) -> Result { - crate::resolution::ensure_agency_profiles(&mut campaign); - let previous_revision = campaign.revision; - if let Some(wave) = &resolution_wave { - for assignment in &wave.cover.causal_follow_through { - if campaign.nemesis_attention_history.iter().any(|record| { - record.anchor_reference == assignment.anchor_reference - && record.responder_subject_id == assignment.responder_subject_id - }) { - return Err(KernelError::Invalid( - "Nemesis attempted to serve an already committed causal attention window" - .into(), - )); - } - campaign - .nemesis_attention_history - .push(crate::domain::NemesisAttentionRecord { - anchor_reference: assignment.anchor_reference.clone(), - responder_subject_id: assignment.responder_subject_id.clone(), - served_world_revision: previous_revision.saturating_add(1), - }); - } - } - campaign.revision += 1; - let committed_at = Utc::now(); - let external_authorities = store - .load_all::("external_subject_authority.v1") - .map_err(persist)?; - let external_proposals = resolution_wave - .as_ref() - .map(|wave| { - external_proposals_for_wave( - campaign.id, - campaign.revision, - committed_at, - wave, - &external_authorities, - ) - }) - .transpose() - .map_err(|error| KernelError::Invalid(error.to_string()))? - .unwrap_or_default(); - let receipt = WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision, - revision: campaign.revision, - command_kind: "strategic_tick".into(), - committed_at, - roll: None, - }; - let strategic = crate::domain::StrategicTickReceipt { - schema: "ghostlight.strategic_tick.v1".into(), - campaign_id: campaign.id, - previous_revision, - revision: campaign.revision, - source, - model_receipt_hash, - model_receipt_hashes: resolution_wave - .as_ref() - .map(|wave| wave.model_receipt_hashes.clone()) - .unwrap_or_default(), - resolution_epoch: resolution_wave.as_ref().map(|wave| wave.resolution_epoch), - resolution_cover_id: resolution_wave.as_ref().map(|wave| { - format!( - "{}:{}:{}", - campaign.id, wave.world_revision, wave.resolution_epoch - ) - }), - event_ids, - committed_at, - }; - let key = format!("{}-{}", campaign.id, campaign.revision); - store - .append_strategic_tick( - &row, - &campaign, - &key, - &receipt, - &strategic, - resolution_wave.as_ref(), - &external_proposals, - mutation - .as_ref() - .map(|(transition, receipt)| (&transition.authority, &transition.batch, receipt)), - ) - .map_err(persist)?; - Ok(CommandResult::Committed { campaign, receipt }) -} - -fn external_proposals_for_wave( - campaign_id: uuid::Uuid, - world_revision: u64, - created_at: chrono::DateTime, - wave: &ResolutionWaveCommit, - authorities: &[crate::consumer::ExternalSubjectAuthority], -) -> anyhow::Result> { - let mut proposals = Vec::new(); - for appraisal in &wave.appraisals { - for action in &appraisal.actions { - let action_digest = crate::resolution::cell_action_digest(action)?; - for authority in authorities { - if crate::consumer::proposal_targets(action) - .contains(&authority.subject_id.as_str()) - { - let id = crate::legacy_transition::digest_serializable(&( - campaign_id, - world_revision, - &authority.id, - &action_digest, - ))?; - proposals.push(crate::consumer::ExternalWorldProposal { - schema: "ghostlight.external_world_proposal.v1".into(), - id: format!("external-proposal:{id}"), - campaign_id, - world_revision, - authority_id: authority.id.clone(), - external_subject_id: authority.subject_id.clone(), - source_subject_id: action.subject_id.clone(), - intent: action.intent.clone(), - intended_effect: action.intended_effect.clone(), - action_digest: action_digest.clone(), - public_channels: action.public_channels.clone(), - state_references: action.state_references.clone(), - status: crate::consumer::ExternalProposalStatus::Pending, - created_at, - }); - } - } - } - } - Ok(proposals) -} - -fn commit_resolution_control( - store: &CampaignStore, - row: cultcache_legacy::CultCacheEnvelope, - campaign: Campaign, - previous_resolution_epoch: u64, - operation: &str, -) -> Result { - let receipt = ResolutionControlReceipt { - schema: "ghostlight.resolution_control_receipt.v1".into(), - campaign_id: campaign.id, - world_revision: campaign.revision, - previous_resolution_epoch, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - provider_configuration_epoch: campaign.resolution_policy.provider_configuration_epoch, - operation: operation.into(), - active_cell_budget: campaign.resolution_policy.active_cell_budget, - pin_ids: campaign.resolution_pins.keys().cloned().collect(), - committed_at: Utc::now(), - }; - store - .append_resolution_control(&row, &campaign, &receipt) - .map_err(persist)?; - Ok(CommandResult::ResolutionUpdated { campaign, receipt }) -} - -fn commit( - store: &CampaignStore, - row: cultcache_legacy::CultCacheEnvelope, - mut campaign: Campaign, - kind: &str, - roll: Option, -) -> Result { - crate::resolution::ensure_agency_profiles(&mut campaign); - let previous_revision = campaign.revision; - campaign.revision += 1; - let receipt = WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision, - revision: campaign.revision, - command_kind: kind.into(), - committed_at: Utc::now(), - roll, - }; - store - .append_world_transition( - &row, - "ghostlight.campaign.v1", - &campaign, - &format!("{}-{}", campaign.id, campaign.revision), - &receipt, - ) - .map_err(persist)?; - Ok(CommandResult::Committed { campaign, receipt }) -} - -fn commit_mutation_transition( - store: &CampaignStore, - row: cultcache_legacy::CultCacheEnvelope, - mut campaign: Campaign, - kind: &str, - roll: Option, - transition: crate::legacy_transition::LoweredLegacyTransition, - mutation_receipt: crate::transition::WorldMutationReceipt, -) -> Result { - crate::resolution::ensure_agency_profiles(&mut campaign); - let previous_revision = campaign.revision; - campaign.revision += 1; - if mutation_receipt.previous_world_revision != previous_revision - || mutation_receipt.world_revision != campaign.revision - { - return Err(KernelError::Invalid( - "mutation receipt does not bind the campaign transition".into(), - )); - } - let receipt = WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision, - revision: campaign.revision, - command_kind: kind.into(), - committed_at: mutation_receipt.committed_at, - roll, - }; - store - .append_world_transition_with_mutation( - &row, - "ghostlight.campaign.v1", - &campaign, - &format!("{}-{}", campaign.id, campaign.revision), - &receipt, - &transition.authority, - &transition.batch, - &mutation_receipt, - ) - .map_err(persist)?; - Ok(CommandResult::Committed { campaign, receipt }) -} - -fn load_campaign_membership( - store: &CampaignStore, - campaign_id: uuid::Uuid, -) -> Result { - store - .load::("campaign_membership.v1", &campaign_id.to_string()) - .map_err(persist)? - .map(|(_, membership)| membership) - .ok_or_else(|| KernelError::Invalid("campaign membership is missing".into())) -} - -fn optional_campaign_membership( - store: &CampaignStore, - campaign_id: uuid::Uuid, -) -> Result, KernelError> { - store - .load::("campaign_membership.v1", &campaign_id.to_string()) - .map_err(persist) - .map(|value| value.map(|(_, membership)| membership)) -} - -fn validate_bounded_coop_effect( - store: &CampaignStore, - campaign: &Campaign, - acting_actor_id: &str, - effect: &WorldEffectDelta, -) -> Result<(), KernelError> { - let Some(membership) = optional_campaign_membership(store, campaign.id)? else { - return Ok(()); - }; - let controlled = membership.controlled_actor_ids(); - if controlled.len() < 2 || !controlled.contains(acting_actor_id) { - return Ok(()); - } - if !effect.actor_moves.is_empty() { - return Err(KernelError::Invalid( - "co-op travel requires a unanimous group-travel proposal".into(), - )); - } - let mut protected_targets = BTreeSet::new(); - protected_targets.extend(effect.actor_conditions.keys().cloned()); - protected_targets.extend(effect.actor_commitments.keys().cloned()); - protected_targets.extend(effect.actor_knowledge_additions.keys().cloned()); - protected_targets.extend(effect.actor_observations.keys().cloned()); - protected_targets.extend(effect.actor_relationship_updates.keys().cloned()); - if protected_targets - .iter() - .any(|target| target != acting_actor_id && controlled.contains(target)) - { - return Err(KernelError::Invalid( - "player-versus-player effects are unsupported in bounded co-op".into(), - )); - } - Ok(()) -} - -fn require_active_member<'a>( - membership: &'a CampaignMembership, - member_id: &str, -) -> Result<&'a crate::session_zero::CampaignMember, KernelError> { - membership - .members - .get(member_id) - .filter(|member| member.active) - .ok_or_else(|| KernelError::Invalid("campaign member is not active".into())) -} - -fn active_member_ids(membership: &CampaignMembership) -> BTreeSet { - membership - .members - .values() - .filter(|member| member.active) - .map(|member| member.member_id.clone()) - .collect() -} - -fn commit_governed_time_advance( - store: &CampaignStore, - campaign_row: cultcache_legacy::CultCacheEnvelope, - mut campaign: Campaign, - proposal_row: cultcache_legacy::CultCacheEnvelope, - mut proposal: TimeAdvanceProposal, -) -> Result { - let transition = crate::legacy_transition::lower_time_advance( - &campaign, - proposal.minutes, - crate::transition::MutationProcedure::Governance, - &proposal.id, - Utc::now() + Duration::minutes(5), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mutation_receipt = - crate::legacy_transition::apply_lowered_transition(&mut campaign, &transition, Utc::now()) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - campaign.last_player_activity = Utc::now(); - campaign.away_ticks_processed = 0; - campaign.pending_ticks = 0; - crate::resolution::ensure_agency_profiles(&mut campaign); - let previous_revision = campaign.revision; - campaign.revision = campaign.revision.saturating_add(1); - proposal.committed = true; - let receipt = WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision, - revision: campaign.revision, - command_kind: "unanimous_time_advance".into(), - committed_at: mutation_receipt.committed_at, - roll: None, - }; - store - .commit_time_advance( - &campaign_row, - &campaign, - &proposal_row, - &proposal, - &receipt, - (&transition.authority, &transition.batch, &mutation_receipt), - ) - .map_err(persist)?; - Ok(CommandResult::Committed { campaign, receipt }) -} - -fn join_public_names(names: &[String]) -> String { - match names { - [] => "The party".into(), - [name] => name.clone(), - [first, second] => format!("{first} and {second}"), - _ => format!( - "{}, and {}", - names[..names.len() - 1].join(", "), - names.last().expect("non-empty names") - ), - } -} - -fn commit_governed_group_travel( - store: &CampaignStore, - campaign_row: cultcache_legacy::CultCacheEnvelope, - mut campaign: Campaign, - proposal_row: cultcache_legacy::CultCacheEnvelope, - mut proposal: GroupTravelProposal, - membership: &CampaignMembership, -) -> Result { - let active_actor_ids = membership.controlled_actor_ids(); - if active_actor_ids.iter().any(|actor_id| { - campaign - .actors - .get(actor_id) - .is_none_or(|actor| actor.location_id != proposal.origin_location_id) - }) { - return Err(KernelError::Invalid( - "group-travel proposal no longer matches the shared scene".into(), - )); - } - let route = campaign - .locations - .get(&proposal.origin_location_id) - .and_then(|location| { - location - .routes - .values() - .find(|route| route.destination_id == proposal.destination_location_id) - .cloned() - }) - .ok_or_else(|| KernelError::Invalid("group-travel route no longer exists".into()))?; - if route.travel_minutes != proposal.travel_minutes { - return Err(KernelError::Invalid( - "group-travel route changed after proposal".into(), - )); - } - let origin_name = campaign.locations[&proposal.origin_location_id] - .name - .clone(); - let destination_name = campaign.locations[&proposal.destination_location_id] - .name - .clone(); - let traveler_names = active_actor_ids - .iter() - .filter_map(|actor_id| { - campaign - .actors - .get(actor_id) - .map(|actor| actor.name.clone()) - }) - .collect::>(); - let transition = crate::legacy_transition::lower_group_travel( - &campaign, - &active_actor_ids, - &proposal.origin_location_id, - &proposal.destination_location_id, - route.travel_minutes, - &proposal.id, - Utc::now() + Duration::minutes(5), - ) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - let mutation_receipt = - crate::legacy_transition::apply_lowered_transition(&mut campaign, &transition, Utc::now()) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - crate::resolution::ensure_agency_profiles(&mut campaign); - campaign.last_player_activity = Utc::now(); - campaign.away_ticks_processed = 0; - campaign.pending_ticks = 0; - let previous_revision = campaign.revision; - campaign.revision = campaign.revision.saturating_add(1); - let travel_summary = format!( - "{} {} from {} to {} — {}. {} minutes pass.", - join_public_names(&traveler_names), - if traveler_names.len() == 1 { - "travels" - } else { - "travel" - }, - origin_name, - destination_name, - route.distance, - route.travel_minutes - ); - campaign.transcript.push(NarrativeTurn { - revision: campaign.revision, - at: campaign.world_time, - speaker: "world".into(), - text: travel_summary.clone(), - persona_response_actor_ids: BTreeSet::new(), - }); - campaign.events.push(Event { - id: format!("group-travel:{}", campaign.revision), - at: campaign.world_time, - kind: "group_travel".into(), - summary: travel_summary, - actor_ids: active_actor_ids.into_iter().collect(), - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec![ - proposal.origin_location_id.clone(), - proposal.destination_location_id.clone(), - ], - public_channels: vec![], - }); - proposal.committed = true; - let receipt = WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision, - revision: campaign.revision, - command_kind: "unanimous_group_travel".into(), - committed_at: mutation_receipt.committed_at, - roll: None, - }; - store - .commit_group_travel( - &campaign_row, - &campaign, - &proposal_row, - &proposal, - &receipt, - (&transition.authority, &transition.batch, &mutation_receipt), - ) - .map_err(persist)?; - Ok(CommandResult::Committed { campaign, receipt }) -} - -fn commit_governed_cell_budget( - store: &CampaignStore, - campaign_row: cultcache_legacy::CultCacheEnvelope, - mut campaign: Campaign, - proposal_row: cultcache_legacy::CultCacheEnvelope, - mut proposal: CellBudgetProposal, -) -> Result { - let previous_epoch = campaign.resolution_policy.resolution_epoch; - campaign.resolution_policy.active_cell_budget = proposal.active_cell_budget; - campaign.resolution_policy.pending_active_cell_budget = None; - campaign.resolution_policy.resolution_epoch = previous_epoch.saturating_add(1); - campaign.resolution_cover = None; - crate::resolution::validate_policy(&campaign.resolution_policy) - .map_err(|error| KernelError::Invalid(error.to_string()))?; - proposal.committed = true; - let receipt = ResolutionControlReceipt { - schema: "ghostlight.resolution_control_receipt.v1".into(), - campaign_id: campaign.id, - world_revision: campaign.revision, - previous_resolution_epoch: previous_epoch, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - provider_configuration_epoch: campaign.resolution_policy.provider_configuration_epoch, - operation: "unanimous_set_active_cell_budget".into(), - active_cell_budget: campaign.resolution_policy.active_cell_budget, - pin_ids: campaign.resolution_pins.keys().cloned().collect(), - committed_at: Utc::now(), - }; - store - .commit_cell_budget(&campaign_row, &campaign, &proposal_row, &proposal, &receipt) - .map_err(persist)?; - Ok(CommandResult::ResolutionUpdated { campaign, receipt }) -} - -struct ClockBindingCommitData { - admission: crate::clock::ClockConsequenceBindingAdmission, - emitted_event_ids: Vec, - news_count_before: usize, - next_wave_index: usize, -} - -fn commit_with_records( - store: &CampaignStore, - row: cultcache_legacy::CultCacheEnvelope, - mut campaign: Campaign, - kind: &str, - evidence: Vec, - candidates: Vec, - model_receipts: Vec, - clock_binding: Option, - mutation: Option<( - crate::legacy_transition::LoweredLegacyTransition, - crate::transition::WorldMutationReceipt, - )>, -) -> Result { - crate::resolution::ensure_agency_profiles(&mut campaign); - let previous_revision = campaign.revision; - campaign.revision += 1; - if let Some((_, mutation_receipt)) = &mutation - && (mutation_receipt.previous_world_revision != previous_revision - || mutation_receipt.world_revision != campaign.revision) - { - return Err(KernelError::Invalid( - "mutation receipt does not bind the recorded world commit".into(), - )); - } - let committed_at = mutation - .as_ref() - .map(|(_, receipt)| receipt.committed_at) - .unwrap_or_else(Utc::now); - let receipt = WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision, - revision: campaign.revision, - command_kind: kind.into(), - committed_at, - roll: None, - }; - let clock_binding_receipt = if let Some(binding) = clock_binding { - let emitted_events = binding.emitted_event_ids.iter().collect::>(); - let emitted_news_ids = campaign - .news - .iter() - .skip(binding.news_count_before) - .filter(|news| news.event_ids.iter().any(|id| emitted_events.contains(id))) - .map(|news| news.id.clone()) - .collect::>(); - let expected_news_ids = campaign - .events - .iter() - .filter(|event| emitted_events.contains(&event.id)) - .flat_map(|event| { - event - .public_channels - .iter() - .map(|channel| crate::domain::event_publication_id(&event.id, channel)) - }) - .collect::>(); - if emitted_news_ids.iter().collect::>() - != expected_news_ids.iter().collect::>() - { - return Err(KernelError::Invalid( - "clock consequence binding did not publish the exact admitted event channels" - .into(), - )); - } - Some(crate::clock::ClockConsequenceBindingReceipt { - schema: "ghostlight.clock_consequence_binding_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision, - revision: campaign.revision, - snapshot_binding: binding.admission.snapshot_binding, - binding_batch_digest: binding.admission.binding_batch_digest, - bindings: binding.admission.bindings, - model_receipt_ids: model_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>() - .into_iter() - .collect(), - accepted_model_receipt_id: binding.admission.accepted_model_receipt_id, - emitted_event_ids: binding.emitted_event_ids, - emitted_news_ids, - news_count_before: binding.news_count_before, - next_wave_index: binding.next_wave_index, - committed_at, - }) - } else { - None - }; - store - .append_world_commit( - &row, - &campaign, - &format!("{}-{}", campaign.id, campaign.revision), - &receipt, - &evidence, - &candidates, - &model_receipts, - clock_binding_receipt.as_ref(), - mutation - .as_ref() - .map(|(transition, receipt)| (&transition.authority, &transition.batch, receipt)), - ) - .map_err(persist)?; - Ok(CommandResult::Committed { campaign, receipt }) -} - -fn persist(e: anyhow::Error) -> KernelError { - KernelError::Persistence(e.to_string()) -} - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - use sha2::{Digest, Sha256}; - use std::collections::{BTreeMap, BTreeSet}; - - fn test_action_digest(label: &str) -> String { - format!("sha256:{:x}", Sha256::digest(label.as_bytes())) - } - - #[test] - fn strategic_activity_phase_is_derived_from_exact_locations() { - assert_eq!( - relative_activity_phase("yard", Some("room"), &["yard".into()]), - 0 - ); - assert_eq!( - relative_activity_phase("yard", Some("room"), &["room".into()]), - 2 - ); - assert_eq!( - relative_activity_phase("yard", Some("room"), &["yard".into(), "room".into()]), - 1 - ); - assert_eq!(relative_activity_phase("yard", None, &["yard".into()]), 1); - } - - fn resolve_test_activities(mut plan: StrategicTickPlan) -> StrategicTickPlan { - plan.activity_outcomes.extend( - plan.gestalt_activities - .iter() - .map(|activity| (activity.action_digest.clone(), activity.gestalt_id.clone())) - .chain( - plan.actor_activities.iter().map(|activity| { - (activity.action_digest.clone(), activity.actor_id.clone()) - }), - ) - .chain(plan.member_activities.iter().map(|activity| { - ( - activity.action_digest.clone(), - crate::domain::gestalt_member_subject_id(&activity.member_id), - ) - })) - .map( - |(action_digest, source_subject_id)| StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest, - source_subject_id, - band: StrategicOutcomeBand::Mixed, - summary: "The attempt produces no durable material change.".into(), - supporting_state_references: vec![], - effect: StrategicOutcomeEffect::NoMaterialChange { - reason: "No response is established in this test snapshot.".into(), - }, - }, - ), - ); - plan - } - - fn assert_only_strategic_obligations_advanced(before: &Campaign, after: &Campaign) { - let mut expected = before.clone(); - expected.world_time += Duration::hours(i64::from(expected.tick_hours)); - for clock in expected.clocks.values_mut() { - clock.progress = clock.progress.saturating_add(1).min(clock.threshold); - } - assert_eq!(after, &expected); - } - - pub(crate) fn campaign() -> Campaign { - let id = uuid::Uuid::new_v4(); - let actor = ActorState { - id: "player".into(), - name: "Player".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }; - Campaign { - schema: "ghostlight.campaign.v1".into(), - id, - name: "Test".into(), - revision: 0, - branch_origin: BranchOrigin { - canon_cutoff: "test".into(), - evidence_receipt_ids: vec![], - }, - world_time: Utc::now(), - tick_hours: 6, - player_actor_id: "player".into(), - locations: BTreeMap::from([( - "room".into(), - Location { - id: "room".into(), - name: "Room".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec!["stable".into()], - }, - )]), - actors: BTreeMap::from([("player".into(), actor)]), - institutions: BTreeMap::new(), - clocks: BTreeMap::new(), - facts: BTreeMap::new(), - civic_systems: BTreeMap::new(), - transcript: vec![], - last_player_activity: Utc::now(), - pending_ticks: 0, - away_ticks_processed: 0, - events: vec![], - news: vec![], - canon_candidates: BTreeMap::new(), - gestalts: BTreeMap::new(), - gestalt_members: BTreeMap::new(), - pending_world_proposals: vec![], - agency_profiles: BTreeMap::new(), - agency_relations: BTreeMap::new(), - gestalt_lineages: BTreeMap::new(), - resolution_policy: Default::default(), - resolution_pins: BTreeMap::new(), - resolution_cover: None, - nemesis_attention_history: Vec::new(), - strategic_tick_count: 0, - } - } - - fn civic_locality_elaboration() -> LocalityElaboration { - let public_facts = [ - ( - "fact:room-authority", - "Mayor Selka Vey holds the civic seal while the ward assembly controls appropriations.", - ), - ( - "fact:room-selection", - "Residents elected Selka Vey over Oren Vale at the last mayoral ballot.", - ), - ( - "fact:room-resources", - "Published berth dues fund the civic treasury.", - ), - ( - "fact:room-redress", - "Residents may appeal a mayoral order to the ward petitions bench.", - ), - ]; - let facts = public_facts - .iter() - .map(|(id, statement)| WorldFact { - id: (*id).into(), - statement: (*statement).into(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from([ - "room".into(), - "civic-quarter".into(), - ]), - }) - .collect::>(); - let institution_profile = |id: &str, authority: &str| AgencyProfile { - schema: "ghostlight.agency_profile.v1".into(), - id: format!("agency:{id}"), - subject_id: id.into(), - subject_kind: AgencySubjectKind::Institution, - profile_version: 0, - collective_authority_id: None, - parent_subject_id: None, - active_leaf: true, - simulation_eligible: true, - facets: BTreeMap::from([ - (AgencyAxis::Geography, BTreeSet::from(["room".into()])), - ( - AgencyAxis::Ideology, - BTreeSet::from(["public mandate".into()]), - ), - (AgencyAxis::Authority, BTreeSet::from([authority.into()])), - ( - AgencyAxis::EconomyRole, - BTreeSet::from(["civic administration".into()]), - ), - ( - AgencyAxis::SpeciesBody, - BTreeSet::from(["mixed residents".into()]), - ), - ( - AgencyAxis::Information, - BTreeSet::from(["ward notices".into()]), - ), - ]), - location_ids: BTreeSet::from(["civic-quarter".into()]), - information_channels: BTreeSet::from(["ward notice board".into()]), - detail_debt: 0, - last_detail_tick: 0, - evidence_receipt_ids: vec![], - }; - LocalityElaboration { - target_location_id: "room".into(), - expansion: RegionExpansion { - origin_location_id: "room".into(), - origin_routes: BTreeMap::from([( - "to-civic-quarter".into(), - Route { - destination_id: "civic-quarter".into(), - distance: "through the public arcade".into(), - travel_minutes: 5, - }, - )]), - locations: vec![Location { - id: "civic-quarter".into(), - name: "Civic Quarter".into(), - container_id: Some("room".into()), - routes: BTreeMap::from([( - "to-room".into(), - Route { - destination_id: "room".into(), - distance: "back through the public arcade".into(), - travel_minutes: 5, - }, - )]), - persistent_features: vec!["sealed ballot archive".into()], - }], - facts, - populations: vec![GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "room-residents".into(), - name: "Room residents".into(), - version: 0, - home_location_id: "civic-quarter".into(), - shared_capabilities: BTreeSet::from(["participate in ward ballots".into()]), - shared_knowledge: public_facts - .iter() - .map(|(_, statement)| (*statement).into()) - .collect(), - resources: BTreeSet::from(["ward hall".into()]), - goals: vec!["keep the treasury answerable".into()], - pressures: vec!["the mayor and assembly dispute appropriations".into()], - }], - population_profiles: vec![AgencyProfile { - schema: "ghostlight.agency_profile.v1".into(), - id: "agency:room-residents".into(), - subject_id: "room-residents".into(), - subject_kind: AgencySubjectKind::Gestalt, - profile_version: 0, - collective_authority_id: Some("room-residents".into()), - parent_subject_id: None, - active_leaf: true, - simulation_eligible: true, - facets: BTreeMap::from([ - (AgencyAxis::Geography, BTreeSet::from(["room".into()])), - ( - AgencyAxis::Ideology, - BTreeSet::from(["ward representation".into()]), - ), - ( - AgencyAxis::Authority, - BTreeSet::from(["resident franchise".into()]), - ), - ( - AgencyAxis::EconomyRole, - BTreeSet::from(["berth work".into()]), - ), - ( - AgencyAxis::SpeciesBody, - BTreeSet::from(["mixed residents".into()]), - ), - ( - AgencyAxis::Information, - BTreeSet::from(["ward notices".into()]), - ), - ]), - location_ids: BTreeSet::from(["civic-quarter".into()]), - information_channels: BTreeSet::from(["ward notice board".into()]), - detail_debt: 0, - last_detail_tick: 0, - evidence_receipt_ids: vec![], - }], - migration_relations: vec![], - institutions: vec![ - InstitutionState { - id: "mayoral-office".into(), - name: "Mayoral Office".into(), - resources: vec!["civic seal".into()], - goals: vec!["retain emergency spending discretion".into()], - posture: "press for immediate appropriation".into(), - }, - InstitutionState { - id: "ward-assembly".into(), - name: "Ward Assembly".into(), - resources: vec!["appropriations ledger".into()], - goals: vec!["bind spending to public accounts".into()], - posture: "withhold funds pending audit".into(), - }, - ], - institution_profiles: vec![ - institution_profile("mayoral-office", "mayoral orders"), - institution_profile("ward-assembly", "appropriations"), - ], - local_relations: vec![AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "relation:mayor-assembly".into(), - from_subject_id: "mayoral-office".into(), - to_subject_id: "ward-assembly".into(), - kind: AgencyRelationKind::Rivalry, - strength: 72, - active: true, - evidence_receipt_ids: vec![], - }], - civic_system: Some(CivicSystemManifest { - schema: "ghostlight.civic_system_manifest.v1".into(), - version: 0, - jurisdiction_location_id: "room".into(), - governing_institution_ids: BTreeSet::from([ - "mayoral-office".into(), - "ward-assembly".into(), - ]), - resident_population_ids: BTreeSet::from(["room-residents".into()]), - public_authority_fact_ids: BTreeSet::from(["fact:room-authority".into()]), - public_selection_fact_ids: BTreeSet::from(["fact:room-selection".into()]), - public_resource_fact_ids: BTreeSet::from(["fact:room-resources".into()]), - public_redress_fact_ids: BTreeSet::from(["fact:room-redress".into()]), - political_relation_ids: BTreeSet::from(["relation:mayor-assembly".into()]), - semantic_verification_receipt_id: String::new(), - }), - }, - } - } - - fn civic_verifier_receipt( - campaign: &Campaign, - expansion: &mut RegionExpansion, - source_receipt_ids: Vec, - ) -> crate::model::ModelStageReceipt { - let digest = crate::compiler::civic_candidate_digest(expansion).unwrap(); - let mut receipt = crate::model::ModelStageReceipt { - schema: "ghostlight.persona_stage_receipt.v1".into(), - receipt_hash: String::new(), - provider: "fixture".into(), - model: "fixture".into(), - stage: "destination_civic_verification".into(), - snapshot_binding: String::new(), - request_hash: test_action_digest("civic-verifier-request"), - output_hash: test_action_digest("civic-verifier-output"), - source_receipt_ids, - latency_ms: 1, - validation_result: "valid".into(), - local_validation_error: None, - input_chars: 1, - output_chars: 1, - provider_attempts: vec![], - }; - receipt.rebind_snapshot(crate::compiler::civic_verifier_binding(campaign, &digest)); - expansion - .civic_system - .as_mut() - .unwrap() - .semantic_verification_receipt_id = receipt.storage_key().to_owned(); - receipt - } - - struct FixtureWorldElaborationSubAgent { - operations: BTreeMap< - crate::elaboration::ElaboratorTitle, - Vec, - >, - } - - #[async_trait::async_trait] - impl crate::elaboration::ElaborationSubAgentPort - for FixtureWorldElaborationSubAgent - { - async fn invoke( - &self, - invocation: crate::elaboration::ElaborationSubAgentInvocation, - ) -> std::result::Result< - crate::elaboration::ElaborationSubAgentOutput< - crate::elaboration::WorldElaborationProposal, - >, - crate::elaboration::ElaborationSubAgentFailure, - > { - let index = invocation.dispatch.title_dispatch_count as usize - 1; - let operation = self - .operations - .get(&invocation.dispatch.title) - .and_then(|operations| operations.get(index)) - .cloned() - .ok_or_else(|| crate::elaboration::ElaborationSubAgentFailure { - diagnostic: "fixture elaborator received an extra dispatch".into(), - model_stage_receipts: Vec::new(), - })?; - let binding = crate::elaboration::world_elaboration_invocation_binding( - &invocation.wave, - &invocation.dispatch, - ) - .map_err(|error| crate::elaboration::ElaborationSubAgentFailure { - diagnostic: error.to_string(), - model_stage_receipts: Vec::new(), - })?; - let mut model_receipt = crate::model::ModelStageReceipt { - schema: "ghostlight.persona_stage_receipt.v1".into(), - receipt_hash: String::new(), - provider: "fixture".into(), - model: "fixture-model".into(), - stage: format!( - "world_elaboration_{}", - invocation - .dispatch - .title - .display_name() - .to_ascii_lowercase() - ), - snapshot_binding: String::new(), - request_hash: test_action_digest(&format!( - "elaboration-request:{}", - invocation.dispatch.ordinal - )), - output_hash: test_action_digest(&format!( - "elaboration-output:{}", - invocation.dispatch.ordinal - )), - 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(), - }; - model_receipt.rebind_snapshot(binding); - Ok(crate::elaboration::ElaborationSubAgentOutput { - proposal: crate::elaboration::WorldElaborationProposal { - schema: "ghostlight.world_elaboration_proposal.v1".into(), - operation, - }, - model_stage_receipts: vec![model_receipt], - }) - } - } - - async fn dispatch_titled_operations( - campaign: &Campaign, - target_location_id: &str, - operations: Vec<( - crate::elaboration::ElaboratorTitle, - crate::elaboration::WorldElaborationOperation, - )>, - ) -> crate::elaboration::ElaborationWaveRun { - use crate::elaboration::*; - let mut by_title = BTreeMap::>::new(); - for (title, operation) in operations { - by_title.entry(title).or_default().push(operation); - } - let profile = WorldElaborationProfile { - schema: "ghostlight.world_elaboration_profile.v1".into(), - controls: by_title - .iter() - .map(|(title, operations)| ElaboratorControl { - title: *title, - weight: operations.len() as u16, - }) - .collect(), - }; - let invocation_budget = by_title.values().map(Vec::len).sum::() as u32; - let eligible_titles = by_title.keys().copied().collect::>(); - let mut scheduler = ElaborationScheduler::new(&profile).unwrap(); - dispatch_elaboration_wave( - &mut scheduler, - world_elaboration_wave_binding(campaign, target_location_id).unwrap(), - &eligible_titles, - invocation_budget, - 4, - std::sync::Arc::new(FixtureWorldElaborationSubAgent { - operations: by_title, - }), - ) - .await - .unwrap() - } - - #[tokio::test] - async fn resolved_outcome_cannot_admit_an_unrequested_gestalt_member() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.transcript.push(NarrativeTurn { - revision: 0, - at: Utc::now(), - speaker: "world".into(), - text: "They agree to help design the relay.".into(), - persona_response_actor_ids: BTreeSet::new(), - }); - seed.gestalts.insert( - "refugees".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "refugees".into(), - name: "Refugees".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - crate::resolution::ensure_agency_profiles(&mut seed); - let campaign_id = seed.id; - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - - let member = GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "relay-volunteer".into(), - gestalt_id: "refugees".into(), - version: 0, - name: "Relay Volunteer".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!["help with the relay".into()], - memories: vec!["agreed to help".into()], - last_location_id: Some("room".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }; - let error = kernel - .command(WorldCommand::ReconcileGestaltPresence { - expected_revision: 0, - reason: "They agree to help design the relay.".into(), - plan: GestaltPresencePlan { - individuations: vec![GestaltIndividuation { - gestalt_id: "refugees".into(), - expected_gestalt_version: 0, - member, - location_id: "room".into(), - }], - promotions: vec![], - demotions: vec![], - }, - }) - .await - .unwrap_err(); - assert!( - error - .to_string() - .contains("immediately committed player speech") - ); - let persisted = store - .load::("campaign.v1", &campaign_id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(persisted.revision, 0); - assert!(persisted.gestalt_members.is_empty()); - assert_eq!(persisted.transcript.len(), 1); - } - - #[tokio::test] - async fn kernel_rejects_individuation_that_duplicates_addressed_actor_without_mutation() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.actors.insert( - "taren".into(), - ActorState { - id: "taren".into(), - name: "Taren".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - seed.gestalts.insert( - "refugees".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "refugees".into(), - name: "Refugees".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - let speech = "Taren, tell me whether the regulator is holding."; - let reason = format!("{} says: {speech}", seed.player_actor_id); - seed.transcript.push(NarrativeTurn { - revision: 0, - at: Utc::now(), - speaker: seed.player_actor_id.clone(), - text: speech.into(), - persona_response_actor_ids: BTreeSet::from(["taren".into()]), - }); - crate::resolution::ensure_agency_profiles(&mut seed); - let campaign_id = seed.id; - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - - let error = kernel - .command(WorldCommand::ReconcileGestaltPresence { - expected_revision: 0, - reason, - plan: GestaltPresencePlan { - individuations: vec![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("room".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }, - location_id: "room".into(), - }], - promotions: vec![], - demotions: vec![], - }, - }) - .await - .unwrap_err(); - assert!(error.to_string().contains("already-addressed actor")); - let persisted = store - .load::("campaign.v1", &campaign_id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(persisted.revision, 0); - assert!(!persisted.gestalt_members.contains_key("second-taren")); - assert_eq!(persisted.actors["taren"].name, "Taren"); - } - - #[test] - fn individuation_validation_and_application_share_the_canonical_subject_namespace() { - let mut value = campaign(); - value.gestalts.insert( - "refugees".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "refugees".into(), - name: "Refugees".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - crate::resolution::ensure_agency_profiles(&mut value); - let member = GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "relay-volunteer".into(), - gestalt_id: "refugees".into(), - version: 0, - name: "Relay Volunteer".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("room".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }; - let actor_id = crate::domain::gestalt_member_subject_id(&member.id); - let mut reservation = value.agency_profiles["refugees"].clone(); - reservation.id = actor_id.clone(); - reservation.subject_id = "detached-profile-subject".into(); - reservation.active_leaf = false; - reservation.simulation_eligible = false; - value - .agency_profiles - .insert("detached-profile-key".into(), reservation); - let individuation = GestaltIndividuation { - gestalt_id: "refugees".into(), - expected_gestalt_version: 0, - member: member.clone(), - location_id: "room".into(), - }; - - let diagnostic = crate::resolution::validate_gestalt_individuation(&value, &individuation) - .unwrap_err() - .to_string(); - assert!(diagnostic.contains("established canonical subject identity")); - - value.gestalt_members.insert(member.id.clone(), member); - let error = apply_promotion( - &mut value, - &GestaltPromotion { - gestalt_id: "refugees".into(), - expected_gestalt_version: 0, - member_id: "relay-volunteer".into(), - expected_member_version: 0, - location_id: "room".into(), - }, - ) - .unwrap_err(); - assert!( - error - .to_string() - .contains("established canonical subject identity") - ); - assert!(!value.actors.contains_key(&actor_id)); - assert!( - value.gestalt_members["relay-volunteer"] - .materialized_actor_id - .is_none() - ); - } - - #[test] - fn composite_selected_action_commits_atomically_and_rebuilds_derived_lanes() { - let mut value = campaign(); - value.locations.insert( - "yard".into(), - Location { - id: "yard".into(), - name: "Yard".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - ); - value.locations.get_mut("room").unwrap().routes.insert( - "yard-route".into(), - crate::domain::Route { - destination_id: "yard".into(), - distance: "nearby".into(), - travel_minutes: 15, - }, - ); - let mut runner = value.actors["player"].clone(); - runner.id = "runner".into(); - runner.name = "Runner".into(); - value.actors.insert(runner.id.clone(), runner); - crate::resolution::ensure_agency_profiles(&mut value); - let proposal = CellActionProposal { - subject_id: "runner".into(), - intent: "cross into the yard, inspect it, and brace one loose gate".into(), - intended_effect: "arrive, identify one local hazard, and attempt a bounded repair" - .into(), - priority: 80, - state_references: vec!["subject:runner".into()], - public_channels: vec![], - effects: vec![ - StrategicCellEffect::ActorMove { - actor_id: "runner".into(), - destination_id: "yard".into(), - }, - StrategicCellEffect::ActorActivity { - actor_id: "runner".into(), - activity: StrategicActivityKind::Investigate, - target_subject_ids: vec![], - location_ids: vec!["yard".into()], - }, - StrategicCellEffect::ActorActivity { - actor_id: "runner".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["yard".into()], - }, - ], - }; - let digest = crate::resolution::cell_action_digest(&proposal).unwrap(); - let mut plan = crate::resolution::project_selected_actions(&value, vec![proposal]).unwrap(); - plan.activity_outcomes = vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: digest, - source_subject_id: "runner".into(), - band: StrategicOutcomeBand::Success, - summary: "Runner completes the inspection without a durable discovery.".into(), - supporting_state_references: vec![], - effect: StrategicOutcomeEffect::NoMaterialChange { - reason: "The inspection reveals no durable new fact.".into(), - }, - }]; - plan.actor_moves = vec![StrategicActorMove { - actor_id: "player".into(), - destination_id: "invented".into(), - public_channels: vec![], - }]; - - let applied = apply_strategic_tick_plan(&mut value, plan).unwrap(); - - assert_eq!(value.actors["runner"].location_id, "yard"); - assert_eq!(value.actors["player"].location_id, "room"); - assert_eq!( - applied - .events - .iter() - .map(|event| event.kind.as_str()) - .collect::>(), - vec!["actor_movement", "actor_activity", "actor_activity"] - ); - } - - fn hierarchical_refugee_campaign() -> Campaign { - let mut value = campaign(); - value.locations.insert( - "camp".into(), - Location { - id: "camp".into(), - name: "Transit camp".into(), - container_id: None, - routes: BTreeMap::from([( - "to-docks".into(), - Route { - destination_id: "docks".into(), - distance: "across the bay".into(), - travel_minutes: 90, - }, - )]), - persistent_features: vec!["departure board".into()], - }, - ); - value.locations.insert( - "docks".into(), - Location { - id: "docks".into(), - name: "South docks".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec!["net lofts".into()], - }, - ); - let gestalt = |id: &str, - name: &str, - location: &str, - capabilities: &[&str], - knowledge: &[&str], - goals: &[&str]| GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: id.into(), - name: name.into(), - version: 0, - home_location_id: location.into(), - shared_capabilities: capabilities.iter().map(|value| (*value).into()).collect(), - shared_knowledge: knowledge.iter().map(|value| (*value).into()).collect(), - resources: BTreeSet::new(), - goals: goals.iter().map(|value| (*value).into()).collect(), - pressures: vec![], - }; - value.gestalts.insert( - "refugees-east".into(), - gestalt( - "refugees-east", - "Eastern transit refugees", - "camp", - &["survive transit", "speak old dialect"], - &["camp alarm", "old village"], - &["find safety"], - ), - ); - value.gestalts.insert( - "dock-neighbors".into(), - gestalt( - "dock-neighbors", - "South dock neighbors", - "docks", - &["repair nets"], - &["harbor routines", "public bulletin"], - &["keep the docks running"], - ), - ); - value.gestalt_members.insert( - "mira".into(), - GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "mira".into(), - gestalt_id: "refugees-east".into(), - version: 3, - name: "Mira Venn".into(), - capability_additions: BTreeSet::from(["weave signal cord".into()]), - capability_removals: BTreeSet::from(["speak old dialect".into()]), - knowledge_additions: BTreeSet::from(["the player kept a promise".into()]), - knowledge_removals: BTreeSet::from(["camp alarm".into()]), - equipment: BTreeSet::from(["patched blue satchel".into()]), - conditions: BTreeSet::from(["healed burn scar".into()]), - obligations: BTreeSet::from(["repay the player's help".into()]), - relationships: BTreeMap::from([( - "player".into(), - "trusts them for opening the evacuation gate".into(), - )]), - goals: vec![], - memories: vec!["The player carried her brother through the smoke.".into()], - last_location_id: Some("camp".into()), - materialized_actor_id: None, - last_relevant_revision: 7, - relevance_lease_until_revision: 0, - }, - ); - crate::resolution::ensure_agency_profiles(&mut value); - value - .agency_profiles - .get_mut("refugees-east") - .unwrap() - .parent_subject_id = Some("refugees-by-destination".into()); - value - .agency_profiles - .get_mut("dock-neighbors") - .unwrap() - .parent_subject_id = Some("southport-populations".into()); - value.agency_relations.insert( - "refugee-resettlement".into(), - AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "refugee-resettlement".into(), - from_subject_id: "refugees-east".into(), - to_subject_id: "dock-neighbors".into(), - kind: AgencyRelationKind::Migration, - strength: 90, - active: true, - evidence_receipt_ids: vec![], - }, - ); - value - } - - #[tokio::test] - async fn approved_fission_commits_one_typed_lineage_batch_and_no_parallel_writer() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let seed = hierarchical_refugee_campaign(); - let parent = seed.gestalts["refugees-east"].clone(); - let child = |id: &str, name: &str| GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: id.into(), - name: name.into(), - version: 0, - home_location_id: parent.home_location_id.clone(), - shared_capabilities: parent.shared_capabilities.clone(), - shared_knowledge: parent.shared_knowledge.clone(), - resources: BTreeSet::new(), - goals: parent.goals.clone(), - pressures: parent.pressures.clone(), - }; - let preview = GestaltFissionPreview { - schema: "ghostlight.gestalt_fission_preview.v1".into(), - campaign_id: seed.id, - expected_world_revision: seed.revision, - parent_gestalt_id: parent.id.clone(), - partition_axis: AgencyAxis::Ideology, - children: vec![ - child("refugees-returning", "Refugees planning to return"), - child("refugees-other", "Other eastern transit refugees"), - ], - child_partition_values: BTreeMap::from([ - ("refugees-returning".into(), "returning".into()), - ("refugees-other".into(), "other/unknown".into()), - ]), - residual_child_id: "refugees-other".into(), - member_child_assignments: BTreeMap::from([( - "mira".into(), - "refugees-returning".into(), - )]), - resource_child_assignments: BTreeMap::new(), - evidence_receipt_ids: vec![], - gaps: vec![], - canon_candidates: vec![], - requires_approval: true, - }; - let kernel = WorldKernel::start(store.clone()); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let result = kernel - .command(WorldCommand::FissionGestalt { - expected_revision: seed.revision, - preview, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, receipt } = result else { - panic!("fission did not commit") - }; - assert_eq!(receipt.command_kind, "fission_gestalt"); - assert_eq!(campaign.revision, seed.revision + 1); - assert_eq!(campaign.gestalt_members["mira"].id, "mira"); - assert_eq!( - campaign.gestalt_members["mira"].gestalt_id, - "refugees-returning" - ); - assert!(!campaign.agency_profiles["refugees-east"].active_leaf); - assert!(campaign.agency_profiles["refugees-returning"].active_leaf); - assert_eq!( - store.keys("mutation_authority_envelope.v1").unwrap().len(), - 1 - ); - assert_eq!(store.keys("world_mutation_batch.v1").unwrap().len(), 1); - assert_eq!(store.keys("world_mutation_receipt.v1").unwrap().len(), 1); - let batch = store - .load_all::("world_mutation_batch.v1") - .unwrap() - .pop() - .unwrap(); - let operations = batch - .mutations - .iter() - .map(|mutation| mutation.mutation.operation()) - .collect::>(); - assert!(operations.contains(&crate::transition::WorldMutationOperation::AdmitEntity)); - assert!(operations.contains(&crate::transition::WorldMutationOperation::PopulationSplit)); - assert!( - operations.contains(&crate::transition::WorldMutationOperation::PopulationTransfer) - ); - assert!(!operations.contains(&crate::transition::WorldMutationOperation::ResourceCreate)); - } - - #[test] - fn member_migration_rebases_across_unrelated_hierarchy_without_changing_the_person() { - let mut value = hierarchical_refugee_campaign(); - let capabilities_before = - crate::resolution::effective_member_capabilities(&value, "mira").unwrap(); - let knowledge_before = - crate::resolution::effective_member_knowledge(&value, "mira").unwrap(); - let identity_before = value.gestalt_members["mira"].clone(); - let events = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - member_migrations: vec![StrategicMemberMigration { - member_id: "mira".into(), - source_gestalt_id: "refugees-east".into(), - destination_gestalt_id: "dock-neighbors".into(), - destination_location_id: "docks".into(), - public_channels: vec![], - }], - ..Default::default() - }, - ) - .unwrap(); - let member = &value.gestalt_members["mira"]; - assert_eq!(member.gestalt_id, "dock-neighbors"); - assert_eq!(member.last_location_id.as_deref(), Some("docks")); - assert_eq!(member.version, identity_before.version + 1); - assert_eq!(member.name, identity_before.name); - assert_eq!(member.relationships, identity_before.relationships); - assert_eq!(member.memories, identity_before.memories); - assert_eq!(member.equipment, identity_before.equipment); - assert_eq!(member.conditions, identity_before.conditions); - assert_eq!(member.obligations, identity_before.obligations); - assert_eq!(member.goals, vec!["find safety"]); - assert_eq!( - crate::resolution::effective_member_capabilities(&value, "mira").unwrap(), - capabilities_before - ); - assert_eq!( - crate::resolution::effective_member_knowledge(&value, "mira").unwrap(), - knowledge_before - ); - assert_eq!(events.len(), 1); - assert_eq!(events[0].kind, "gestalt_member_migration"); - assert_eq!(events[0].actor_ids, vec!["member:mira"]); - assert_eq!( - events[0].summary, - "Mira Venn moves from Transit camp to South docks and joins South dock neighbors." - ); - - let actor = materialize_actor( - &value.gestalts["dock-neighbors"], - member, - "member:mira", - "docks", - ); - assert_eq!(actor.name, "Mira Venn"); - assert_eq!(actor.capabilities, capabilities_before); - assert_eq!(actor.knowledge, knowledge_before); - assert_eq!(actor.relationships, identity_before.relationships); - assert_eq!(actor.memories, identity_before.memories); - } - - #[test] - fn diaspora_distributes_people_across_nested_population_branches_without_merging_identity() { - let mut value = hierarchical_refugee_campaign(); - value.locations.get_mut("camp").unwrap().routes.insert( - "to-hills".into(), - Route { - destination_id: "hills".into(), - distance: "along the ridge road".into(), - travel_minutes: 120, - }, - ); - value.locations.insert( - "hills".into(), - Location { - id: "hills".into(), - name: "North hills".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec!["terraced gardens".into()], - }, - ); - - let population = |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::from([format!("live among {name}")]), - shared_knowledge: BTreeSet::from([format!("routines of {name}")]), - resources: BTreeSet::new(), - goals: vec![format!("sustain {name}")], - pressures: vec![], - }; - for (id, name, location) in [ - ("displaced-root", "Displaced people", "camp"), - ("crisis-refugees", "Crisis refugees", "camp"), - ("displaced-other", "Other displaced people", "camp"), - ("crisis-other", "Other crisis refugees", "camp"), - ("southport-root", "Southport residents", "docks"), - ("harbor-populations", "Harbor populations", "docks"), - ("harbor-other", "Other harbor residents", "docks"), - ("inland-other", "Inland residents", "hills"), - ("hill-neighbors", "North hill neighbors", "hills"), - ("inland-unknown", "Other inland residents", "hills"), - ] { - value - .gestalts - .insert(id.into(), population(id, name, location)); - } - crate::resolution::ensure_agency_profiles(&mut value); - - for parent_id in [ - "displaced-root", - "crisis-refugees", - "southport-root", - "harbor-populations", - "inland-other", - ] { - let profile = value.agency_profiles.get_mut(parent_id).unwrap(); - profile.active_leaf = false; - profile.simulation_eligible = false; - } - for (child_id, parent_id) in [ - ("crisis-refugees", "displaced-root"), - ("displaced-other", "displaced-root"), - ("refugees-east", "crisis-refugees"), - ("crisis-other", "crisis-refugees"), - ("harbor-populations", "southport-root"), - ("inland-other", "southport-root"), - ("dock-neighbors", "harbor-populations"), - ("harbor-other", "harbor-populations"), - ("hill-neighbors", "inland-other"), - ("inland-unknown", "inland-other"), - ] { - value - .agency_profiles - .get_mut(child_id) - .unwrap() - .parent_subject_id = Some(parent_id.into()); - } - let lineage = - |parent: &str, children: [&str; 2], residual: &str, axis: AgencyAxis| GestaltLineage { - schema: "ghostlight.gestalt_lineage.v1".into(), - parent_gestalt_id: parent.into(), - child_gestalt_ids: children.iter().map(|id| (*id).into()).collect(), - partition_axis: axis, - partition_values: BTreeMap::from([ - (children[0].into(), "selected".into()), - (children[1].into(), "other/unknown".into()), - ]), - residual_child_id: residual.into(), - source_revision: value.revision, - }; - value.gestalt_lineages.insert( - "displaced-root".into(), - lineage( - "displaced-root", - ["crisis-refugees", "displaced-other"], - "displaced-other", - AgencyAxis::Ideology, - ), - ); - value.gestalt_lineages.insert( - "crisis-refugees".into(), - lineage( - "crisis-refugees", - ["refugees-east", "crisis-other"], - "crisis-other", - AgencyAxis::Geography, - ), - ); - value.gestalt_lineages.insert( - "southport-root".into(), - lineage( - "southport-root", - ["harbor-populations", "inland-other"], - "inland-other", - AgencyAxis::Geography, - ), - ); - value.gestalt_lineages.insert( - "harbor-populations".into(), - lineage( - "harbor-populations", - ["dock-neighbors", "harbor-other"], - "harbor-other", - AgencyAxis::EconomyRole, - ), - ); - value.gestalt_lineages.insert( - "inland-other".into(), - lineage( - "inland-other", - ["hill-neighbors", "inland-unknown"], - "inland-unknown", - AgencyAxis::Authority, - ), - ); - - let mut tovan = value.gestalt_members["mira"].clone(); - tovan.id = "tovan".into(); - tovan.name = "Tovan Ser".into(); - tovan.version = 9; - tovan.capability_additions = BTreeSet::from(["tend terrace herbs".into()]); - tovan.knowledge_additions = BTreeSet::from(["the player found his daughter".into()]); - tovan.equipment = BTreeSet::from(["copper seed case".into()]); - tovan.conditions = BTreeSet::from(["healed broken wrist".into()]); - tovan.obligations = BTreeSet::from(["send medicine back to the camp".into()]); - tovan.relationships = BTreeMap::from([( - "player".into(), - "remembers that they found his daughter".into(), - )]); - tovan.memories = vec!["The player found Lio beneath the fallen awning.".into()]; - value.gestalt_members.insert("tovan".into(), tovan); - value.agency_relations.insert( - "hill-resettlement".into(), - AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "hill-resettlement".into(), - from_subject_id: "refugees-east".into(), - to_subject_id: "hill-neighbors".into(), - kind: AgencyRelationKind::Migration, - strength: 85, - active: true, - evidence_receipt_ids: vec![], - }, - ); - - let before = value.gestalt_members.clone(); - let source_before = value.gestalts["refugees-east"].clone(); - let docks_before = value.gestalts["dock-neighbors"].clone(); - let hills_before = value.gestalts["hill-neighbors"].clone(); - let effective_goals = |campaign: &Campaign, id: &str| { - let member = &campaign.gestalt_members[id]; - if member.goals.is_empty() { - campaign.gestalts[&member.gestalt_id] - .goals - .iter() - .cloned() - .collect::>() - } else { - member.goals.iter().cloned().collect::>() - } - }; - let effective_before = ["mira", "tovan"] - .into_iter() - .map(|id| { - ( - id, - ( - crate::resolution::effective_member_capabilities(&value, id).unwrap(), - crate::resolution::effective_member_knowledge(&value, id).unwrap(), - effective_goals(&value, id), - ), - ) - }) - .collect::>(); - - let events = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - member_migrations: vec![ - StrategicMemberMigration { - member_id: "mira".into(), - source_gestalt_id: "refugees-east".into(), - destination_gestalt_id: "dock-neighbors".into(), - destination_location_id: "docks".into(), - public_channels: vec![], - }, - StrategicMemberMigration { - member_id: "tovan".into(), - source_gestalt_id: "refugees-east".into(), - destination_gestalt_id: "hill-neighbors".into(), - destination_location_id: "hills".into(), - public_channels: vec![], - }, - ], - ..Default::default() - }, - ) - .unwrap(); - - for (id, destination, location) in [ - ("mira", "dock-neighbors", "docks"), - ("tovan", "hill-neighbors", "hills"), - ] { - let member = &value.gestalt_members[id]; - let old = &before[id]; - assert_eq!(member.id, old.id); - assert_eq!(member.name, old.name); - assert_eq!(member.gestalt_id, destination); - assert_eq!(member.last_location_id.as_deref(), Some(location)); - assert_eq!(member.version, old.version + 1); - assert_eq!(member.relationships, old.relationships); - assert_eq!(member.memories, old.memories); - assert_eq!(member.equipment, old.equipment); - assert_eq!(member.conditions, old.conditions); - assert_eq!(member.obligations, old.obligations); - assert_eq!( - crate::resolution::effective_member_capabilities(&value, id).unwrap(), - effective_before[id].0 - ); - assert_eq!( - crate::resolution::effective_member_knowledge(&value, id).unwrap(), - effective_before[id].1 - ); - assert_eq!(effective_goals(&value, id), effective_before[id].2); - let actor = materialize_actor( - &value.gestalts[destination], - member, - &crate::domain::gestalt_member_subject_id(id), - location, - ); - assert_eq!(actor.name, old.name); - assert_eq!(actor.relationships, old.relationships); - assert_eq!(actor.memories, old.memories); - } - for (id, before, version_increment) in [ - ("refugees-east", source_before, 1), - ("dock-neighbors", docks_before, 1), - ("hill-neighbors", hills_before, 1), - ] { - let after = &value.gestalts[id]; - assert_eq!(after.name, before.name); - assert_eq!(after.home_location_id, before.home_location_id); - assert_eq!(after.shared_capabilities, before.shared_capabilities); - assert_eq!(after.shared_knowledge, before.shared_knowledge); - assert_eq!(after.resources, before.resources); - assert_eq!(after.goals, before.goals); - assert_eq!(after.pressures, before.pressures); - assert_eq!(after.version, before.version + version_increment); - } - assert_eq!(events.len(), 2); - assert_eq!(events[0].actor_ids, vec!["member:mira"]); - assert_eq!(events[1].actor_ids, vec!["member:tovan"]); - assert_eq!( - events[0].gestalt_ids, - vec!["refugees-east", "dock-neighbors"] - ); - assert_eq!( - events[1].gestalt_ids, - vec!["refugees-east", "hill-neighbors"] - ); - - let depth = |leaf_id: &str| { - let mut current = leaf_id; - let mut depth = 0; - while let Some(lineage) = value.gestalt_lineages.values().find(|lineage| { - lineage - .child_gestalt_ids - .iter() - .any(|child| child == current) - }) { - depth += 1; - current = &lineage.parent_gestalt_id; - } - depth - }; - assert_eq!(depth("refugees-east"), 2); - assert_eq!(depth("dock-neighbors"), 2); - assert_eq!(depth("hill-neighbors"), 2); - } - - #[test] - fn gestalt_migration_moves_only_the_population_leaf() { - let mut value = hierarchical_refugee_campaign(); - let member_before = value.gestalt_members["mira"].clone(); - let destination_before = value.gestalts["dock-neighbors"].clone(); - let events = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - gestalt_migrations: vec![StrategicGestaltMigration { - gestalt_id: "refugees-east".into(), - destination_gestalt_id: "dock-neighbors".into(), - destination_location_id: "docks".into(), - public_channels: vec!["camp-bulletin".into()], - }], - ..Default::default() - }, - ) - .unwrap(); - - assert_eq!(value.gestalts["refugees-east"].home_location_id, "docks"); - assert_eq!(value.gestalts["refugees-east"].version, 1); - assert_eq!( - value.agency_profiles["refugees-east"].location_ids, - BTreeSet::from(["docks".into()]) - ); - assert_eq!(value.gestalt_members["mira"], member_before); - assert_eq!(value.gestalts["dock-neighbors"], destination_before); - assert_eq!(events.len(), 1); - assert_eq!(events[0].kind, "gestalt_migration"); - assert_eq!( - events[0].summary, - "Eastern transit refugees relocates from Transit camp to South docks near South dock neighbors." - ); - assert!(!events[0].summary.contains("refugees-east")); - assert!(!events[0].summary.contains("dock-neighbors")); - assert_eq!(events[0].location_ids, vec!["camp", "docks"]); - assert_eq!( - events[0].gestalt_ids, - vec!["refugees-east", "dock-neighbors"] - ); - } - - #[test] - fn simultaneous_migration_preserves_snapshot_scoped_activity() { - let mut value = hierarchical_refugee_campaign(); - value.gestalts.insert( - "camp-neighbors".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "camp-neighbors".into(), - name: "Camp neighbors".into(), - version: 0, - home_location_id: "camp".into(), - shared_capabilities: BTreeSet::from(["raise signal fires".into()]), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec!["keep departures visible".into()], - pressures: vec![], - }, - ); - crate::resolution::ensure_agency_profiles(&mut value); - - let events = apply_strategic_tick_plan( - &mut value, - resolve_test_activities(StrategicTickPlan { - gestalt_migrations: vec![StrategicGestaltMigration { - gestalt_id: "refugees-east".into(), - destination_gestalt_id: "dock-neighbors".into(), - destination_location_id: "docks".into(), - public_channels: vec![], - }], - gestalt_activities: vec![StrategicGestaltActivity { - action_digest: test_action_digest("simultaneous communication"), - gestalt_id: "camp-neighbors".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["refugees-east".into()], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap(); - - assert_eq!(value.gestalts["refugees-east"].home_location_id, "docks"); - assert_eq!(events.len(), 2); - assert_eq!(events[1].kind, "gestalt_activity"); - assert_eq!(events[1].location_ids, vec!["camp"]); - assert_eq!( - events[1].summary, - "Camp neighbors sends a communication to Eastern transit refugees." - ); - } - - #[test] - fn cohesive_gestalt_internal_coordination_reaches_canonical_and_legacy_commit_paths() { - let action = CellActionProposal { - subject_id: "refugees-east".into(), - intent: "coordinate the households' own water watch".into(), - intended_effect: - "coordinate internal water-watch shifts without naming an external party".into(), - priority: 80, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Coordinate, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - }], - }; - let action_digest = crate::resolution::cell_action_digest(&action).unwrap(); - let mut canonical = hierarchical_refugee_campaign(); - let canonical_events = apply_strategic_tick_plan( - &mut canonical, - StrategicTickPlan { - selected_actions: vec![action], - activity_outcomes: vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest, - source_subject_id: "refugees-east".into(), - band: StrategicOutcomeBand::Mixed, - summary: "The households arrange the watch; its efficacy remains unsettled." - .into(), - supporting_state_references: vec![], - effect: StrategicOutcomeEffect::NoMaterialChange { - reason: "No external response or durable result is established.".into(), - }, - }], - ..Default::default() - }, - ) - .unwrap(); - assert_eq!(canonical_events.len(), 1); - assert_eq!(canonical_events[0].kind, "gestalt_activity"); - assert!( - canonical_events[0] - .summary - .contains("internal water-watch shifts") - ); - - let mut legacy = hierarchical_refugee_campaign(); - let legacy_events = apply_strategic_tick_plan( - &mut legacy, - resolve_test_activities(StrategicTickPlan { - gestalt_activities: vec![StrategicGestaltActivity { - action_digest: test_action_digest("internal water-watch coordination"), - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Coordinate, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap(); - assert_eq!(legacy_events.len(), 1); - assert_eq!( - legacy_events[0].summary, - "Eastern transit refugees attempts internal coordination." - ); - } - - #[test] - fn institution_posture_uses_the_canonical_character_bound_at_commit() { - let mut value = campaign(); - value.institutions.insert( - "board".into(), - InstitutionState { - id: "board".into(), - name: "Board".into(), - resources: vec![], - goals: vec![], - posture: "watching".into(), - }, - ); - crate::resolution::ensure_agency_profiles(&mut value); - let events = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - institution_actions: vec![StrategicInstitutionAction { - institution_id: "board".into(), - posture: "x".repeat(MAX_POSTURE_CHARS), - location_ids: vec![], - public_channels: vec![], - }], - ..Default::default() - }, - ) - .unwrap(); - assert_eq!(events.len(), 1); - assert!( - events[0] - .summary - .starts_with("Board announces a new course: ") - ); - assert!(!events[0].summary.contains("adopts posture")); - assert_eq!( - value.institutions["board"].posture.chars().count(), - MAX_POSTURE_CHARS - ); - - let before_oversized = value.clone(); - assert!( - apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - institution_actions: vec![StrategicInstitutionAction { - institution_id: "board".into(), - posture: "y".repeat(MAX_POSTURE_CHARS + 1), - location_ids: vec![], - public_channels: vec![], - }], - ..Default::default() - }, - ) - .is_err() - ); - assert_eq!(value, before_oversized); - } - - #[test] - fn canonical_action_commits_distinct_scopes_of_one_activity_kind() { - let mut value = hierarchical_refugee_campaign(); - let targeted = StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["dock-neighbors".into()], - location_ids: vec!["camp".into()], - }; - let local = StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - }; - let action = CellActionProposal { - subject_id: "refugees-east".into(), - intent: "Warn the dock neighbors and the unnamed camp assembly.".into(), - intended_effect: "Send both warnings without merging their audiences.".into(), - priority: 80, - state_references: vec![], - public_channels: vec![], - effects: vec![targeted.clone(), local], - }; - let action_digest = crate::resolution::cell_action_digest(&action).unwrap(); - let events = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - selected_actions: vec![action], - activity_outcomes: vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest, - source_subject_id: "refugees-east".into(), - band: StrategicOutcomeBand::Mixed, - summary: "The warnings are sent; their reception remains unsettled.".into(), - supporting_state_references: vec![], - effect: StrategicOutcomeEffect::NoMaterialChange { - reason: "No response is established in this test snapshot.".into(), - }, - }], - ..Default::default() - }, - ) - .unwrap(); - - assert_eq!(events.len(), 2); - assert!(events.iter().all(|event| event.kind == "gestalt_activity")); - assert_eq!( - events - .iter() - .map(|event| event.id.as_str()) - .collect::>() - .len(), - 2 - ); - - let before_duplicate = value.clone(); - let duplicate = CellActionProposal { - subject_id: "refugees-east".into(), - intent: "Repeat one exact warning twice.".into(), - intended_effect: "Send the same warning twice.".into(), - priority: 80, - state_references: vec![], - public_channels: vec![], - effects: vec![targeted.clone(), targeted], - }; - let duplicate_digest = crate::resolution::cell_action_digest(&duplicate).unwrap(); - let error = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - selected_actions: vec![duplicate], - activity_outcomes: vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: duplicate_digest, - source_subject_id: "refugees-east".into(), - band: StrategicOutcomeBand::Mixed, - summary: "The repeated warning has no separate durable result.".into(), - supporting_state_references: vec![], - effect: StrategicOutcomeEffect::NoMaterialChange { - reason: "No distinct response is established.".into(), - }, - }], - ..Default::default() - }, - ) - .unwrap_err(); - assert!(error.to_string().contains("acts twice"), "{error}"); - assert_eq!(value, before_duplicate); - - let aliased = CellActionProposal { - subject_id: "refugees-east".into(), - intent: "Repeat one local warning through aliased location syntax.".into(), - intended_effect: "Send one local warning.".into(), - priority: 80, - state_references: vec![], - public_channels: vec![], - effects: vec![ - StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec![], - location_ids: vec![], - }, - StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - }, - ], - }; - let aliased_digest = crate::resolution::cell_action_digest(&aliased).unwrap(); - let error = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - selected_actions: vec![aliased], - activity_outcomes: vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: aliased_digest, - source_subject_id: "refugees-east".into(), - band: StrategicOutcomeBand::Mixed, - summary: "The local warning has no separate durable result.".into(), - supporting_state_references: vec![], - effect: StrategicOutcomeEffect::NoMaterialChange { - reason: "No distinct response is established.".into(), - }, - }], - ..Default::default() - }, - ) - .unwrap_err(); - assert!(error.to_string().contains("acts twice"), "{error}"); - assert_eq!(value, before_duplicate); - } - - #[test] - fn invalid_late_strategic_action_cannot_partially_apply_an_earlier_action() { - let mut value = hierarchical_refugee_campaign(); - let before = value.clone(); - let error = apply_strategic_tick_plan( - &mut value, - resolve_test_activities(StrategicTickPlan { - gestalt_migrations: vec![StrategicGestaltMigration { - gestalt_id: "refugees-east".into(), - destination_gestalt_id: "dock-neighbors".into(), - destination_location_id: "docks".into(), - public_channels: vec![], - }], - gestalt_activities: vec![StrategicGestaltActivity { - action_digest: test_action_digest("conflicting refugee preparation"), - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap_err(); - - assert!(error.to_string().contains("acts twice")); - assert_eq!(value, before); - } - - #[test] - fn population_cannot_move_without_its_exact_migration_relation() { - let mut value = hierarchical_refugee_campaign(); - value.agency_relations.clear(); - let before = value.clone(); - let error = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - gestalt_migrations: vec![StrategicGestaltMigration { - gestalt_id: "refugees-east".into(), - destination_gestalt_id: "dock-neighbors".into(), - destination_location_id: "docks".into(), - public_channels: vec![], - }], - ..Default::default() - }, - ) - .unwrap_err(); - assert!(error.to_string().contains("source-to-destination relation")); - assert_eq!(value, before); - } - - #[test] - fn invalid_population_migration_batch_has_no_partial_move() { - let mut value = hierarchical_refugee_campaign(); - let before = value.clone(); - let action = StrategicGestaltMigration { - gestalt_id: "refugees-east".into(), - destination_gestalt_id: "dock-neighbors".into(), - destination_location_id: "docks".into(), - public_channels: vec![], - }; - let error = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - gestalt_migrations: vec![action.clone(), action], - ..Default::default() - }, - ) - .unwrap_err(); - assert!(error.to_string().contains("acts twice")); - assert_eq!(value, before); - } - - #[test] - fn member_migration_requires_the_persons_route_and_typed_population_relation() { - let mut value = hierarchical_refugee_campaign(); - value.agency_relations.clear(); - let before = value.clone(); - let error = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - member_migrations: vec![StrategicMemberMigration { - member_id: "mira".into(), - source_gestalt_id: "refugees-east".into(), - destination_gestalt_id: "dock-neighbors".into(), - destination_location_id: "docks".into(), - public_channels: vec![], - }], - ..Default::default() - }, - ) - .unwrap_err(); - assert!(error.to_string().contains("migration relation")); - assert_eq!(value.gestalt_members, before.gestalt_members); - } - - #[test] - fn gestalt_action_resolves_exact_pressure_and_records_only_the_typed_transition() { - let mut value = hierarchical_refugee_campaign(); - value.gestalts.get_mut("refugees-east").unwrap().pressures = - vec!["the storm closes the camp".into()]; - let events = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - gestalt_actions: vec![StrategicGestaltAction { - gestalt_id: "refugees-east".into(), - pressure_additions: vec!["shelter assignments remain unsettled".into()], - pressure_resolutions: vec!["the storm closes the camp".into()], - public_channels: vec![], - }], - ..Default::default() - }, - ) - .unwrap(); - assert_eq!( - value.gestalts["refugees-east"].pressures, - vec!["shelter assignments remain unsettled"] - ); - assert_eq!(value.gestalts["refugees-east"].version, 1); - assert_eq!( - events[0].summary, - "A declaration from Eastern transit refugees marks this matter settled: the storm closes the camp; New public demand from Eastern transit refugees: shelter assignments remain unsettled" - ); - } - - #[test] - fn gestalt_activity_requires_an_explicit_resolved_no_material_outcome() { - let mut value = hierarchical_refugee_campaign(); - let before = value.clone(); - let events = apply_strategic_tick_plan( - &mut value, - resolve_test_activities(StrategicTickPlan { - gestalt_activities: vec![StrategicGestaltActivity { - action_digest: test_action_digest("refugee coordination"), - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Coordinate, - target_subject_ids: vec!["dock-neighbors".into()], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap(); - assert_only_strategic_obligations_advanced(&before, &value); - assert_eq!(events.len(), 1); - assert_eq!(events[0].kind, "gestalt_activity"); - assert_eq!( - events[0].summary, - "Eastern transit refugees attempts to coordinate with South dock neighbors." - ); - assert_eq!( - events[0].gestalt_ids, - vec!["refugees-east", "dock-neighbors"] - ); - assert!(events[0].actor_ids.is_empty()); - assert!(events[0].institution_ids.is_empty()); - assert!( - events - .iter() - .all(|event| event.kind != "strategic_activity_outcome") - ); - } - - #[test] - fn durable_publication_reports_the_published_course_not_an_unfinished_publication_attempt() { - let summary = strategic_activity_summary( - "Thornweald Charcoal Guilds", - &StrategicActivityKind::Communicate, - &["Copper Synod".into()], - Some("Publish the caravan evidence and call every forest kiln to readiness"), - &["root-wire broadsheet".into()], - ); - - assert_eq!( - summary, - "Public statement from Thornweald Charcoal Guilds: Publish the caravan evidence and call every forest kiln to readiness." - ); - assert!(!summary.contains("attempt")); - } - - #[test] - fn strategic_outcome_materializes_a_bounded_resource_from_exact_capability() { - let mut value = hierarchical_refugee_campaign(); - let digest = test_action_digest("refugees prepare storm lashings"); - let events = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - gestalt_activities: vec![StrategicGestaltActivity { - action_digest: digest.clone(), - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - activity_outcomes: vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: digest, - source_subject_id: "refugees-east".into(), - band: StrategicOutcomeBand::Success, - summary: "The refugees finish a set of storm lashings.".into(), - supporting_state_references: vec![ - "capability:survive transit".into(), - "location:camp".into(), - ], - effect: StrategicOutcomeEffect::ResourceCreated { - owner_subject_id: "refugees-east".into(), - resource: "storm lashings".into(), - }, - }], - ..Default::default() - }, - ) - .unwrap(); - - assert!( - value.gestalts["refugees-east"] - .resources - .contains("storm lashings") - ); - assert_eq!(value.gestalts["refugees-east"].version, 1); - assert_eq!(events.len(), 2); - assert_eq!(events[1].kind, "strategic_activity_outcome"); - } - - #[test] - fn invalid_outcome_bundle_cannot_apply_an_earlier_material_effect() { - let mut value = hierarchical_refugee_campaign(); - let before = value.clone(); - let first = test_action_digest("valid material preparation"); - let second = test_action_digest("invalid resource spend"); - let error = apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - gestalt_activities: vec![ - StrategicGestaltActivity { - action_digest: first.clone(), - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - public_channels: vec![], - }, - StrategicGestaltActivity { - action_digest: second.clone(), - gestalt_id: "dock-neighbors".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["docks".into()], - public_channels: vec![], - }, - ], - activity_outcomes: vec![ - StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: first, - source_subject_id: "refugees-east".into(), - band: StrategicOutcomeBand::Success, - summary: "A valid first result.".into(), - supporting_state_references: vec!["capability:survive transit".into()], - effect: StrategicOutcomeEffect::ResourceCreated { - owner_subject_id: "refugees-east".into(), - resource: "valid new shelter frame".into(), - }, - }, - StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: second, - source_subject_id: "dock-neighbors".into(), - band: StrategicOutcomeBand::Failure, - summary: "An invalid second result.".into(), - supporting_state_references: vec!["capability:repair nets".into()], - effect: StrategicOutcomeEffect::ResourceConsumed { - owner_subject_id: "dock-neighbors".into(), - resource: "invented missing winch".into(), - }, - }, - ], - ..Default::default() - }, - ) - .unwrap_err(); - - assert!(error.to_string().contains("custody")); - assert_eq!(value, before); - } - - #[test] - fn member_outcome_preserves_its_own_relationship_without_mutating_the_player() { - let mut value = hierarchical_refugee_campaign(); - value.agency_relations.insert( - "refugee-message-to-player".into(), - AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "refugee-message-to-player".into(), - from_subject_id: "refugees-east".into(), - to_subject_id: "player".into(), - kind: AgencyRelationKind::Communication, - strength: 40, - active: true, - evidence_receipt_ids: vec![], - }, - ); - let player_before = value.actors["player"].clone(); - let digest = test_action_digest("mira renews her promise"); - apply_strategic_tick_plan( - &mut value, - StrategicTickPlan { - member_activities: vec![StrategicMemberActivity { - action_digest: digest.clone(), - member_id: "mira".into(), - source_gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["player".into()], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - activity_outcomes: vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: digest, - source_subject_id: "member:mira".into(), - band: StrategicOutcomeBand::Success, - summary: "Mira keeps the promise alive despite the distance.".into(), - supporting_state_references: vec!["member:mira".into()], - effect: StrategicOutcomeEffect::MemberRelationship { - member_id: "mira".into(), - other_subject_id: "player".into(), - description: "intends to find and repay the rescuer after settling".into(), - }, - }], - ..Default::default() - }, - ) - .unwrap(); - - assert_eq!(value.actors["player"], player_before); - assert_eq!( - value.gestalt_members["mira"].relationships["player"], - "intends to find and repay the rescuer after settling" - ); - } - - #[test] - fn local_investigation_needs_a_location_but_not_an_invented_actor() { - let mut value = hierarchical_refugee_campaign(); - let before = value.clone(); - let events = apply_strategic_tick_plan( - &mut value, - resolve_test_activities(StrategicTickPlan { - gestalt_activities: vec![StrategicGestaltActivity { - action_digest: test_action_digest("local refugee investigation"), - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Investigate, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap(); - assert_only_strategic_obligations_advanced(&before, &value); - assert_eq!( - events[0].summary, - "Eastern transit refugees begins a local investigation." - ); - assert!(events[0].actor_ids.is_empty()); - assert!(events[0].institution_ids.is_empty()); - } - - #[test] - fn local_communication_records_the_source_without_inventing_a_listener() { - let mut value = hierarchical_refugee_campaign(); - let before = value.clone(); - let events = apply_strategic_tick_plan( - &mut value, - resolve_test_activities(StrategicTickPlan { - gestalt_activities: vec![StrategicGestaltActivity { - action_digest: test_action_digest("local refugee communication"), - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap(); - assert_only_strategic_obligations_advanced(&before, &value); - assert_eq!( - events[0].summary, - "Eastern transit refugees attempts a local communication." - ); - assert!(events[0].actor_ids.is_empty()); - assert!(events[0].institution_ids.is_empty()); - assert_eq!(events[0].gestalt_ids, vec!["refugees-east"]); - } - - #[test] - fn local_obstruction_records_the_source_without_inventing_a_target() { - let mut value = hierarchical_refugee_campaign(); - let before = value.clone(); - let events = apply_strategic_tick_plan( - &mut value, - resolve_test_activities(StrategicTickPlan { - gestalt_activities: vec![StrategicGestaltActivity { - action_digest: test_action_digest("local infrastructure obstruction"), - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Obstruct, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap(); - assert_only_strategic_obligations_advanced(&before, &value); - assert_eq!( - events[0].summary, - "Eastern transit refugees attempts local interference." - ); - assert!(events[0].actor_ids.is_empty()); - assert!(events[0].institution_ids.is_empty()); - assert_eq!(events[0].gestalt_ids, vec!["refugees-east"]); - } - - #[test] - fn dormant_member_can_speak_locally_without_inventing_a_listener() { - let mut value = hierarchical_refugee_campaign(); - let before = value.clone(); - let events = apply_strategic_tick_plan( - &mut value, - resolve_test_activities(StrategicTickPlan { - member_activities: vec![StrategicMemberActivity { - action_digest: test_action_digest("mira local communication"), - member_id: "mira".into(), - source_gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap(); - assert_only_strategic_obligations_advanced(&before, &value); - assert_eq!( - events[0].summary, - "Mira Venn attempts a local communication." - ); - assert_eq!(events[0].actor_ids, vec!["member:mira"]); - assert!(events[0].institution_ids.is_empty()); - assert_eq!(events[0].gestalt_ids, vec!["refugees-east"]); - } - - #[test] - fn colocated_gestalt_can_address_a_dormant_member_without_absorbing_their_agency() { - let mut value = hierarchical_refugee_campaign(); - value - .gestalt_members - .get_mut("mira") - .unwrap() - .last_location_id = Some("docks".into()); - value.gestalt_members.get_mut("mira").unwrap().gestalt_id = "dock-neighbors".into(); - let before = value.clone(); - let events = apply_strategic_tick_plan( - &mut value, - resolve_test_activities(StrategicTickPlan { - gestalt_activities: vec![StrategicGestaltActivity { - action_digest: test_action_digest("neighbors address mira"), - gestalt_id: "dock-neighbors".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["member:mira".into()], - location_ids: vec!["docks".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap(); - assert_only_strategic_obligations_advanced(&before, &value); - assert_eq!(events.len(), 1); - assert_eq!( - events[0].summary, - "South dock neighbors sends a communication to Mira Venn." - ); - assert_eq!(events[0].actor_ids, vec!["member:mira"]); - assert_eq!(events[0].gestalt_ids, vec!["dock-neighbors"]); - } - - #[test] - fn gestalt_cannot_address_a_dormant_member_at_another_location() { - let mut value = hierarchical_refugee_campaign(); - let before = value.clone(); - let error = apply_strategic_tick_plan( - &mut value, - resolve_test_activities(StrategicTickPlan { - gestalt_activities: vec![StrategicGestaltActivity { - action_digest: test_action_digest("remote address mira"), - gestalt_id: "dock-neighbors".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["member:mira".into()], - location_ids: vec!["docks".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap_err(); - assert!(error.to_string().contains("exact graph or location scope")); - assert_eq!(value, before); - } - - #[test] - fn gestalt_activity_rejects_a_nonadjacent_target_without_mutation() { - let mut value = hierarchical_refugee_campaign(); - value.gestalts.insert( - "distant-crowd".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "distant-crowd".into(), - name: "Distant crowd".into(), - version: 0, - home_location_id: "docks".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - crate::resolution::ensure_agency_profiles(&mut value); - let before = value.clone(); - let error = apply_strategic_tick_plan( - &mut value, - resolve_test_activities(StrategicTickPlan { - gestalt_activities: vec![StrategicGestaltActivity { - action_digest: test_action_digest("nonadjacent communication"), - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["distant-crowd".into()], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap_err(); - assert!(error.to_string().contains("exact graph or location scope")); - assert_eq!(value, before); - } - - #[test] - fn dormant_member_activity_preserves_identity_and_population_state() { - let mut value = hierarchical_refugee_campaign(); - let before = value.clone(); - let events = apply_strategic_tick_plan( - &mut value, - resolve_test_activities(StrategicTickPlan { - member_activities: vec![StrategicMemberActivity { - action_digest: test_action_digest("mira addresses refugees"), - member_id: "mira".into(), - source_gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["refugees-east".into()], - location_ids: vec!["camp".into()], - public_channels: vec![], - }], - ..Default::default() - }), - ) - .unwrap(); - assert_only_strategic_obligations_advanced(&before, &value); - assert_eq!(events.len(), 1); - assert_eq!(events[0].kind, "gestalt_member_activity"); - assert_eq!( - events[0].summary, - "Mira Venn sends a communication to Eastern transit refugees." - ); - assert_eq!(events[0].actor_ids, vec!["member:mira"]); - assert_eq!(events[0].gestalt_ids, vec!["refugees-east"]); - } - - #[tokio::test] - async fn clock_binding_commit_is_payload_bound_atomic_and_preserves_player() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let mut seed = campaign(); - seed.revision = 14; - seed.institutions.insert( - "court".into(), - InstitutionState { - id: "court".into(), - name: "Court".into(), - resources: Vec::new(), - goals: Vec::new(), - posture: "counting knives".into(), - }, - ); - crate::resolution::ensure_agency_profiles(&mut seed); - seed.agency_profiles - .get_mut("court") - .unwrap() - .information_channels - .extend(["court broadsheet".into(), "palace wire".into()]); - seed.clocks.insert( - "coup".into(), - WorldClock { - id: "coup".into(), - label: "Coup".into(), - progress: 3, - threshold: 3, - consequence: "The palace guard arrests the regent at breakfast.".into(), - consequence_scope: WorldEventScope::default(), - }, - ); - seed.clocks.insert( - "blackout".into(), - WorldClock { - id: "blackout".into(), - label: "Blackout".into(), - progress: 2, - threshold: 2, - consequence: "The archive lamps go dark and the sealed rolls vanish.".into(), - consequence_scope: WorldEventScope::default(), - }, - ); - store - .create_unadmitted_fixture_campaign(&seed, &[], &[]) - .unwrap(); - let player_before = rmp_serde::to_vec_named(&seed.actors["player"]).unwrap(); - let bindings = vec![ - crate::clock::ClockConsequenceBinding { - clock_id: "blackout".into(), - scope: WorldEventScope { - actor_ids: Vec::new(), - institution_ids: vec!["court".into()], - gestalt_ids: Vec::new(), - location_ids: vec!["room".into()], - public_channels: Vec::new(), - }, - }, - crate::clock::ClockConsequenceBinding { - clock_id: "coup".into(), - scope: 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(), "palace wire".into()], - }, - }, - ]; - let snapshot_binding = crate::clock::clock_consequence_binding_snapshot(&seed).unwrap(); - let binding_batch_digest = - crate::clock::clock_consequence_binding_batch_digest(&seed, &bindings).unwrap(); - let mut accepted_receipt = crate::model::ModelStageReceipt { - schema: "ghostlight.persona_stage_receipt.v1".into(), - receipt_hash: String::new(), - provider: "fixture".into(), - model: "fixture-terra".into(), - stage: crate::clock::CLOCK_CONSEQUENCE_BINDING_STAGE.into(), - snapshot_binding: String::new(), - request_hash: test_action_digest("clock-binding-request"), - output_hash: test_action_digest("clock-binding-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(), - }; - accepted_receipt.rebind_snapshot(crate::clock::clock_consequence_admission_binding( - &snapshot_binding, - &binding_batch_digest, - )); - let admission = crate::clock::ClockConsequenceBindingAdmission { - schema: "ghostlight.clock_consequence_binding_admission.v1".into(), - campaign_id: seed.id, - expected_revision: seed.revision, - snapshot_binding, - binding_batch_digest, - bindings: bindings.clone(), - accepted_model_receipt_id: accepted_receipt.storage_key().to_owned(), - }; - let kernel = WorldKernel::start(store.clone()); - let CommandResult::Committed { campaign, .. } = kernel - .command(WorldCommand::BindClockConsequences { - expected_revision: seed.revision, - admission, - model_stage_receipts: vec![accepted_receipt], - }) - .await - .unwrap() - else { - panic!("clock binding did not commit") - }; - - assert_eq!( - rmp_serde::to_vec_named(&campaign.actors["player"]).unwrap(), - player_before - ); - let (_, receipt) = store - .load::( - "clock_consequence_binding_receipt.v1", - &format!("{}-{}", campaign.id, campaign.revision), - ) - .unwrap() - .unwrap(); - assert_eq!(receipt.bindings, bindings); - assert_eq!( - receipt.emitted_event_ids, - ["clock-consequence:blackout", "clock-consequence:coup"] - ); - assert_eq!(receipt.emitted_news_ids.len(), 2); - assert_eq!(receipt.news_count_before, 0); - assert_eq!(receipt.next_wave_index, 1); - } - - #[tokio::test] - async fn stale_command_cannot_mutate_campaign() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = campaign(); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - kernel - .command(WorldCommand::Wait { - expected_revision: 0, - minutes: 30, - }) - .await - .unwrap(); - let stale = kernel - .command(WorldCommand::Wait { - expected_revision: 0, - minutes: 30, - }) - .await; - assert!(matches!(stale, Err(KernelError::Stale { actual: 1, .. }))); - let (_, stored): (_, Campaign) = store - .load("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap(); - assert_eq!(stored.revision, 1); - assert_eq!(stored.world_time, seed.world_time + Duration::minutes(30)); - assert_eq!( - store.keys("mutation_authority_envelope.v1").unwrap().len(), - 1 - ); - assert_eq!(store.keys("world_mutation_batch.v1").unwrap().len(), 1); - assert_eq!(store.keys("world_mutation_receipt.v1").unwrap().len(), 1); - } - - #[tokio::test] - async fn invalid_wait_and_oversized_speech_cannot_mutate_campaign() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = campaign(); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let baseline = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - - assert!( - kernel - .command(WorldCommand::Wait { - expected_revision: 0, - minutes: 1_441, - }) - .await - .is_err() - ); - assert!( - kernel - .command(WorldCommand::Speak { - expected_revision: 0, - actor_id: "player".into(), - text: "x".repeat(4_001), - intended_effect: None, - persona_response_actor_ids: BTreeSet::new(), - }) - .await - .is_err() - ); - let stored = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(stored, baseline); - assert!(store.keys("world_commit_receipt.v1").unwrap().is_empty()); - } - - #[tokio::test] - async fn speech_can_bind_a_nearby_folded_person_then_materialize_that_exact_member() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store); - let mut seed = campaign(); - seed.gestalts.insert( - "refugees".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "refugees".into(), - name: "Refugees".into(), - version: 4, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - seed.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!["Ash repaired the coupling".into()], - last_location_id: Some("room".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }, - ); - crate::resolution::ensure_agency_profiles(&mut seed); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - - let spoken = kernel - .command(WorldCommand::Speak { - expected_revision: 0, - actor_id: "player".into(), - text: "Taren with the water handcart, is the coupling holding?".into(), - intended_effect: None, - persona_response_actor_ids: BTreeSet::from(["member:water-cart-taren".into()]), - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = spoken else { - panic!("speech did not commit") - }; - assert!(!campaign.actors.contains_key("member:water-cart-taren")); - let plan = crate::gestalt::required_addressed_promotions(&campaign).unwrap(); - assert_eq!(plan.promotions.len(), 1); - assert_eq!(plan.promotions[0].expected_gestalt_version, 4); - assert_eq!(plan.promotions[0].expected_member_version, 7); - - let reconciled = kernel - .command(WorldCommand::ReconcileGestaltPresence { - expected_revision: 1, - reason: "player says: Taren with the water handcart, is the coupling holding?" - .into(), - plan, - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = reconciled else { - panic!("addressed member was not materialized") - }; - assert!(campaign.actors.contains_key("member:water-cart-taren")); - assert_eq!( - campaign.gestalt_members["water-cart-taren"] - .materialized_actor_id - .as_deref(), - Some("member:water-cart-taren") - ); - let arrival = campaign.transcript.last().unwrap(); - assert_eq!(arrival.speaker, "world"); - assert!(arrival.text.contains("Taren")); - assert!(arrival.text.contains("Refugees")); - assert!(arrival.text.contains("Room")); - assert!( - campaign - .transcript - .iter() - .rev() - .find(|turn| turn.speaker == campaign.player_actor_id) - .unwrap() - .persona_response_actor_ids - == BTreeSet::from(["member:water-cart-taren".into()]) - ); - } - - #[tokio::test] - async fn npc_speech_does_not_impersonate_player_activity() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store); - let mut seed = campaign(); - let inactive_since = Utc::now() - Duration::hours(2); - seed.last_player_activity = inactive_since; - let mut npc = seed.actors["player"].clone(); - npc.id = "npc".into(); - npc.name = "NPC".into(); - seed.actors.insert("npc".into(), npc); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let result = kernel - .command(WorldCommand::Speak { - expected_revision: 0, - actor_id: "npc".into(), - text: "The world does not wait.".into(), - intended_effect: None, - persona_response_actor_ids: BTreeSet::new(), - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!() - }; - assert_eq!(campaign.last_player_activity, inactive_since); - } - - #[tokio::test] - async fn assessment_is_private_and_attempt_commits_roll_atomically() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = campaign(); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let result = kernel - .command(WorldCommand::Assess { - expected_revision: 0, - intent: ActionIntent { - actor_id: "player".into(), - description: "Open the ordinary door".into(), - intended_effect: "Pass through".into(), - }, - proposal: None, - }) - .await - .unwrap(); - let CommandResult::Assessed { assessment } = result else { - panic!("expected assessment") - }; - let (_, before): (_, Campaign) = store - .load("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap(); - assert_eq!(before.revision, 0); - let result = kernel - .command(WorldCommand::Attempt { - actor_id: "player".into(), - assessment_digest: assessment.digest, - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, receipt } = result else { - panic!("expected commit") - }; - assert_eq!(campaign.revision, 1); - assert!(receipt.roll.is_some()); - assert_eq!(store.keys("world_commit_receipt.v1").unwrap().len(), 1); - assert_eq!(store.keys("roll_receipt.v1").unwrap().len(), 1); - assert_eq!( - store.keys("mutation_authority_envelope.v1").unwrap().len(), - 1 - ); - assert_eq!(store.keys("world_mutation_batch.v1").unwrap().len(), 1); - assert_eq!(store.keys("world_mutation_receipt.v1").unwrap().len(), 1); - } - - #[tokio::test] - async fn repair_assessment_persists_reduced_world_pressure() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.institutions.insert( - "clinic".into(), - InstitutionState { - id: "clinic".into(), - name: "Clinic".into(), - resources: Vec::new(), - goals: Vec::new(), - posture: "repairing the regulator".into(), - }, - ); - seed.clocks.insert( - "clinic-failure".into(), - WorldClock { - id: "clinic-failure".into(), - label: "Clinic failure".into(), - progress: 3, - threshold: 4, - consequence: "The regulator fails.".into(), - consequence_scope: WorldEventScope { - actor_ids: Vec::new(), - institution_ids: vec!["clinic".into()], - gestalt_ids: Vec::new(), - location_ids: vec!["room".into()], - public_channels: Vec::new(), - }, - }, - ); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let intent = ActionIntent { - actor_id: "player".into(), - description: "Patch the failing regulator seal".into(), - intended_effect: "Relieve immediate clinic failure pressure".into(), - }; - let reduction = WorldEffectDelta { - clock_reductions: BTreeMap::from([("clinic-failure".into(), 2)]), - ..Default::default() - }; - let mut assessment = assess(&seed, intent.clone()); - assessment.strong_effect = reduction.clone(); - assessment.success_effect = reduction.clone(); - assessment.mixed_effect = reduction.clone(); - // Keep the effect identical across bands so this test exercises the - // atomic reduction primitive independently of the OS-random roll. - assessment.failure_effect = reduction; - assessment.digest = crate::assessor::assessment_digest(&assessment).unwrap(); - kernel - .command(WorldCommand::Assess { - expected_revision: 0, - intent, - proposal: Some(assessment.clone()), - }) - .await - .unwrap(); - let result = kernel - .command(WorldCommand::Attempt { - actor_id: "player".into(), - assessment_digest: assessment.digest, - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!("expected repair commit") - }; - - assert_eq!(campaign.clocks["clinic-failure"].progress, 1); - assert_eq!(campaign.revision, 1); - } - - #[tokio::test] - async fn stale_assessment_returns_original_intent_for_fresh_compilation() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = campaign(); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let intent = ActionIntent { - actor_id: "player".into(), - description: "Open the ordinary door".into(), - intended_effect: "Pass through".into(), - }; - let CommandResult::Assessed { assessment } = kernel - .command(WorldCommand::Assess { - expected_revision: 0, - intent: intent.clone(), - proposal: None, - }) - .await - .unwrap() - else { - panic!() - }; - kernel - .command(WorldCommand::Speak { - expected_revision: 0, - actor_id: "player".into(), - text: "Wait.".into(), - intended_effect: None, - persona_response_actor_ids: BTreeSet::new(), - }) - .await - .unwrap(); - let error = kernel - .command(WorldCommand::Attempt { - actor_id: "player".into(), - assessment_digest: assessment.digest, - }) - .await - .unwrap_err(); - match error { - KernelError::StaleAssessment { - intent: stale_intent, - actual_revision, - } => { - assert_eq!(stale_intent, intent); - assert_eq!(actual_revision, 1); - } - other => panic!("unexpected error: {other}"), - } - assert!(store.keys("roll_receipt.v1").unwrap().is_empty()); - } - - #[tokio::test] - async fn strategic_tick_without_an_admitted_wave_advances_only_deterministic_obligations() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.institutions.insert( - "board".into(), - InstitutionState { - id: "board".into(), - name: "Board".into(), - resources: vec!["permits".into()], - goals: vec!["contain the strike".into()], - posture: "watching".into(), - }, - ); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let result = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: None, - resolution_wave: None, - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!("expected commit") - }; - assert!(campaign.events.is_empty()); - assert!(campaign.news.is_empty()); - assert_eq!(campaign.away_ticks_processed, 1); - assert_eq!(campaign.institutions["board"].posture, "watching"); - assert_eq!(campaign.world_time, seed.world_time + Duration::hours(6)); - let ticks = store - .load_all::("strategic_tick.v1") - .unwrap(); - assert_eq!(ticks.len(), 1); - assert_eq!(ticks[0].source, TickSource::Scheduler); - assert!(ticks[0].event_ids.is_empty()); - assert!(ticks[0].model_receipt_hash.is_none()); - assert_eq!(store.keys("world_mutation_receipt.v1").unwrap().len(), 1); - } - - #[tokio::test] - async fn strategic_tick_receipt_includes_derived_clock_consequence() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.institutions.insert( - "court".into(), - InstitutionState { - id: "court".into(), - name: "Court".into(), - resources: Vec::new(), - goals: Vec::new(), - posture: "waiting for the bell".into(), - }, - ); - crate::resolution::ensure_agency_profiles(&mut seed); - seed.agency_profiles - .get_mut("court") - .unwrap() - .information_channels - .insert("court broadsheet".into()); - seed.clocks.insert( - "coup".into(), - WorldClock { - id: "coup".into(), - label: "Coup".into(), - progress: 0, - threshold: 1, - consequence: "The palace guard arrests the regent at breakfast.".into(), - consequence_scope: 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()], - }, - }, - ); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: Vec::new(), - model_stage_receipts: Vec::new(), - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: None, - resolution_wave: None, - }) - .await - .unwrap() - else { - panic!("expected strategic tick commit") - }; - let ticks = store - .load_all::("strategic_tick.v1") - .unwrap(); - - assert_eq!(ticks[0].event_ids, ["clock-consequence:coup"]); - assert!( - campaign - .events - .iter() - .any(|event| event.id == "clock-consequence:coup") - ); - assert!( - campaign - .news - .iter() - .any(|news| news.event_ids == ["clock-consequence:coup"]) - ); - } - - #[tokio::test] - async fn strategic_plan_moves_remote_actors_but_cannot_puppet_the_player() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.locations.get_mut("room").unwrap().routes.insert( - "road".into(), - Route { - destination_id: "yard".into(), - distance: "near".into(), - travel_minutes: 20, - }, - ); - seed.locations.insert( - "yard".into(), - Location { - id: "yard".into(), - name: "Yard".into(), - container_id: None, - routes: BTreeMap::from([( - "back".into(), - Route { - destination_id: "room".into(), - distance: "near".into(), - travel_minutes: 20, - }, - )]), - persistent_features: vec![], - }, - ); - let mut npc = seed.actors["player"].clone(); - npc.id = "runner".into(); - npc.name = "Runner".into(); - seed.actors.insert(npc.id.clone(), npc); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - - let puppet = crate::domain::StrategicTickPlan { - actor_moves: vec![crate::domain::StrategicActorMove { - actor_id: "player".into(), - destination_id: "yard".into(), - public_channels: vec![], - }], - ..Default::default() - }; - assert!(matches!( - kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: Some(puppet), - model_receipt_hash: Some(format!("sha256:{}", "a".repeat(64))), - resolution_wave: None, - }) - .await, - Err(KernelError::Invalid(_)) - )); - let (_, unchanged): (_, Campaign) = store - .load("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap(); - assert_eq!(unchanged.revision, 0); - assert_eq!(unchanged.actors["player"].location_id, "room"); - - let valid = crate::domain::StrategicTickPlan { - actor_moves: vec![crate::domain::StrategicActorMove { - actor_id: "runner".into(), - destination_id: "yard".into(), - public_channels: vec!["courier-network".into()], - }], - ..Default::default() - }; - let result = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: Some(valid), - model_receipt_hash: Some(format!("sha256:{}", "b".repeat(64))), - resolution_wave: None, - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!("expected commit") - }; - assert_eq!(campaign.actors["runner"].location_id, "yard"); - assert_eq!(campaign.actors["player"].location_id, "room"); - assert_eq!(campaign.events[0].kind, "actor_movement"); - assert_eq!( - campaign.events[0].summary, - "Runner moves from Room to Yard." - ); - assert!(!campaign.events[0].summary.contains("room")); - assert!(!campaign.events[0].summary.contains("yard")); - let ticks = store - .load_all::("strategic_tick.v1") - .unwrap(); - assert_eq!( - ticks[0].model_receipt_hash, - Some(format!("sha256:{}", "b".repeat(64))) - ); - - let actor_activity = resolve_test_activities(crate::domain::StrategicTickPlan { - actor_activities: vec![crate::domain::StrategicActorActivity { - action_digest: test_action_digest("runner-investigates-yard"), - actor_id: "runner".into(), - activity: StrategicActivityKind::Investigate, - target_subject_ids: vec![], - location_ids: vec!["yard".into()], - public_channels: vec![], - }], - ..Default::default() - }); - let result = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 1, - source: TickSource::Scheduler, - plan: Some(actor_activity), - model_receipt_hash: Some(format!("sha256:{}", "c".repeat(64))), - resolution_wave: None, - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!("expected commit") - }; - assert_eq!(campaign.actors["runner"].location_id, "yard"); - assert_eq!(campaign.actors["player"].location_id, "room"); - assert!( - campaign - .events - .iter() - .any(|event| event.kind == "actor_activity" - && event.actor_ids.contains(&"runner".to_owned())) - ); - assert!( - campaign - .events - .iter() - .all(|event| event.kind != "strategic_activity_outcome") - ); - - let origin_activity = crate::domain::CellActionProposal { - subject_id: "runner".into(), - intent: "Repair the yard marker, then return to the room.".into(), - intended_effect: "Attempt the repair before leaving the yard.".into(), - priority: 50, - state_references: vec![], - public_channels: vec![], - effects: vec![ - crate::domain::StrategicCellEffect::ActorMove { - actor_id: "runner".into(), - destination_id: "room".into(), - }, - crate::domain::StrategicCellEffect::ActorActivity { - actor_id: "runner".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["yard".into()], - }, - ], - }; - let action_digest = crate::resolution::cell_action_digest(&origin_activity).unwrap(); - let result = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 2, - source: TickSource::Scheduler, - plan: Some(StrategicTickPlan { - selected_actions: vec![origin_activity], - activity_outcomes: vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: action_digest.clone(), - source_subject_id: "runner".into(), - band: StrategicOutcomeBand::Mixed, - summary: "The yard repair remains provisional.".into(), - supporting_state_references: vec![], - effect: StrategicOutcomeEffect::NoMaterialChange { - reason: "The repair did not establish a durable state change.".into(), - }, - }], - ..StrategicTickPlan::default() - }), - model_receipt_hash: Some(format!("sha256:{}", "d".repeat(64))), - resolution_wave: None, - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!("expected commit") - }; - assert_eq!(campaign.actors["runner"].location_id, "room"); - let activity_index = campaign - .events - .iter() - .position(|event| { - event - .id - .starts_with("strategic:3:actor-activity:runner:prepare:") - }) - .unwrap(); - let movement_index = campaign - .events - .iter() - .position(|event| event.id == "strategic:3:actor:runner") - .unwrap(); - assert_eq!( - campaign.events[activity_index].summary, - "Runner attempts the repair before leaving the yard." - ); - assert!( - campaign - .events - .iter() - .all(|event| !event.id.starts_with("strategic:3:activity-outcome:")) - ); - assert!(activity_index < movement_index); - } - - #[tokio::test] - async fn region_expansion_commits_topology_evidence_and_candidate_together() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = campaign(); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let evidence = VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: "vault:route".into(), - provider: "fixture".into(), - query_hash: "sha256:q".into(), - witnesses: vec![SourceWitness { - source_id: "lore/roads.md".into(), - exact_locator: "line:10".into(), - content_hash: "sha256:witness".into(), - excerpt: "The annex road remains open.".into(), - authority_lane: "canon".into(), - temporal_scope: "fixture-era".into(), - }], - retrieved_at: Utc::now(), - }; - let candidate = CanonCandidate { - schema: "ghostlight.canon_candidate.v1".into(), - id: "candidate:gate".into(), - originating_campaign_id: seed.id, - gap: "Who owns the gate?".into(), - evidence_receipt_ids: vec![evidence.id.clone()], - conflicts: vec![], - proposed_wording: "Clarify gate ownership".into(), - affected_vault_sources: vec![], - status: "review".into(), - }; - let location = Location { - id: "annex".into(), - name: "Annex".into(), - container_id: None, - routes: BTreeMap::from([( - "back".into(), - Route { - destination_id: "room".into(), - distance: "near".into(), - travel_minutes: 10, - }, - )]), - persistent_features: vec!["stable annex".into()], - }; - let result = kernel - .command(WorldCommand::ExpandRegion { - expected_revision: 0, - expansion: RegionExpansion { - origin_location_id: "room".into(), - origin_routes: BTreeMap::from([( - "to-annex".into(), - Route { - destination_id: "annex".into(), - distance: "near".into(), - travel_minutes: 10, - }, - )]), - locations: vec![location], - facts: vec![WorldFact { - id: "annex-gate".into(), - statement: "The annex gate is maintained from the inner booth.".into(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec![evidence.id.clone()], - discoverable_at_location_ids: BTreeSet::from(["annex".into()]), - }], - populations: vec![], - population_profiles: vec![], - migration_relations: vec![], - institutions: vec![], - institution_profiles: vec![], - local_relations: vec![], - civic_system: None, - }, - evidence_receipts: vec![evidence], - canon_candidates: vec![candidate], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!("expected commit") - }; - assert!(campaign.locations.contains_key("annex")); - assert_eq!( - campaign.locations["room"].routes["to-annex"].destination_id, - "annex" - ); - assert_eq!(campaign.revision, 1); - assert_eq!( - campaign.facts["annex-gate"].discoverable_at_location_ids, - BTreeSet::from(["annex".into()]) - ); - assert_eq!(store.keys("vault_evidence_receipt.v1").unwrap().len(), 1); - assert_eq!(store.keys("canon_candidate.v1").unwrap().len(), 1); - assert_eq!(store.keys("world_mutation_batch.v1").unwrap().len(), 1); - assert_eq!(store.keys("world_mutation_receipt.v1").unwrap().len(), 1); - let batches = store - .load_all::("world_mutation_batch.v1") - .unwrap(); - assert_eq!(batches[0].mutations.len(), 4); - assert_eq!( - batches[0] - .mutations - .iter() - .filter(|mutation| matches!( - &mutation.mutation, - crate::transition::WorldMutation::AdmitEntity { .. } - )) - .count(), - 2 - ); - let (_, manifest): (_, VaultManifest) = store - .load("vault_manifest.v1", &seed.id.to_string()) - .unwrap() - .unwrap(); - assert!(manifest.source_ids.contains("lore/roads.md")); - assert!(manifest.authority_lanes.contains("canon")); - assert!(manifest.temporal_scopes.contains("fixture-era")); - } - - #[tokio::test] - async fn inhabited_region_admission_preserves_people_and_invalidates_only_derived_cover() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.gestalts.insert( - "refugees".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "refugees".into(), - name: "Refugees".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec!["seek voluntary settlement".into()], - pressures: vec![], - }, - ); - seed.gestalt_members.insert( - "taren".into(), - GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "taren".into(), - gestalt_id: "refugees".into(), - version: 3, - 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!["reach the ridge villages".into()], - memories: vec!["Ash repaired my regulator".into()], - last_location_id: Some("room".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }, - ); - crate::resolution::ensure_agency_profiles(&mut seed); - let original_member = seed.gestalt_members["taren"].clone(); - let original_epoch = seed.resolution_policy.resolution_epoch; - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let evidence = VaultEvidenceReceipt { - schema: "ghostlight.vault_evidence_receipt.v1".into(), - id: "vault:ridge".into(), - provider: "fixture".into(), - query_hash: "sha256:q".into(), - witnesses: vec![], - retrieved_at: Utc::now(), - }; - let statement = "The ridge assembly governs voluntary admission.".to_owned(); - let population = GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "ridge-households".into(), - name: "Ridge Households".into(), - version: 0, - home_location_id: "ridge".into(), - shared_capabilities: BTreeSet::from(["communal agriculture".into()]), - shared_knowledge: BTreeSet::from([statement.clone()]), - resources: BTreeSet::from(["shared kitchen".into()]), - goals: vec!["decide admissions collectively".into()], - pressures: vec!["winter capacity is finite".into()], - }; - let profile = AgencyProfile { - schema: "ghostlight.agency_profile.v1".into(), - id: "agency:ridge-households".into(), - subject_id: population.id.clone(), - subject_kind: AgencySubjectKind::Gestalt, - profile_version: 0, - collective_authority_id: Some(population.id.clone()), - parent_subject_id: None, - active_leaf: true, - simulation_eligible: true, - facets: BTreeMap::from([ - (AgencyAxis::Geography, BTreeSet::from(["ridge".into()])), - (AgencyAxis::Ideology, BTreeSet::from(["consent".into()])), - (AgencyAxis::Authority, BTreeSet::from(["assembly".into()])), - ( - AgencyAxis::EconomyRole, - BTreeSet::from(["agriculture".into()]), - ), - (AgencyAxis::SpeciesBody, BTreeSet::from(["mixed".into()])), - (AgencyAxis::Information, BTreeSet::from(["local".into()])), - ]), - location_ids: BTreeSet::from(["ridge".into()]), - information_channels: BTreeSet::from(["village assembly bulletin".into()]), - detail_debt: 0, - last_detail_tick: 0, - evidence_receipt_ids: vec![evidence.id.clone()], - }; - let relation = AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "migration:refugees:ridge".into(), - from_subject_id: "refugees".into(), - to_subject_id: population.id.clone(), - kind: AgencyRelationKind::Migration, - strength: 50, - active: true, - evidence_receipt_ids: vec![evidence.id.clone()], - }; - let result = kernel - .command(WorldCommand::ExpandRegion { - expected_revision: 0, - expansion: RegionExpansion { - origin_location_id: "room".into(), - origin_routes: BTreeMap::from([( - "to-ridge".into(), - Route { - destination_id: "ridge".into(), - distance: "2 km".into(), - travel_minutes: 20, - }, - )]), - locations: vec![Location { - id: "ridge".into(), - name: "Ridge Village".into(), - container_id: None, - routes: BTreeMap::from([( - "to-room".into(), - Route { - destination_id: "room".into(), - distance: "2 km".into(), - travel_minutes: 20, - }, - )]), - persistent_features: vec!["assembly hall".into()], - }], - facts: vec![WorldFact { - id: "ridge-admission".into(), - statement, - scope: FactScope::ProvisionalLocal, - evidence_receipt_ids: vec![evidence.id.clone()], - discoverable_at_location_ids: BTreeSet::from(["ridge".into()]), - }], - populations: vec![population], - population_profiles: vec![profile], - migration_relations: vec![relation], - institutions: vec![], - institution_profiles: vec![], - local_relations: vec![], - civic_system: None, - }, - evidence_receipts: vec![evidence], - canon_candidates: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!("expected commit") - }; - assert_eq!(campaign.gestalt_members["taren"], original_member); - assert_eq!(campaign.gestalts["refugees"].home_location_id, "room"); - assert_eq!( - campaign.gestalts["ridge-households"].home_location_id, - "ridge" - ); - assert_eq!( - campaign.agency_relations["migration:refugees:ridge"].kind, - AgencyRelationKind::Migration - ); - assert_eq!( - campaign.resolution_policy.resolution_epoch, - original_epoch + 1 - ); - assert!(campaign.resolution_cover.is_none()); - assert_eq!( - crate::resolution::gestalt_migration_destinations(&campaign, "refugees", "room")["ridge-households"], - "ridge" - ); - } - - #[tokio::test] - async fn locality_elaboration_preserves_the_city_and_grounds_a_named_residents_vote() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store); - let seed = campaign(); - let original = seed.locations["room"].clone(); - let mut elaboration = civic_locality_elaboration(); - let verifier_receipt = civic_verifier_receipt(&seed, &mut elaboration.expansion, vec![]); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - - let committed = kernel - .command(WorldCommand::ElaborateLocality { - expected_revision: 0, - elaboration, - evidence_receipts: vec![], - canon_candidates: vec![], - model_stage_receipts: vec![verifier_receipt], - }) - .await - .unwrap(); - let CommandResult::Committed { - campaign: elaborated, - .. - } = committed - else { - panic!("expected committed locality elaboration") - }; - assert_eq!(elaborated.locations["room"].id, original.id); - assert_eq!(elaborated.locations["room"].name, original.name); - assert_eq!( - elaborated.locations["room"].persistent_features, - original.persistent_features - ); - assert_eq!( - elaborated.locations["civic-quarter"] - .container_id - .as_deref(), - Some("room") - ); - assert_eq!(elaborated.institutions.len(), 2); - assert_eq!(elaborated.civic_systems["room"].version, 0); - assert!( - !elaborated.civic_systems["room"] - .semantic_verification_receipt_id - .is_empty() - ); - assert_eq!( - elaborated.agency_relations["relation:mayor-assembly"].kind, - AgencyRelationKind::Rivalry - ); - let selection = elaborated.facts["fact:room-selection"].statement.clone(); - assert!( - elaborated.gestalts["room-residents"] - .shared_knowledge - .contains(&selection) - ); - - let named = kernel - .command(WorldCommand::IndividuateGestaltMember { - expected_revision: 1, - individuation: GestaltIndividuation { - gestalt_id: "room-residents".into(), - expected_gestalt_version: 0, - member: GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "iren-vale".into(), - gestalt_id: "room-residents".into(), - version: 0, - name: "Iren Vale".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!["make berth dues transparent".into()], - memories: vec![ - "I voted for Oren Vale because he promised a public berth audit." - .into(), - ], - last_location_id: Some("civic-quarter".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }, - location_id: "civic-quarter".into(), - }, - }) - .await - .unwrap(); - let CommandResult::Committed { - campaign: individuated, - .. - } = named - else { - panic!("expected committed resident individuation") - }; - let resident = &individuated.actors["member:iren-vale"]; - assert!(resident.knowledge.contains(&selection)); - assert!(resident.memories[0].contains("Oren Vale")); - let resident_profile = &individuated.agency_profiles["member:iren-vale"]; - assert!(resident_profile.active_leaf); - assert!(resident_profile.simulation_eligible); - assert_eq!( - crate::elaboration::canonical_actionable_subject_count(&individuated), - crate::elaboration::canonical_actionable_subject_count(&elaborated) + 1 - ); - } - - #[tokio::test] - async fn elaboration_admission_keeps_the_first_writer_and_exposes_the_conflict() { - use crate::elaboration::{ - ElaboratorTitle, WorldElaborationOperation, admit_world_elaboration_wave, - }; - let seed = campaign(); - let first = WorldElaborationOperation::AddPlace { - id: "north-gate".into(), - name: "Northern Gate".into(), - container_id: Some("room".into()), - persistent_features: vec!["A duck statue locals call Harold".into()], - }; - let second = WorldElaborationOperation::AddPlace { - id: "north-gate".into(), - name: "North Tollhouse".into(), - container_id: Some("room".into()), - persistent_features: vec!["A toll bell".into()], - }; - let run = dispatch_titled_operations( - &seed, - "room", - vec![ - (ElaboratorTitle::Patina, first), - (ElaboratorTitle::Ledger, second), - ], - ) - .await; - - let admission = admit_world_elaboration_wave(&seed, "room", run).unwrap(); - - assert_eq!(admission.accepted_operations().len(), 1); - assert_eq!(admission.rejections().len(), 1); - assert_eq!( - admission.rejections()[0].kind, - crate::elaboration::WorldElaborationRejectionKind::WriteConflict - ); - assert_eq!( - admission.rejections()[0].conflicting_dispatch_ordinal, - Some(1) - ); - assert!(admission.candidate_diagnostic().is_some()); - } - - #[tokio::test] - async fn invalid_civic_locality_leaves_the_coarse_city_untouched() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = campaign(); - let campaign_id = seed.id; - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let mut elaboration = civic_locality_elaboration(); - elaboration.expansion.populations[0] - .shared_knowledge - .remove("Residents elected Selka Vey over Oren Vale at the last mayoral ballot."); - - let error = kernel - .command(WorldCommand::ElaborateLocality { - expected_revision: 0, - elaboration, - evidence_receipts: vec![], - canon_candidates: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap_err(); - assert!(error.to_string().contains("public civic facts")); - let stored = store - .load::("campaign.v1", &campaign_id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(stored.revision, 0); - assert_eq!(stored.locations.len(), 1); - assert!(stored.institutions.is_empty()); - assert!(stored.gestalts.is_empty()); - } - - #[tokio::test] - async fn structurally_valid_civic_locality_requires_its_bound_semantic_receipt() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = campaign(); - let campaign_id = seed.id; - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - - let error = kernel - .command(WorldCommand::ElaborateLocality { - expected_revision: 0, - elaboration: civic_locality_elaboration(), - evidence_receipts: vec![], - canon_candidates: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap_err(); - assert!( - error.to_string().contains("semantic verifier receipt"), - "{error}" - ); - let stored = store - .load::("campaign.v1", &campaign_id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(stored.revision, 0); - assert!(stored.civic_systems.is_empty()); - assert!(stored.institutions.is_empty()); - } - - #[tokio::test] - async fn gestalt_member_dematerializes_to_delta_and_returns_as_same_person() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.locations.insert( - "away".into(), - Location { - id: "away".into(), - name: "Away".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - ); - seed.actors.get_mut("player").unwrap().location_id = "away".into(); - seed.gestalts.insert( - "village".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "village".into(), - name: "The villagers".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::from(["basic smithing".into()]), - shared_knowledge: BTreeSet::from(["village roads".into()]), - resources: BTreeSet::new(), - goals: vec!["keep the village fed".into()], - pressures: vec![], - }, - ); - let gestalt_baseline = seed.gestalts["village"].clone(); - crate::resolution::ensure_agency_profiles(&mut seed); - let demand = crate::resolution::default_demand(&seed, "pre-materialization cover"); - seed.resolution_cover = Some(crate::resolution::plan_cover(&seed, demand).unwrap()); - let john = GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "john".into(), - gestalt_id: "village".into(), - version: 0, - name: "John".into(), - capability_additions: BTreeSet::from(["master blacksmith".into()]), - capability_removals: BTreeSet::new(), - knowledge_additions: BTreeSet::new(), - knowledge_removals: BTreeSet::new(), - equipment: BTreeSet::from(["John's hammer".into()]), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::from([("player".into(), "new acquaintance".into())]), - goals: vec![], - memories: vec!["met the player".into()], - last_location_id: None, - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }; - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let first = kernel - .command(WorldCommand::IndividuateGestaltMember { - expected_revision: 0, - individuation: GestaltIndividuation { - gestalt_id: "village".into(), - expected_gestalt_version: 0, - member: john, - location_id: "room".into(), - }, - }) - .await - .unwrap(); - let CommandResult::Committed { - campaign: first, .. - } = first - else { - panic!() - }; - assert!( - first.actors["member:john"] - .capabilities - .contains("master blacksmith") - ); - assert_eq!(first.resolution_policy.resolution_epoch, 1); - assert!(first.resolution_cover.is_none()); - assert!( - kernel - .command(WorldCommand::DematerializeGestaltMember { - expected_revision: 1, - actor_id: "member:john".into(), - }) - .await - .unwrap_err() - .to_string() - .contains("lease") - ); - kernel - .command(WorldCommand::Wait { - expected_revision: 1, - minutes: 1, - }) - .await - .unwrap(); - let folded = kernel - .command(WorldCommand::DematerializeGestaltMember { - expected_revision: 2, - actor_id: "member:john".into(), - }) - .await - .unwrap(); - let CommandResult::Committed { - campaign: folded, .. - } = folded - else { - panic!() - }; - assert!(!folded.actors.contains_key("member:john")); - assert_eq!(folded.resolution_policy.resolution_epoch, 2); - assert!(folded.resolution_cover.is_none()); - assert_eq!( - folded.gestalt_members["john"].memories, - vec!["met the player"] - ); - let again = kernel - .command(WorldCommand::MaterializeGestaltMember { - expected_revision: 3, - gestalt_id: "village".into(), - expected_gestalt_version: 0, - member_id: "john".into(), - expected_member_version: 2, - location_id: "room".into(), - }) - .await - .unwrap(); - let CommandResult::Committed { - campaign: again, .. - } = again - else { - panic!() - }; - assert_eq!(again.actors["member:john"].name, "John"); - assert_eq!( - again.actors["member:john"].relationships["player"], - "new acquaintance" - ); - assert_eq!(again.gestalts["village"], gestalt_baseline); - assert_eq!(again.resolution_policy.resolution_epoch, 3); - assert!(again.resolution_cover.is_none()); - - let bad_plan = GestaltPresencePlan { - individuations: vec![], - demotions: vec![GestaltDemotion { - actor_id: "member:john".into(), - }], - promotions: vec![GestaltPromotion { - gestalt_id: "village".into(), - expected_gestalt_version: 0, - member_id: "invented-person".into(), - expected_member_version: 0, - location_id: "room".into(), - }], - }; - assert!( - kernel - .command(WorldCommand::ReconcileGestaltPresence { - expected_revision: 4, - reason: "scene relevance changed".into(), - plan: bad_plan, - }) - .await - .is_err() - ); - let persisted = store - .load::("campaign.v1", &again.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(persisted.revision, 4); - assert!(persisted.actors.contains_key("member:john")); - assert_eq!( - persisted.gestalt_members["john"] - .materialized_actor_id - .as_deref(), - Some("member:john") - ); - let receipts = store - .load_all::( - "gestalt_materialization_receipt.v1", - ) - .unwrap(); - assert_eq!(receipts.len(), 3); - assert_eq!(receipts[0].changes[0].operation, "materialized"); - assert_eq!(receipts[1].changes[0].operation, "dematerialized"); - assert_eq!(receipts[2].changes[0].member_id, "john"); - assert_eq!(receipts[0].previous_resolution_epoch, 0); - assert_eq!(receipts[0].resolution_epoch, 1); - assert_eq!(receipts[1].resolution_epoch, 2); - assert_eq!(receipts[2].resolution_epoch, 3); - } - - #[tokio::test] - async fn directly_addressed_persona_must_commit_an_observable_response() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.actors.insert( - "anna".into(), - ActorState { - id: "anna".into(), - name: "Anna".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - seed.transcript.push(NarrativeTurn { - revision: 0, - at: seed.world_time, - speaker: "player".into(), - text: "Anna, answer me.".into(), - persona_response_actor_ids: BTreeSet::from(["anna".into()]), - }); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - - let silent = ActorReaction { - actor_id: "anna".into(), - speech: None, - deliberate_silence: false, - private_delta: ActorStateDelta::default(), - action_proposals: vec![], - }; - let error = kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 0, - event_summary: "player says: Anna, answer me.".into(), - reactions: vec![silent], - gestalt_reactions: vec![], - }) - .await - .unwrap_err(); - assert!(error.to_string().contains("no observable response")); - assert_eq!( - store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1 - .revision, - 0 - ); - - let committed = kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 0, - event_summary: "player says: Anna, answer me.".into(), - reactions: vec![ActorReaction { - actor_id: "anna".into(), - speech: None, - deliberate_silence: true, - private_delta: ActorStateDelta::default(), - action_proposals: vec![], - }], - gestalt_reactions: vec![], - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = committed else { - panic!() - }; - assert_eq!(campaign.revision, 1); - assert_eq!( - campaign.transcript.last().unwrap().text, - "deliberately does not answer." - ); - } - - #[tokio::test] - async fn directly_addressed_local_gestalt_reacts_as_its_exact_collective_subject() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.gestalts.insert( - "households".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "households".into(), - name: "Settlement households".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::from(["collective refusal".into()]), - shared_knowledge: BTreeSet::from(["the slate omits five names".into()]), - resources: BTreeSet::new(), - goals: vec!["keep every household traceable".into()], - pressures: vec!["the convoy slate is closing".into()], - }, - ); - seed.transcript.push(NarrativeTurn { - revision: 0, - at: seed.world_time, - speaker: "player".into(), - text: "Households, will you refuse the slate?".into(), - persona_response_actor_ids: BTreeSet::from(["households".into()]), - }); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - - let missing = kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 0, - event_summary: "player says: Households, will you refuse the slate?".into(), - reactions: vec![], - gestalt_reactions: vec![], - }) - .await - .unwrap_err(); - assert!(missing.to_string().contains("no observable response")); - - let committed = kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 0, - event_summary: "player says: Households, will you refuse the slate?".into(), - reactions: vec![], - gestalt_reactions: vec![GestaltReaction { - gestalt_id: "households".into(), - speech: Some( - "We will refuse a slate that leaves our names untraceable.".into(), - ), - deliberate_silence: false, - }], - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = committed else { - panic!() - }; - assert_eq!(campaign.revision, 1); - assert_eq!(campaign.transcript.last().unwrap().speaker, "households"); - assert_eq!( - campaign.events.last().unwrap().gestalt_ids, - vec!["households"] - ); - assert_eq!(campaign.gestalts["households"], seed.gestalts["households"]); - } - - #[tokio::test] - async fn invalid_reaction_rejects_the_entire_wave_without_mutation() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - for id in ["anna", "bert"] { - seed.actors.insert( - id.into(), - ActorState { - id: id.into(), - name: id.into(), - location_id: "room".into(), - capabilities: BTreeSet::from(["observe".into()]), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - } - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let reactions = vec![ - ActorReaction { - actor_id: "anna".into(), - speech: Some("I saw that.".into()), - deliberate_silence: false, - private_delta: ActorStateDelta { - memories_add: vec!["saw the event".into()], - ..Default::default() - }, - action_proposals: vec![], - }, - ActorReaction { - actor_id: "bert".into(), - speech: None, - deliberate_silence: false, - private_delta: ActorStateDelta::default(), - action_proposals: vec![WorldActionProposal { - actor_id: "bert".into(), - intent: "invoke secret lore".into(), - intended_effect: "control the room".into(), - priority: 10, - state_references: vec!["knowledge:unearned secret lore".into()], - }], - }, - ]; - assert!( - kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 0, - event_summary: "the player acts".into(), - reactions, - gestalt_reactions: vec![], - }) - .await - .is_err() - ); - let persisted = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(persisted.revision, 0); - assert!(persisted.actors["anna"].memories.is_empty()); - assert!(persisted.transcript.is_empty()); - assert!(persisted.pending_world_proposals.is_empty()); - } - - #[tokio::test] - async fn reaction_interpreter_cannot_write_actor_memory() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.transcript.push(NarrativeTurn { - revision: 0, - at: seed.world_time, - speaker: "player".into(), - text: "Tell me which seal I repaired.".into(), - persona_response_actor_ids: BTreeSet::new(), - }); - seed.actors.insert( - "anna".into(), - ActorState { - id: "anna".into(), - name: "Anna".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - seed.actors.insert( - "taren".into(), - ActorState { - id: "taren".into(), - name: "Taren".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - - let result = kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 0, - event_summary: "player says: Tell me which seal I repaired.".into(), - reactions: vec![ActorReaction { - actor_id: "anna".into(), - speech: None, - deliberate_silence: false, - private_delta: ActorStateDelta { - memories_add: vec!["I repaired the seal.".into()], - ..Default::default() - }, - action_proposals: vec![], - }], - gestalt_reactions: vec![], - }) - .await; - assert!( - matches!(result, Err(KernelError::Invalid(message)) if message.contains("cannot write actor memory")) - ); - let identity_result = kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 0, - event_summary: "player says: Tell me which seal I repaired.".into(), - reactions: vec![ActorReaction { - actor_id: "anna".into(), - speech: Some("My name is Anna.".into()), - deliberate_silence: false, - private_delta: ActorStateDelta { - identity_adoption: Some("Taren".into()), - ..Default::default() - }, - action_proposals: vec![], - }], - gestalt_reactions: vec![], - }) - .await; - assert!( - matches!(identity_result, Err(KernelError::Invalid(message)) if message.contains("exact spoken handle")) - ); - let conflicting_identity_result = kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 0, - event_summary: "player says: Tell me which seal I repaired.".into(), - reactions: vec![ActorReaction { - actor_id: "anna".into(), - speech: Some("My name is Taren.".into()), - deliberate_silence: false, - private_delta: ActorStateDelta { - identity_adoption: Some("Taren".into()), - ..Default::default() - }, - action_proposals: vec![], - }], - gestalt_reactions: vec![], - }) - .await; - assert!( - matches!(conflicting_identity_result, Err(KernelError::Invalid(message)) if message.contains("established local or population identity")) - ); - let persisted = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(persisted.revision, 0); - assert!(persisted.actors["anna"].memories.is_empty()); - } - - #[tokio::test] - async fn reaction_memory_preserves_exact_committed_speaker_attribution() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.transcript.push(NarrativeTurn { - revision: 0, - at: seed.world_time, - speaker: "player".into(), - text: "Tell me which seal I repaired.".into(), - persona_response_actor_ids: BTreeSet::new(), - }); - seed.actors.insert( - "anna".into(), - ActorState { - id: "anna".into(), - name: "Anna".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - - kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 0, - event_summary: "player says: Tell me which seal I repaired.".into(), - reactions: vec![ActorReaction { - actor_id: "anna".into(), - speech: Some("I did not witness it.".into()), - deliberate_silence: false, - private_delta: ActorStateDelta::default(), - action_proposals: vec![], - }], - gestalt_reactions: vec![], - }) - .await - .unwrap(); - let persisted = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!( - persisted.actors["anna"].memories, - vec!["Witnessed: player says: Tell me which seal I repaired."] - ); - assert!(!persisted.actors["anna"].memories[0].contains("Anna repaired")); - } - - #[tokio::test] - async fn initiative_grants_one_npc_opportunity_without_faking_player_activity() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.transcript.push(NarrativeTurn { - revision: 0, - at: seed.world_time, - speaker: "world".into(), - text: "a disturbance".into(), - persona_response_actor_ids: BTreeSet::new(), - }); - seed.last_player_activity = Utc::now() - Duration::hours(2); - for id in ["anna", "bert"] { - seed.actors.insert( - id.into(), - ActorState { - id: id.into(), - name: id.into(), - location_id: "room".into(), - capabilities: BTreeSet::from(["intervene".into()]), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - } - let activity = seed.last_player_activity; - let campaign_id = seed.id; - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let proposal = |actor: &str, priority| WorldActionProposal { - actor_id: actor.into(), - intent: "intervene".into(), - intended_effect: "take control of the immediate situation".into(), - priority, - state_references: vec!["capability:intervene".into(), "location:room".into()], - }; - let anna = proposal("anna", 9); - let bert = proposal("bert", 4); - let wave = kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 0, - event_summary: "a disturbance".into(), - reactions: vec![ - ActorReaction { - actor_id: "anna".into(), - speech: None, - deliberate_silence: false, - private_delta: ActorStateDelta::default(), - action_proposals: vec![anna.clone()], - }, - ActorReaction { - actor_id: "bert".into(), - speech: None, - deliberate_silence: false, - private_delta: ActorStateDelta::default(), - action_proposals: vec![bert.clone()], - }, - ], - gestalt_reactions: vec![], - }) - .await - .unwrap(); - let assessment_for = |actor: &str| ActionIntent { - actor_id: actor.into(), - description: "intervene".into(), - intended_effect: "take control of the immediate situation".into(), - }; - let CommandResult::Assessed { - assessment: bert_assessment, - } = kernel - .command(WorldCommand::Assess { - expected_revision: 1, - intent: assessment_for("bert"), - proposal: None, - }) - .await - .unwrap() - else { - panic!() - }; - assert!( - kernel - .command(WorldCommand::ResolveNpcAction { - expected_revision: 1, - proposal: bert, - assessment: bert_assessment, - }) - .await - .is_err() - ); - let CommandResult::Assessed { assessment } = kernel - .command(WorldCommand::Assess { - expected_revision: 1, - intent: assessment_for("anna"), - proposal: None, - }) - .await - .unwrap() - else { - panic!() - }; - let mut malformed = assessment.clone(); - malformed - .success_effect - .actor_conditions - .insert("invented-actor".into(), ConditionDelta::default()); - malformed.digest = crate::assessor::assessment_digest(&malformed).unwrap(); - assert!( - kernel - .command(WorldCommand::ResolveNpcAction { - expected_revision: 1, - proposal: anna.clone(), - assessment: malformed, - }) - .await - .is_err() - ); - let unchanged = store - .load::("campaign.v1", &campaign_id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(unchanged.revision, 1); - assert_eq!(unchanged.pending_world_proposals.len(), 2); - let resolved = kernel - .command(WorldCommand::ResolveNpcAction { - expected_revision: 1, - proposal: anna, - assessment, - }) - .await - .unwrap(); - let CommandResult::Committed { - campaign: resolved, .. - } = resolved - else { - panic!() - }; - assert!(resolved.pending_world_proposals.is_empty()); - let persisted = store - .load::("campaign.v1", &resolved.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(persisted.last_player_activity, activity); - assert_eq!(persisted.revision, 2); - let CommandResult::Committed { campaign, .. } = wave else { - panic!() - }; - assert_eq!(campaign.pending_world_proposals.len(), 2); - } - - #[tokio::test] - async fn npc_initiative_cannot_rebase_across_a_new_foreground_revision() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - seed.transcript.push(NarrativeTurn { - revision: 0, - at: seed.world_time, - speaker: "world".into(), - text: "a disturbance".into(), - persona_response_actor_ids: BTreeSet::new(), - }); - seed.actors.insert( - "anna".into(), - ActorState { - id: "anna".into(), - name: "Anna".into(), - location_id: "room".into(), - capabilities: BTreeSet::from(["intervene".into()]), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - let campaign_id = seed.id; - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let proposal = WorldActionProposal { - actor_id: "anna".into(), - intent: "intervene".into(), - intended_effect: "take control of the immediate situation".into(), - priority: 9, - state_references: vec!["capability:intervene".into(), "location:room".into()], - }; - kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 0, - event_summary: "a disturbance".into(), - reactions: vec![ActorReaction { - actor_id: "anna".into(), - speech: None, - deliberate_silence: false, - private_delta: ActorStateDelta::default(), - action_proposals: vec![proposal.clone()], - }], - gestalt_reactions: vec![], - }) - .await - .unwrap(); - kernel - .command(WorldCommand::Speak { - expected_revision: 1, - actor_id: "player".into(), - text: "I move on before Anna acts.".into(), - intended_effect: None, - persona_response_actor_ids: BTreeSet::new(), - }) - .await - .unwrap(); - let intent = ActionIntent { - actor_id: "anna".into(), - description: proposal.intent.clone(), - intended_effect: proposal.intended_effect.clone(), - }; - let CommandResult::Assessed { assessment } = kernel - .command(WorldCommand::Assess { - expected_revision: 2, - intent, - proposal: None, - }) - .await - .unwrap() - else { - panic!() - }; - let error = kernel - .command(WorldCommand::ResolveNpcAction { - expected_revision: 2, - proposal, - assessment, - }) - .await - .unwrap_err(); - assert!(error.to_string().contains("current reaction wave")); - - let refreshed = kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: 2, - event_summary: "player says: I move on before Anna acts.".into(), - reactions: vec![ActorReaction { - actor_id: "anna".into(), - speech: None, - deliberate_silence: false, - private_delta: ActorStateDelta::default(), - action_proposals: vec![], - }], - gestalt_reactions: vec![], - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = refreshed else { - panic!() - }; - assert_eq!(campaign.revision, 3); - assert!(campaign.pending_world_proposals.is_empty()); - let persisted = store - .load::("campaign.v1", &campaign_id.to_string()) - .unwrap() - .unwrap() - .1; - assert!(persisted.pending_world_proposals.is_empty()); - } - - #[tokio::test] - async fn roll_commits_only_the_prevalidated_typed_outcome_delta() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = campaign(); - let player_location = seed.actors["player"].location_id.clone(); - seed.facts.insert( - "fact:door-brace-seated".into(), - WorldFact { - id: "fact:door-brace-seated".into(), - statement: "The door brace is seated against the frame.".into(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from([player_location]), - }, - ); - let campaign_id = seed.id; - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let intent = ActionIntent { - actor_id: "player".into(), - description: "brace the door".into(), - intended_effect: "become braced".into(), - }; - let mut invalid = assess(&seed, intent.clone()); - invalid - .success_effect - .actor_moves - .insert("player".into(), "nowhere".into()); - invalid.digest = crate::assessor::assessment_digest(&invalid).unwrap(); - assert!( - kernel - .command(WorldCommand::Assess { - expected_revision: 0, - intent: intent.clone(), - proposal: Some(invalid), - }) - .await - .is_err() - ); - let mut hidden_finding = assess(&seed, intent.clone()); - hidden_finding - .success_effect - .actor_knowledge_additions - .insert( - "player".into(), - BTreeSet::from(["The hidden latch is broken.".into()]), - ); - hidden_finding.success_stake = "The hidden latch is broken.".into(); - hidden_finding.digest = crate::assessor::assessment_digest(&hidden_finding).unwrap(); - assert!( - kernel - .command(WorldCommand::Assess { - expected_revision: 0, - intent: intent.clone(), - proposal: Some(hidden_finding), - }) - .await - .is_err() - ); - let delta = WorldEffectDelta { - actor_conditions: BTreeMap::from([( - "player".into(), - ConditionDelta { - add: BTreeSet::from(["braced".into()]), - remove: BTreeSet::new(), - }, - )]), - actor_knowledge_additions: BTreeMap::from([( - "player".into(), - BTreeSet::from(["The door brace is seated against the frame.".into()]), - )]), - ..Default::default() - }; - let mut valid = assess(&seed, intent.clone()); - valid.success_stake = - "The door brace is seated against the frame. You become braced.".into(); - valid.mixed_stake = valid.success_stake.clone(); - valid.failure_stake = valid.success_stake.clone(); - valid.strong_effect = delta.clone(); - valid.success_effect = delta.clone(); - valid.mixed_effect = delta.clone(); - valid.failure_effect = delta; - valid.digest = crate::assessor::assessment_digest(&valid).unwrap(); - kernel - .command(WorldCommand::Assess { - expected_revision: 0, - intent, - proposal: Some(valid.clone()), - }) - .await - .unwrap(); - kernel - .command(WorldCommand::Attempt { - actor_id: "player".into(), - assessment_digest: valid.digest, - }) - .await - .unwrap(); - let persisted = store - .load::("campaign.v1", &campaign_id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(persisted.revision, 1); - assert!(persisted.actors["player"].conditions.contains("braced")); - assert!( - persisted.actors["player"] - .knowledge - .contains("The door brace is seated against the frame.") - ); - assert!(persisted.facts.values().any(|fact| { - fact.statement == "The door brace is seated against the frame." - && fact.scope == FactScope::BranchLocal - })); - assert_eq!(persisted.facts.len(), 1); - } - - #[test] - fn information_effects_reveal_existing_accessible_facts_only() { - let statement = "The maintenance panel records a seven-minute interruption."; - let mut seed = campaign(); - seed.facts.insert( - "fact:panel-interruption".into(), - WorldFact { - id: "fact:panel-interruption".into(), - statement: statement.into(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["room".into()]), - }, - ); - let effect = WorldEffectDelta { - actor_knowledge_additions: BTreeMap::from([( - "player".into(), - BTreeSet::from([statement.into()]), - )]), - ..Default::default() - }; - assert!( - crate::assessor::validate_effect(&seed, &seed.actors["player"], &effect, statement,) - .is_ok() - ); - - let mut absent = seed.clone(); - absent.facts.clear(); - assert!( - crate::assessor::validate_effect( - &absent, - &absent.actors["player"], - &effect, - statement, - ) - .unwrap_err() - .to_string() - .contains("existing accessible WorldFact") - ); - - let mut wrong_place = seed.clone(); - wrong_place - .facts - .get_mut("fact:panel-interruption") - .unwrap() - .discoverable_at_location_ids = BTreeSet::from(["elsewhere".into()]); - assert!( - crate::assessor::validate_effect( - &wrong_place, - &wrong_place.actors["player"], - &effect, - statement, - ) - .is_err() - ); - - let mut speaker = seed.actors["player"].clone(); - speaker.id = "speaker".into(); - speaker.name = "Speaker".into(); - speaker.knowledge.insert(statement.into()); - seed.actors.insert(speaker.id.clone(), speaker.clone()); - seed.facts - .get_mut("fact:panel-interruption") - .unwrap() - .discoverable_at_location_ids - .clear(); - assert!( - crate::assessor::validate_effect(&seed, &speaker, &effect, statement).is_ok(), - "an actor may communicate an existing fact they know to another present actor" - ); - } - - fn resolution_stage( - cell_id: &str, - campaign: &Campaign, - stage: &str, - marker: char, - ) -> crate::model::ModelStageReceipt { - let hash = test_action_digest(&format!( - "resolution-stage:{}:{}:{}:{}:{}", - campaign.id, campaign.revision, cell_id, stage, marker - )); - crate::model::ModelStageReceipt { - schema: "ghostlight.persona_stage_receipt.v1".into(), - receipt_hash: hash.clone(), - provider: "fixture".into(), - model: "fixture".into(), - stage: stage.into(), - snapshot_binding: format!( - "campaign:{}:revision:{}:resolution:{}:cell:{}", - campaign.id, - campaign.revision, - campaign.resolution_policy.resolution_epoch, - cell_id - ), - request_hash: format!("sha256:{}", "e".repeat(64)), - output_hash: format!("sha256:{}", "f".repeat(64)), - source_receipt_ids: vec![], - latency_ms: 1, - validation_result: "valid".into(), - local_validation_error: None, - input_chars: 7, - output_chars: 7, - provider_attempts: vec![], - } - } - - fn inaction_wave( - campaign: &Campaign, - store: &CampaignStore, - ) -> crate::domain::ResolutionWaveCommit { - let cover = crate::resolution::plan_cover( - campaign, - crate::resolution::default_demand(campaign, "kernel fixture"), - ) - .unwrap(); - let mut hashes = Vec::new(); - for (cell_index, cell) in cover.cells.iter().enumerate() { - for (stage_index, stage) in ["cell_projector", "cell_persona", "cell_interpreter"] - .into_iter() - .enumerate() - { - let marker = - char::from_u32(u32::from(b'a') + (cell_index * 3 + stage_index) as u32) - .unwrap(); - let receipt = resolution_stage(&cell.id, campaign, stage, marker); - store - .insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - &receipt, - ) - .unwrap(); - hashes.push(receipt.storage_key().to_owned()); - } - } - crate::domain::ResolutionWaveCommit { - schema: "ghostlight.resolution_wave_commit.v1".into(), - world_revision: campaign.revision, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - plan_receipt: crate::resolution::plan_receipt(campaign, &cover), - appraisals: cover - .cells - .iter() - .map(|cell| { - let decision_owner = cell - .detail_focus_subject_id - .as_ref() - .or_else(|| cell.subject_ids.iter().next()) - .expect("a simulation cell has at least one subject") - .clone(); - CellAppraisal { - schema: "ghostlight.cell_appraisal.v1".into(), - cell_id: cell.id.clone(), - world_revision: campaign.revision, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - considered_subject_ids: BTreeSet::from([decision_owner.clone()]), - actions: vec![], - inactions: vec![crate::domain::CellInaction { - subject_id: decision_owner, - reason: "No justified move.".into(), - }], - } - }) - .collect(), - cover, - activity_outcomes: vec![], - strategic_individuations: vec![], - model_receipt_hashes: hashes, - } - } - - #[test] - fn direct_strategic_plan_cannot_write_external_subject_state() { - let external = BTreeSet::from(["external-hold".to_string()]); - let mut plan = StrategicTickPlan::default(); - plan.institution_actions.push(StrategicInstitutionAction { - institution_id: "external-hold".into(), - posture: "overwritten".into(), - location_ids: Vec::new(), - public_channels: Vec::new(), - }); - assert!(strategic_plan_writes_external_subject(&plan, &external)); - - plan.institution_actions.clear(); - plan.activity_outcomes.push(StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: format!("sha256:{}", "a".repeat(64)), - source_subject_id: "foreign-court".into(), - band: StrategicOutcomeBand::Success, - summary: "Attempted cross-boundary resource mutation.".into(), - supporting_state_references: Vec::new(), - effect: StrategicOutcomeEffect::ResourceConsumed { - owner_subject_id: "external-hold".into(), - resource: "ore".into(), - }, - }); - assert!(strategic_plan_writes_external_subject(&plan, &external)); - - plan.activity_outcomes.clear(); - plan.selected_actions.push(CellActionProposal { - subject_id: "foreign-court".into(), - intent: "Contact the hold.".into(), - intended_effect: "Request negotiation.".into(), - priority: 1, - state_references: Vec::new(), - public_channels: Vec::new(), - effects: vec![StrategicCellEffect::ActorActivity { - actor_id: "foreign-court".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["external-hold".into()], - location_ids: Vec::new(), - }], - }); - assert!(strategic_plan_writes_external_subject(&plan, &external)); - } - - #[test] - fn strategic_wave_derives_attributed_external_proposal() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let campaign = crate::resolution::tests::campaign(2, 2); - let mut wave = inaction_wave(&campaign, &store); - let appraisal = wave.appraisals.first_mut().unwrap(); - let source_subject_id = appraisal.inactions[0].subject_id.clone(); - appraisal.inactions.clear(); - appraisal.actions.push(CellActionProposal { - subject_id: source_subject_id.clone(), - intent: "Open talks with the external hold.".into(), - intended_effect: "Establish a negotiating channel.".into(), - priority: 1, - state_references: Vec::new(), - public_channels: vec!["diplomatic".into()], - effects: vec![StrategicCellEffect::ActorActivity { - actor_id: source_subject_id.clone(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["external-hold".into()], - location_ids: Vec::new(), - }], - }); - let authorities = vec![crate::consumer::ExternalSubjectAuthority { - schema: "ghostlight.external_subject_authority.v1".into(), - id: "authority:external-hold".into(), - campaign_id: campaign.id, - subject_id: "external-hold".into(), - subject_kind: AgencySubjectKind::Institution, - owner_id: "fixture-consumer".into(), - authority_key_sha256: crate::consumer::authority_key_digest("secret"), - last_source_revision: None, - last_payload_digest: None, - }]; - let proposals = - external_proposals_for_wave(campaign.id, 1, Utc::now(), &wave, &authorities).unwrap(); - assert_eq!(proposals.len(), 1); - assert_eq!(proposals[0].source_subject_id, source_subject_id); - assert_eq!(proposals[0].external_subject_id, "external-hold"); - assert_eq!(proposals[0].authority_id, "authority:external-hold"); - } - - #[tokio::test] - async fn resolution_budget_commits_without_advancing_fictional_state() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = crate::resolution::tests::campaign(6, 8); - let world_time = seed.world_time; - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let result = kernel - .command(WorldCommand::SetResolutionBudget { - expected_revision: 0, - expected_resolution_epoch: 0, - active_cell_budget: 3, - }) - .await - .unwrap(); - let CommandResult::ResolutionUpdated { campaign, receipt } = result else { - panic!("resolution command used the world commit path") - }; - assert_eq!(campaign.revision, 0); - assert_eq!(campaign.world_time, world_time); - assert_eq!(campaign.resolution_policy.active_cell_budget, 3); - assert_eq!(campaign.resolution_policy.resolution_epoch, 1); - assert_eq!(receipt.previous_resolution_epoch, 0); - let unchanged = kernel - .command(WorldCommand::SetResolutionBudget { - expected_revision: 0, - expected_resolution_epoch: 1, - active_cell_budget: 3, - }) - .await - .unwrap_err(); - assert!(unchanged.to_string().contains("does not change")); - assert!( - kernel - .command(WorldCommand::SetResolutionBudget { - expected_revision: 0, - expected_resolution_epoch: 0, - active_cell_budget: 4, - }) - .await - .is_err() - ); - assert_eq!( - store.keys("resolution_control_receipt.v1").unwrap().len(), - 1 - ); - } - - #[tokio::test] - async fn provider_parallelism_changes_without_repartitioning_the_world() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store); - let mut seed = crate::resolution::tests::campaign(6, 3); - let cover = crate::resolution::plan_cover( - &seed, - crate::resolution::default_demand(&seed, "existing cover"), - ) - .unwrap(); - seed.resolution_cover = Some(cover.clone()); - let world_time = seed.world_time; - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let result = kernel - .command(WorldCommand::SetProviderParallelism { - expected_revision: 0, - expected_provider_configuration_epoch: 0, - provider_parallelism: 4, - }) - .await - .unwrap(); - let CommandResult::ResolutionUpdated { campaign, receipt } = result else { - panic!("operator control used the fictional world commit path") - }; - assert_eq!(campaign.revision, 0); - assert_eq!(campaign.world_time, world_time); - assert_eq!(campaign.resolution_policy.resolution_epoch, 0); - assert_eq!(campaign.resolution_policy.provider_configuration_epoch, 1); - assert_eq!(campaign.resolution_policy.provider_parallelism, 4); - assert_eq!(campaign.resolution_cover, Some(cover)); - assert_eq!(receipt.operation, "set_provider_parallelism"); - let unchanged = kernel - .command(WorldCommand::SetProviderParallelism { - expected_revision: 0, - expected_provider_configuration_epoch: 1, - provider_parallelism: 4, - }) - .await - .unwrap_err(); - assert!(unchanged.to_string().contains("does not change")); - assert!( - kernel - .command(WorldCommand::SetProviderParallelism { - expected_revision: 0, - expected_provider_configuration_epoch: 0, - provider_parallelism: 2, - }) - .await - .is_err() - ); - } - - #[tokio::test] - async fn strategic_resolution_wave_commits_cover_and_all_appraisals_atomically() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = crate::resolution::tests::campaign(6, 2); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let persisted = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - let wave = inaction_wave(&persisted, &store); - let cell_count = wave.cover.cells.len(); - let result = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: Some(format!("sha256:{}", "9".repeat(64))), - resolution_wave: Some(wave), - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!() - }; - assert_eq!(campaign.revision, 1); - assert_eq!(campaign.strategic_tick_count, 1); - assert!(campaign.resolution_cover.is_some()); - assert_eq!(store.keys("cell_appraisal.v1").unwrap().len(), cell_count); - assert_eq!(store.keys("resolution_plan_receipt.v1").unwrap().len(), 1); - assert_eq!(store.keys("strategic_tick.v1").unwrap().len(), 1); - } - - #[tokio::test] - async fn kernel_rejects_a_forged_nemesis_agenda_and_commits_the_exact_receipted_one() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = crate::resolution::tests::campaign(1, 1); - let responder = "faction-0000"; - seed.agency_profiles - .get_mut(responder) - .unwrap() - .information_channels - .insert("public-court".into()); - seed.events.push(crate::domain::Event { - id: "court-accusation".into(), - at: seed.world_time, - kind: "public_accusation".into(), - summary: "The court accuses Faction 0 of concealing the winter tally.".into(), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec![], - public_channels: vec!["public-court".into()], - }); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let persisted = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - let mut wave = inaction_wave(&persisted, &store); - wave.cover.causal_follow_through = vec![crate::domain::CausalFollowThroughAssignment { - anchor_reference: "event:court-accusation".into(), - responder_subject_id: responder.into(), - }]; - - let error = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: Some(format!("sha256:{}", "9".repeat(64))), - resolution_wave: Some(wave.clone()), - }) - .await - .unwrap_err(); - assert!(error.to_string().contains("exact Nemesis receipt")); - let unchanged = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(unchanged.revision, 0); - assert!(unchanged.nemesis_attention_history.is_empty()); - - let mut receipt = resolution_stage( - &wave.cover.cells[0].id, - &persisted, - crate::follow_through::NEMESIS_STAGE, - 'z', - ); - receipt.snapshot_binding = - crate::follow_through::nemesis_admission_binding(&persisted, &wave.cover).unwrap(); - store - .insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - &receipt, - ) - .unwrap(); - wave.model_receipt_hashes - .push(receipt.storage_key().to_owned()); - let result = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: Some(format!("sha256:{}", "9".repeat(64))), - resolution_wave: Some(wave), - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!() - }; - assert_eq!(campaign.nemesis_attention_history.len(), 1); - assert_eq!( - campaign.nemesis_attention_history[0].anchor_reference, - "event:court-accusation" - ); - assert_eq!( - campaign.nemesis_attention_history[0].responder_subject_id, - responder - ); - assert_eq!( - campaign.nemesis_attention_history[0].served_world_revision, - 1 - ); - } - - #[tokio::test] - async fn invalid_effect_verifier_receipt_cannot_authorize_an_actionful_cell() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = crate::resolution::tests::campaign(3, 1); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let persisted = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - let mut wave = inaction_wave(&persisted, &store); - let subject_id = wave.cover.cells[0] - .subject_ids - .iter() - .next() - .unwrap() - .clone(); - wave.appraisals[0].actions = vec![CellActionProposal { - subject_id: subject_id.clone(), - intent: "adopt a new position".into(), - intended_effect: "publish a different commitment".into(), - priority: 1, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::Institution { - institution_id: subject_id, - posture: "publishing a bounded new commitment".into(), - location_ids: vec![], - }], - }]; - wave.appraisals[0].inactions.clear(); - let mut rejected_verifier = resolution_stage( - &wave.cover.cells[0].id, - &persisted, - "cell_effect_verifier", - 'd', - ); - rejected_verifier.validation_result = "semantic_invalid".into(); - rejected_verifier.local_validation_error = - Some("typed effect reverses the decision".into()); - store - .insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - rejected_verifier.storage_key(), - &rejected_verifier, - ) - .unwrap(); - wave.model_receipt_hashes - .push(rejected_verifier.storage_key().to_owned()); - - let error = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: Some(format!("sha256:{}", "9".repeat(64))), - resolution_wave: Some(wave), - }) - .await - .unwrap_err(); - assert!( - error - .to_string() - .contains("lacks action-bound cell_effect_verifier"), - "unexpected kernel rejection: {error}" - ); - let stored = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(stored.revision, 0); - assert_eq!(stored.world_time, seed.world_time); - } - - #[test] - fn activity_outcome_receipts_bind_each_selected_action_independently() { - let value = hierarchical_refugee_campaign(); - let first = format!("sha256:{}", "1".repeat(64)); - let second = format!("sha256:{}", "2".repeat(64)); - let bindings = expected_activity_outcome_bindings(&value, &[first.clone(), second.clone()]); - - assert_eq!(bindings.len(), 2); - assert_eq!( - bindings[0], - crate::outcome::activity_outcome_binding( - value.id, - value.revision, - value.resolution_policy.resolution_epoch, - std::slice::from_ref(&first), - ) - ); - assert_eq!( - bindings[1], - crate::outcome::activity_outcome_binding( - value.id, - value.revision, - value.resolution_policy.resolution_epoch, - std::slice::from_ref(&second), - ) - ); - assert!( - !bindings.contains(&crate::outcome::activity_outcome_binding( - value.id, - value.revision, - value.resolution_policy.resolution_epoch, - &[first, second], - )) - ); - } - - #[tokio::test] - async fn activity_outcome_receipt_must_bind_the_exact_selected_action() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = hierarchical_refugee_campaign(); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let persisted = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - let mut wave = inaction_wave(&persisted, &store); - let refugees_cell_id = wave - .cover - .cells - .iter() - .find(|cell| cell.subject_ids.contains("refugees-east")) - .map(|cell| cell.id.clone()) - .unwrap(); - let appraisal = wave - .appraisals - .iter_mut() - .find(|appraisal| appraisal.cell_id == refugees_cell_id) - .unwrap(); - appraisal.considered_subject_ids = BTreeSet::from(["refugees-east".into()]); - let proposal = CellActionProposal { - subject_id: "refugees-east".into(), - intent: "prepare storm lashings".into(), - intended_effect: "finish one bounded set of camp lashings".into(), - priority: 60, - state_references: vec![ - "subject:refugees-east".into(), - "capability:survive transit".into(), - "location:camp".into(), - ], - public_channels: vec![], - effects: vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees-east".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["camp".into()], - }], - }; - let action_digest = crate::resolution::cell_action_digest(&proposal).unwrap(); - appraisal.actions = vec![proposal]; - appraisal.inactions.clear(); - let appraisal_cell_id = appraisal.cell_id.clone(); - let appraisal_actions = appraisal.actions.clone(); - wave.activity_outcomes = vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: action_digest.clone(), - source_subject_id: "refugees-east".into(), - band: StrategicOutcomeBand::Success, - summary: "The camp finishes one set of storm lashings.".into(), - supporting_state_references: vec!["capability:survive transit".into()], - effect: StrategicOutcomeEffect::ResourceCreated { - owner_subject_id: "refugees-east".into(), - resource: "storm lashings".into(), - }, - }]; - - let base_binding = format!( - "campaign:{}:revision:{}:resolution:{}:cell:{}", - persisted.id, - persisted.revision, - persisted.resolution_policy.resolution_epoch, - appraisal_cell_id - ); - let mut verifier = - resolution_stage(&appraisal_cell_id, &persisted, "cell_effect_verifier", '7'); - verifier.snapshot_binding = - crate::persona::cell_effect_verification_binding(&base_binding, &appraisal_actions) - .unwrap(); - let wrong_outcome = resolution_stage( - &appraisal_cell_id, - &persisted, - "strategic_outcome_resolver", - '8', - ); - for receipt in [verifier, wrong_outcome] { - store - .insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - &receipt, - ) - .unwrap(); - wave.model_receipt_hashes - .push(receipt.storage_key().to_owned()); - } - let outcome_binding = crate::outcome::activity_outcome_binding( - persisted.id, - persisted.revision, - persisted.resolution_policy.resolution_epoch, - &[action_digest], - ); - let mut rejected_luna = resolution_stage( - &appraisal_cell_id, - &persisted, - "strategic_outcome_resolver", - '9', - ); - rejected_luna.snapshot_binding = outcome_binding.clone(); - rejected_luna.model = crate::model::MODEL_FAST.into(); - rejected_luna.validation_result = "semantic_invalid".into(); - rejected_luna.local_validation_error = Some("fixture semantic mismatch".into()); - let mut admitted_terra = resolution_stage( - &appraisal_cell_id, - &persisted, - "strategic_outcome_resolver", - 'a', - ); - admitted_terra.snapshot_binding = outcome_binding; - admitted_terra.model = crate::model::MODEL_BALANCED.into(); - admitted_terra.source_receipt_ids = vec![rejected_luna.storage_key().to_owned()]; - let mut outcome_verifier = resolution_stage( - &appraisal_cell_id, - &persisted, - "strategic_outcome_verifier", - 'b', - ); - outcome_verifier.snapshot_binding = crate::outcome::activity_outcome_verification_binding( - persisted.id, - persisted.revision, - persisted.resolution_policy.resolution_epoch, - &wave.activity_outcomes, - ) - .unwrap(); - outcome_verifier.source_receipt_ids = vec![admitted_terra.storage_key().to_owned()]; - for receipt in [&rejected_luna, &admitted_terra, &outcome_verifier] { - store - .insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - receipt, - ) - .unwrap(); - } - let mut missing_verifier_wave = wave.clone(); - missing_verifier_wave.model_receipt_hashes.extend([ - rejected_luna.storage_key().to_owned(), - admitted_terra.storage_key().to_owned(), - ]); - let mut correct_wave = missing_verifier_wave.clone(); - correct_wave - .model_receipt_hashes - .push(outcome_verifier.storage_key().to_owned()); - - let error = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: Some(format!("sha256:{}", "9".repeat(64))), - resolution_wave: Some(wave), - }) - .await - .unwrap_err(); - assert!( - error - .to_string() - .contains("lacks an activity-bound strategic outcome receipt"), - "unexpected kernel rejection: {error}" - ); - let stored = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(stored.revision, 0); - assert_eq!(stored.world_time, seed.world_time); - assert!( - !stored.gestalts["refugees-east"] - .resources - .contains("storm lashings") - ); - - let error = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: Some(format!("sha256:{}", "a".repeat(64))), - resolution_wave: Some(missing_verifier_wave), - }) - .await - .unwrap_err(); - assert!( - error - .to_string() - .contains("lacks an outcome-bound strategic verifier receipt"), - "unexpected kernel rejection: {error}" - ); - - let result = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: Some(format!("sha256:{}", "a".repeat(64))), - resolution_wave: Some(correct_wave), - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!() - }; - assert_eq!(campaign.revision, 1); - assert!( - campaign.gestalts["refugees-east"] - .resources - .contains("storm lashings") - ); - assert_eq!( - store.keys("strategic_activity_outcome.v1").unwrap().len(), - 1 - ); - } - - #[tokio::test] - async fn strategic_wave_atomically_individuates_and_materializes_an_action_bound_person() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let mut seed = hierarchical_refugee_campaign(); - seed.agency_profiles - .get_mut("refugees-east") - .unwrap() - .information_channels - .insert("storm-camp broadsheet".into()); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let persisted = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - let mut wave = inaction_wave(&persisted, &store); - let cell_id = wave - .cover - .cells - .iter() - .find(|cell| cell.subject_ids.contains("refugees-east")) - .unwrap() - .id - .clone(); - let appraisal = wave - .appraisals - .iter_mut() - .find(|appraisal| appraisal.cell_id == cell_id) - .unwrap(); - appraisal.considered_subject_ids = BTreeSet::from(["refugees-east".into()]); - let action = CellActionProposal { - subject_id: "refugees-east".into(), - intent: "appoint a named storm delegation broker".into(), - intended_effect: "make one accuser answer for the camp negotiation".into(), - priority: 80, - state_references: vec!["subject:refugees-east".into(), "location:camp".into()], - public_channels: vec!["storm-camp broadsheet".into()], - effects: vec![StrategicCellEffect::Gestalt { - gestalt_id: "refugees-east".into(), - pressure_additions: vec![ - "Veska Rill says the east quartermasters sold the lower road twice".into(), - ], - pressure_resolutions: vec![], - }], - }; - let action_digest = crate::resolution::cell_action_digest(&action).unwrap(); - appraisal.actions = vec![action.clone()]; - appraisal.inactions.clear(); - wave.strategic_individuations = vec![StrategicGestaltIndividuation { - schema: "ghostlight.strategic_gestalt_individuation.v1".into(), - action_digest: action_digest.clone(), - rationale: - "She accused the east quartermasters of selling the broken lower road twice.".into(), - individuation: GestaltIndividuation { - gestalt_id: "refugees-east".into(), - expected_gestalt_version: 0, - location_id: "camp".into(), - member: GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "veska-rill".into(), - gestalt_id: "refugees-east".into(), - version: 0, - name: "Veska Rill".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::from(["answer to the camp wards".into()]), - relationships: BTreeMap::new(), - goals: vec!["secure the storm route".into()], - memories: vec!["the deep excavation broke the lower road".into()], - last_location_id: Some("camp".into()), - materialized_actor_id: None, - last_relevant_revision: persisted.revision, - relevance_lease_until_revision: persisted.revision + 4, - }, - }, - }]; - let base_binding = format!( - "campaign:{}:revision:{}:resolution:{}:cell:{}", - persisted.id, persisted.revision, persisted.resolution_policy.resolution_epoch, cell_id - ); - let mut verifier = resolution_stage(&cell_id, &persisted, "cell_effect_verifier", '7'); - verifier.snapshot_binding = crate::persona::cell_effect_verification_binding( - &base_binding, - std::slice::from_ref(&action), - ) - .unwrap(); - let mut selector = resolution_stage( - &cell_id, - &persisted, - "strategic_individuation_selector", - '8', - ); - selector.rebind_snapshot(crate::scheduler::strategic_individuation_binding( - &persisted, - std::slice::from_ref(&action_digest), - Some( - &crate::scheduler::strategic_individuation_proposal_digest( - &wave.strategic_individuations[0], - ) - .unwrap(), - ), - )); - for receipt in [verifier, selector] { - store - .insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - &receipt, - ) - .unwrap(); - wave.model_receipt_hashes - .push(receipt.storage_key().to_owned()); - } - let mut substituted = wave.clone(); - substituted.strategic_individuations[0] - .individuation - .member - .name = "Substituted Caller Payload".into(); - let error = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: persisted.revision, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: Some(format!("sha256:{}", "c".repeat(64))), - resolution_wave: Some(substituted), - }) - .await - .unwrap_err(); - assert!( - error.to_string().contains("payload-bound selector receipt"), - "{error}" - ); - let unchanged = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(unchanged.revision, persisted.revision); - assert!(!unchanged.gestalt_members.contains_key("veska-rill")); - let result = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: persisted.revision, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: Some(format!("sha256:{}", "b".repeat(64))), - resolution_wave: Some(wave), - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, .. } = result else { - panic!() - }; - let member = &campaign.gestalt_members["veska-rill"]; - assert_eq!( - member.materialized_actor_id.as_deref(), - Some("member:veska-rill") - ); - assert_eq!(campaign.actors["member:veska-rill"].name, "Veska Rill"); - assert!(campaign.agency_profiles["member:veska-rill"].simulation_eligible); - assert!( - campaign - .events - .iter() - .any(|event| event.kind == "gestalt_individuation") - ); - let public_individuation = campaign - .events - .iter() - .find(|event| { - event.kind == "gestalt_individuation" - && event - .public_channels - .iter() - .any(|channel| channel == "storm-camp broadsheet") - }) - .unwrap(); - let public_issue = campaign - .news - .iter() - .find(|issue| issue.event_ids == [public_individuation.id.clone()]) - .unwrap(); - assert_eq!( - public_individuation.summary, - "Veska Rill steps forward within Eastern transit refugees to secure the storm route." - ); - assert!(!public_individuation.summary.contains("selected action")); - assert_eq!( - public_issue.headline, - crate::domain::committed_news_headline(&public_individuation.summary) - ); - assert!(public_issue.headline.contains("Veska Rill")); - let proposals = store - .load_all::("strategic_gestalt_individuation.v1") - .unwrap(); - assert_eq!(proposals.len(), 1); - assert_eq!(proposals[0].action_digest, action_digest); - - let mut second_wave = inaction_wave(&campaign, &store); - let second_cell_id = second_wave - .cover - .cells - .iter() - .find(|cell| cell.subject_ids.contains("member:veska-rill")) - .unwrap() - .id - .clone(); - let second_appraisal = second_wave - .appraisals - .iter_mut() - .find(|appraisal| appraisal.cell_id == second_cell_id) - .unwrap(); - second_appraisal.considered_subject_ids = BTreeSet::from(["member:veska-rill".into()]); - let second_action = CellActionProposal { - subject_id: "member:veska-rill".into(), - intent: "cross the bay to confront the quartermasters".into(), - intended_effect: "arrive at the south docks without resolving the accusation".into(), - priority: 91, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::ActorMove { - actor_id: "member:veska-rill".into(), - destination_id: "docks".into(), - }], - }; - second_appraisal.actions = vec![second_action.clone()]; - second_appraisal.inactions.clear(); - let second_base_binding = format!( - "campaign:{}:revision:{}:resolution:{}:cell:{}", - campaign.id, - campaign.revision, - campaign.resolution_policy.resolution_epoch, - second_cell_id - ); - let mut second_verifier = - resolution_stage(&second_cell_id, &campaign, "cell_effect_verifier", 'v'); - second_verifier.snapshot_binding = crate::persona::cell_effect_verification_binding( - &second_base_binding, - std::slice::from_ref(&second_action), - ) - .unwrap(); - store - .insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - second_verifier.storage_key(), - &second_verifier, - ) - .unwrap(); - second_wave - .model_receipt_hashes - .push(second_verifier.storage_key().to_owned()); - let result = kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: campaign.revision, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: Some(test_action_digest("second-veska-wave")), - resolution_wave: Some(second_wave), - }) - .await - .unwrap(); - let CommandResult::Committed { - campaign: campaign_after_second_wave, - .. - } = result - else { - panic!() - }; - assert_eq!( - campaign_after_second_wave.actors["member:veska-rill"].location_id, - "docks" - ); - assert!(campaign_after_second_wave.events.iter().any(|event| { - event.kind == "actor_movement" && event.actor_ids.contains(&"member:veska-rill".into()) - })); - } - - #[tokio::test] - async fn stale_resolution_wave_leaves_time_clocks_and_campaign_unmutated() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let kernel = WorldKernel::start(store.clone()); - let seed = crate::resolution::tests::campaign(4, 2); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - let persisted = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - let wave = inaction_wave(&persisted, &store); - kernel - .command(WorldCommand::SetResolutionBudget { - expected_revision: 0, - expected_resolution_epoch: 0, - active_cell_budget: 1, - }) - .await - .unwrap(); - let before = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - assert!( - kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: 0, - source: TickSource::Scheduler, - plan: None, - model_receipt_hash: Some(format!("sha256:{}", "8".repeat(64))), - resolution_wave: Some(wave), - }) - .await - .is_err() - ); - let after = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(after, before); - assert!(store.keys("strategic_tick.v1").unwrap().is_empty()); - } - - fn two_player_membership(campaign: &mut Campaign) -> CampaignMembership { - let mut guest = campaign.actors["player"].clone(); - guest.id = "guest".into(); - guest.name = "Guest".into(); - campaign.actors.insert(guest.id.clone(), guest); - crate::resolution::ensure_agency_profiles(campaign); - campaign - .agency_profiles - .get_mut("player") - .unwrap() - .simulation_eligible = false; - campaign - .agency_profiles - .get_mut("guest") - .unwrap() - .simulation_eligible = false; - CampaignMembership { - schema: "ghostlight.campaign_membership.v1".into(), - campaign_id: campaign.id, - governance_epoch: 0, - host_member_id: "member:host".into(), - members: BTreeMap::from([ - ( - "member:host".into(), - crate::session_zero::CampaignMember { - member_id: "member:host".into(), - account_hash: "account:host".into(), - display_name: "Host".into(), - actor_id: "player".into(), - is_host: true, - active: true, - cell_allowance: 8, - }, - ), - ( - "member:guest".into(), - crate::session_zero::CampaignMember { - member_id: "member:guest".into(), - account_hash: "account:guest".into(), - display_name: "Guest".into(), - actor_id: "guest".into(), - is_host: false, - active: true, - cell_allowance: 8, - }, - ), - ]), - extraordinary_permissions: BTreeMap::new(), - } - } - - #[tokio::test] - async fn group_travel_retries_uncommitted_unanimous_approval_and_moves_every_member_once() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let mut seed = campaign(); - seed.locations.insert( - "harbor".into(), - Location { - id: "harbor".into(), - name: "Harbor".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec!["stone quay".into()], - }, - ); - seed.locations.get_mut("room").unwrap().routes.insert( - "harbor".into(), - Route { - destination_id: "harbor".into(), - distance: "nearby".into(), - travel_minutes: 20, - }, - ); - seed.locations.insert( - "yard".into(), - Location { - id: "yard".into(), - name: "Yard".into(), - container_id: None, - routes: BTreeMap::from([( - "harbor".into(), - Route { - destination_id: "harbor".into(), - distance: "farther away".into(), - travel_minutes: 45, - }, - )]), - persistent_features: vec!["freight apron".into()], - }, - ); - let membership = two_player_membership(&mut seed); - let campaign_id = seed.id; - let start_time = seed.world_time; - let kernel = WorldKernel::start(store.clone()); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed, - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - store - .insert( - "campaign_membership.v1", - "ghostlight.campaign_membership.v1", - &campaign_id.to_string(), - &membership, - ) - .unwrap(); - let pending = kernel - .command(WorldCommand::ProposeGroupTravel { - expected_revision: 0, - member_id: "member:host".into(), - destination_location_id: "harbor".into(), - }) - .await - .unwrap(); - let CommandResult::TravelGovernancePending { proposal, campaign } = pending else { - panic!("first approval committed a two-member proposal") - }; - assert_eq!(campaign.revision, 0); - assert_eq!(campaign.actors["player"].location_id, "room"); - let proposal_id = proposal.id; - let (proposal_row, mut persisted_proposal) = store - .load::("group_travel_proposal.v1", &proposal_id) - .unwrap() - .unwrap(); - persisted_proposal.approvals.insert("member:guest".into()); - store - .replace( - &proposal_row, - "ghostlight.group_travel_proposal.v1", - &persisted_proposal, - ) - .unwrap(); - let committed = kernel - .command(WorldCommand::ApproveGroupTravel { - expected_revision: 0, - proposal_id: proposal_id.clone(), - member_id: "member:host".into(), - }) - .await - .unwrap(); - let CommandResult::Committed { campaign, receipt } = committed else { - panic!("unanimous travel did not commit") - }; - assert_eq!(receipt.command_kind, "unanimous_group_travel"); - assert_eq!(campaign.revision, 1); - assert_eq!(campaign.world_time, start_time + Duration::minutes(20)); - assert_eq!(campaign.actors["player"].location_id, "harbor"); - assert_eq!(campaign.actors["guest"].location_id, "harbor"); - let travel_turn = campaign.transcript.last().unwrap(); - assert_eq!(travel_turn.speaker, "world"); - assert!(travel_turn.text.contains("Room")); - assert!(travel_turn.text.contains("Harbor")); - assert!(travel_turn.text.contains("20 minutes pass")); - assert_eq!( - campaign.agency_profiles["player"].location_ids, - BTreeSet::from(["harbor".into()]) - ); - assert_eq!( - campaign.agency_profiles["guest"].location_ids, - BTreeSet::from(["harbor".into()]) - ); - assert_eq!( - store.keys("mutation_authority_envelope.v1").unwrap().len(), - 1 - ); - assert_eq!(store.keys("world_mutation_batch.v1").unwrap().len(), 1); - assert_eq!(store.keys("world_mutation_receipt.v1").unwrap().len(), 1); - let mut reload_projection = campaign.clone(); - crate::resolution::ensure_agency_profiles(&mut reload_projection); - assert_eq!(reload_projection, campaign); - assert!( - kernel - .command(WorldCommand::ApproveGroupTravel { - expected_revision: 0, - proposal_id, - member_id: "member:guest".into(), - }) - .await - .is_err() - ); - assert_eq!( - store - .load::("campaign.v1", &campaign_id.to_string()) - .unwrap() - .unwrap() - .1 - .revision, - 1 - ); - } - - #[tokio::test] - async fn kernel_rejects_player_effects_against_another_controlled_actor() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let mut seed = campaign(); - let membership = two_player_membership(&mut seed); - let kernel = WorldKernel::start(store.clone()); - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed.clone(), - evidence_receipts: vec![], - model_stage_receipts: vec![], - }) - .await - .unwrap(); - store - .insert( - "campaign_membership.v1", - "ghostlight.campaign_membership.v1", - &seed.id.to_string(), - &membership, - ) - .unwrap(); - let intent = ActionIntent { - actor_id: "player".into(), - description: "shove Guest".into(), - intended_effect: "make Guest prone".into(), - }; - let mut assessment = assess(&seed, intent.clone()); - assessment.success_effect.actor_conditions.insert( - "guest".into(), - ConditionDelta { - add: BTreeSet::from(["prone".into()]), - remove: BTreeSet::new(), - }, - ); - assessment.digest = crate::assessor::assessment_digest(&assessment).unwrap(); - let error = kernel - .command(WorldCommand::Assess { - expected_revision: 0, - intent, - proposal: Some(assessment), - }) - .await - .unwrap_err(); - assert!(error.to_string().contains("player-versus-player")); - let stored = store - .load::("campaign.v1", &seed.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(stored.revision, 0); - assert!(!stored.actors["guest"].conditions.contains("prone")); - } -} diff --git a/crates/ghostlight-dungeon/src/legacy_transition.rs b/crates/ghostlight-dungeon/src/legacy_transition.rs deleted file mode 100644 index f8e9f5e..0000000 --- a/crates/ghostlight-dungeon/src/legacy_transition.rs +++ /dev/null @@ -1,4879 +0,0 @@ -//! Temporary aggregate-storage lowering for the world transition migration. -//! -//! `Campaign` remains the persisted aggregate until the component-store -//! migration closes. Legacy effect records may enter here as requirements -//! evidence, but this module lowers them into exact `WorldMutation` permits and -//! runs the canonical component reducer before projecting the accepted values -//! back into the aggregate row. It owns no admission policy of its own. - -use crate::{ - domain::{ - ActorReaction, AgencyProfile, AgencyRelation, Campaign, FactScope, GestaltFissionPreview, - GestaltLineage, GestaltPersonaState, OutcomeBand, StrategicActivityOutcome, - StrategicOutcomeEffect, StrategicTickPlan, WorldEffectDelta, WorldFact, - }, - transition::*, -}; -use anyhow::{Result, anyhow}; -use chrono::{DateTime, Utc}; -use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; - -#[derive(Clone, Debug)] -pub struct LoweredLegacyTransition { - pub authority: MutationAuthorityEnvelope, - pub batch: WorldMutationBatch, -} - -pub fn lower_foreground_effect( - campaign: &Campaign, - acting_actor_id: &str, - effect: &WorldEffectDelta, - outcome: OutcomeBand, - procedure: MutationProcedure, - effect_ceiling: &str, - source_receipt_id: &str, - means_digest: Option, - intended_effect_digest: Option, - expires_at: DateTime, -) -> Result { - if !campaign.actors.contains_key(acting_actor_id) { - return Err(anyhow!("transition actor is unknown")); - } - let mutations = foreground_mutations(campaign, effect, source_receipt_id)?; - lower_exact_mutations( - campaign, - mutations, - procedure, - Some(actor_subject(acting_actor_id)), - MutationOutcomeBinding::Foreground(outcome), - None, - effect_ceiling, - source_receipt_id, - means_digest, - intended_effect_digest, - expires_at, - ) -} - -pub fn lower_time_advance( - campaign: &Campaign, - minutes: u32, - procedure: MutationProcedure, - source_receipt_id: &str, - expires_at: DateTime, -) -> Result { - lower_exact_mutations( - campaign, - vec![WorldMutation::AdvanceWorldTime { - campaign: campaign_subject(campaign), - minutes: i64::from(minutes), - }], - procedure, - None, - MutationOutcomeBinding::Deterministic, - None, - "Advance canonical world time by exactly the admitted duration without puppeting any actor.", - source_receipt_id, - Some(digest_serializable(&("wait", minutes))?), - Some(digest_serializable(&("world_time_minutes", minutes))?), - expires_at, - ) -} - -pub fn lower_group_travel( - campaign: &Campaign, - actor_ids: &BTreeSet, - origin_location_id: &str, - destination_location_id: &str, - travel_minutes: u32, - source_receipt_id: &str, - expires_at: DateTime, -) -> Result { - let route_id = exact_route_id(campaign, origin_location_id, destination_location_id)?; - let route_minutes = campaign - .locations - .get(origin_location_id) - .and_then(|location| { - location - .routes - .values() - .find(|route| route.destination_id == destination_location_id) - }) - .map(|route| route.travel_minutes) - .ok_or_else(|| anyhow!("group travel route vanished"))?; - if route_minutes != travel_minutes { - return Err(anyhow!( - "group travel duration does not match exact topology" - )); - } - let mut mutations = Vec::with_capacity(actor_ids.len() + 1); - for actor_id in actor_ids { - let actor = campaign - .actors - .get(actor_id) - .filter(|actor| actor.location_id == origin_location_id) - .ok_or_else(|| anyhow!("group travel actor is absent from the shared origin"))?; - mutations.push(WorldMutation::Relocate { - subject: actor_subject(&actor.id), - from_place: place_subject(origin_location_id), - to_place: place_subject(destination_location_id), - route_id: route_id.clone(), - }); - } - mutations.push(WorldMutation::AdvanceWorldTime { - campaign: campaign_subject(campaign), - minutes: i64::from(travel_minutes), - }); - lower_exact_mutations( - campaign, - mutations, - MutationProcedure::Governance, - None, - MutationOutcomeBinding::Deterministic, - None, - "Relocate every unanimously bound human actor along one exact route and advance time by that route's duration.", - source_receipt_id, - Some(digest_serializable(&( - actor_ids, - origin_location_id, - destination_location_id, - travel_minutes, - ))?), - Some(digest_serializable(&( - "group_occupancy", - destination_location_id, - ))?), - expires_at, - ) -} - -pub fn lower_fission( - campaign: &Campaign, - preview: &GestaltFissionPreview, - expires_at: DateTime, -) -> Result { - lower_fission_with_validation(campaign, preview, expires_at, false) -} - -pub fn lower_elaborated_fission( - campaign: &Campaign, - preview: &GestaltFissionPreview, - expires_at: DateTime, -) -> Result { - lower_fission_with_validation(campaign, preview, expires_at, true) -} - -fn lower_fission_with_validation( - campaign: &Campaign, - preview: &GestaltFissionPreview, - expires_at: DateTime, - allow_semantic_additions: bool, -) -> Result { - if allow_semantic_additions { - crate::resolution::validate_elaborated_fission(campaign, preview)?; - } else { - crate::resolution::validate_fission(campaign, preview)?; - } - let preview_digest = digest_serializable(preview)?; - let source_receipt_id = format!( - "fission-preview:{}", - preview_digest.trim_start_matches("sha256:") - ); - let parent = population_subject(&preview.parent_gestalt_id); - let mut mutations = Vec::new(); - for child in &preview.children { - let subject = population_subject(&child.id); - mutations.push(WorldMutation::AdmitEntity { - subject: subject.clone(), - initial_components: BTreeSet::from([ - WorldComponentKind::Identity, - WorldComponentKind::Occupancy, - WorldComponentKind::Capability, - WorldComponentKind::Knowledge, - WorldComponentKind::Commitment, - WorldComponentKind::Pressure, - WorldComponentKind::PopulationLineage, - ]), - initial_place: Some(place_subject(&child.home_location_id)), - initial_profile: None, - admission_receipt_id: source_receipt_id.clone(), - }); - mutations.push(WorldMutation::ChangeIdentity { - subject, - operation: IdentityMutationOperation::Adopt, - handle_id: format!("identity:canonical:{}", child.id), - handle_value: Some(child.name.clone()), - audience: Vec::new(), - }); - } - mutations.push(WorldMutation::ChangePopulationLineage { - operation: PopulationLineageOperation::Split, - parent_populations: vec![parent.clone()], - child_populations: preview - .children - .iter() - .map(|child| population_subject(&child.id)) - .collect(), - remainder_population: Some(population_subject(&preview.residual_child_id)), - }); - if allow_semantic_additions { - for child in &preview.children { - let subject = population_subject(&child.id); - for capability in child - .shared_capabilities - .difference(&campaign.gestalts[&preview.parent_gestalt_id].shared_capabilities) - { - mutations.push(WorldMutation::ChangeCapability { - subject: subject.clone(), - operation: CapabilityMutationOperation::Grant, - capability_id: capability.clone(), - description: Some(capability.clone()), - }); - } - for statement in child - .shared_knowledge - .difference(&campaign.gestalts[&preview.parent_gestalt_id].shared_knowledge) - { - let (proposition, needs_admission) = - elaborated_fission_proposition(campaign, statement)?; - if needs_admission { - mutations.push(WorldMutation::AdmitEntity { - subject: proposition.clone(), - initial_components: BTreeSet::from([ - WorldComponentKind::Knowledge, - WorldComponentKind::PropositionContent, - ]), - initial_place: None, - initial_profile: Some(AdmittedEntityProfile::Proposition { - statement: statement.clone(), - scope: FactScope::ProvisionalLocal, - evidence_receipt_ids: BTreeSet::new(), - discoverable_at_places: BTreeSet::new(), - }), - admission_receipt_id: source_receipt_id.clone(), - }); - } - mutations.push(WorldMutation::ChangeKnowledge { - operation: KnowledgeMutationOperation::Acquire, - proposition, - knower: Some(subject.clone()), - speaker: None, - recipients: Vec::new(), - channel: None, - }); - } - for goal in child - .goals - .iter() - .skip(campaign.gestalts[&preview.parent_gestalt_id].goals.len()) - { - mutations.push(WorldMutation::ChangeCommitment { - subject: subject.clone(), - operation: CommitmentMutationOperation::Create, - kind: CommitmentKind::Goal, - commitment_id: format!("goal:elaboration:{}", short_digest(goal)), - counterparty: None, - description: Some(goal.clone()), - }); - } - for pressure in child.pressures.iter().skip( - campaign.gestalts[&preview.parent_gestalt_id] - .pressures - .len(), - ) { - mutations.push(WorldMutation::ChangePressure { - pressure: gestalt_pressure_subject(&child.id, pressure), - owner: subject.clone(), - operation: PressureMutationOperation::Create, - amount: Some(4), - label: Some(pressure.clone()), - }); - } - } - } - for (resource, child_id) in &preview.resource_child_assignments { - mutations.push(WorldMutation::TransferCustody { - resource: resource_subject(campaign, &parent, resource), - from_custodian: parent.clone(), - to_custodian: population_subject(child_id), - }); - } - for member in campaign - .gestalt_members - .values() - .filter(|member| member.gestalt_id == preview.parent_gestalt_id) - { - let destination = preview - .member_child_assignments - .get(&member.id) - .unwrap_or(&preview.residual_child_id); - mutations.push(WorldMutation::ChangePopulationMembership { - actor: actor_subject(&crate::domain::gestalt_member_subject_id(&member.id)), - operation: PopulationMembershipOperation::Transfer, - source_population: Some(parent.clone()), - destination_population: Some(population_subject(destination)), - }); - } - for (jurisdiction, system) in - fission_civic_system_rebindings(campaign, preview, &source_receipt_id) - { - mutations.push(WorldMutation::SetCivicSystem { - jurisdiction, - system, - }); - } - let effect_ceiling = if allow_semantic_additions { - "Admit the approved child populations, preserve their inherited baseline, add only each child's explicitly qualified capabilities, knowledge, goals, and pressures, partition each exact resource once, transfer each named member once, and record one population lineage split." - } else { - "Admit the approved child populations, preserve their inherited baseline, partition each exact resource once, transfer each named member once, and record one population lineage split." - }; - lower_exact_mutations( - campaign, - mutations, - MutationProcedure::CompilerAdmission, - None, - MutationOutcomeBinding::Deterministic, - Some(campaign.resolution_policy.resolution_epoch), - effect_ceiling, - &source_receipt_id, - Some(digest_serializable(&( - "fission", - &preview.parent_gestalt_id, - &preview.partition_axis, - ))?), - Some(preview_digest), - expires_at, - ) -} - -fn elaborated_fission_proposition( - campaign: &Campaign, - statement: &str, -) -> Result<(SubjectRef, bool)> { - if let Some(fact) = campaign - .facts - .values() - .find(|fact| fact.statement == statement) - { - return Ok((proposition_subject(&fact.id), false)); - } - let already_known = campaign - .actors - .values() - .any(|actor| actor.knowledge.contains(statement)) - || campaign - .gestalts - .values() - .any(|gestalt| gestalt.shared_knowledge.contains(statement)) - || campaign.gestalt_members.values().any(|member| { - member.knowledge_additions.contains(statement) - && !member.knowledge_removals.contains(statement) - }); - if already_known { - return Ok(( - proposition_subject(&format!("legacy-knowledge:{}", short_digest(statement))), - false, - )); - } - let fact_id = format!( - "fact:complexity-fission:{:x}", - Sha256::digest(statement.as_bytes()) - ); - if let Some(existing) = campaign.facts.get(&fact_id) { - return if existing.statement == statement { - Ok((proposition_subject(&fact_id), false)) - } else { - Err(anyhow!( - "content-addressed complexity knowledge collided with another fact" - )) - }; - } - Ok((proposition_subject(&fact_id), true)) -} - -fn fission_civic_system_rebindings( - campaign: &Campaign, - preview: &GestaltFissionPreview, - verification_receipt_id: &str, -) -> Vec<(SubjectRef, crate::domain::CivicSystemManifest)> { - let inherited_relation_ids = campaign - .agency_relations - .values() - .filter(|relation| { - relation.active - && (relation.from_subject_id == preview.parent_gestalt_id - || relation.to_subject_id == preview.parent_gestalt_id) - }) - .map(|relation| relation.id.clone()) - .collect::>(); - campaign - .civic_systems - .values() - .filter_map(|system| { - let mut rebound = system.clone(); - if !apply_fission_civic_rebinding( - &mut rebound, - &preview.parent_gestalt_id, - &preview - .children - .iter() - .map(|child| child.id.clone()) - .collect::>(), - &inherited_relation_ids, - ) { - return None; - } - rebound.version = rebound.version.saturating_add(1); - rebound.semantic_verification_receipt_id = verification_receipt_id.into(); - Some((place_subject(&rebound.jurisdiction_location_id), rebound)) - }) - .collect() -} - -fn apply_fission_civic_rebinding( - system: &mut crate::domain::CivicSystemManifest, - parent_id: &str, - child_ids: &[String], - inherited_relation_ids: &BTreeSet, -) -> bool { - let mut changed = false; - if system.resident_population_ids.remove(parent_id) { - system - .resident_population_ids - .extend(child_ids.iter().cloned()); - changed = true; - } - let rebound_relation_ids = system - .political_relation_ids - .intersection(inherited_relation_ids) - .cloned() - .collect::>(); - for relation_id in rebound_relation_ids { - system.political_relation_ids.remove(&relation_id); - system.political_relation_ids.extend( - child_ids - .iter() - .map(|child_id| format!("{relation_id}:fission:{child_id}")), - ); - changed = true; - } - changed -} - -fn fission_civic_reconciliation_rebindings( - campaign: &Campaign, -) -> Vec<(SubjectRef, crate::domain::CivicSystemManifest)> { - campaign - .civic_systems - .values() - .filter_map(|system| { - let mut rebound = system.clone(); - let mut changed = false; - for lineage in campaign.gestalt_lineages.values() { - let inherited_relation_ids = rebound - .political_relation_ids - .iter() - .filter(|relation_id| !campaign.agency_relations.contains_key(*relation_id)) - .filter(|relation_id| { - lineage.child_gestalt_ids.iter().all(|child_id| { - campaign - .agency_relations - .contains_key(&format!("{relation_id}:fission:{child_id}")) - }) - }) - .cloned() - .collect::>(); - changed |= apply_fission_civic_rebinding( - &mut rebound, - &lineage.parent_gestalt_id, - &lineage.child_gestalt_ids, - &inherited_relation_ids, - ); - } - if !changed { - return None; - } - rebound.version = rebound.version.saturating_add(1); - Some((place_subject(&rebound.jurisdiction_location_id), rebound)) - }) - .collect() -} - -pub fn fission_civic_reconciliation_required(campaign: &Campaign) -> bool { - !fission_civic_reconciliation_rebindings(campaign).is_empty() -} - -pub fn lower_fission_civic_reconciliation( - campaign: &Campaign, - expires_at: DateTime, -) -> Result> { - let mut rebindings = fission_civic_reconciliation_rebindings(campaign); - if rebindings.is_empty() { - return Ok(None); - } - let repair_digest = digest_serializable(&(campaign.id, campaign.revision, &rebindings))?; - let source_receipt_id = format!( - "fission-civic-reconciliation:{}", - repair_digest.trim_start_matches("sha256:") - ); - let mutations = rebindings - .iter_mut() - .map(|(jurisdiction, system)| { - system.semantic_verification_receipt_id = source_receipt_id.clone(); - WorldMutation::SetCivicSystem { - jurisdiction: jurisdiction.clone(), - system: system.clone(), - } - }) - .collect(); - lower_exact_mutations( - campaign, - mutations, - MutationProcedure::CompilerAdmission, - None, - MutationOutcomeBinding::Deterministic, - Some(campaign.resolution_policy.resolution_epoch), - "Replace only stale civic population and political-relation bindings whose exact fission lineage and complete child relation set already exist in canonical state.", - &source_receipt_id, - Some(repair_digest.clone()), - Some(repair_digest), - expires_at, - ) - .map(Some) -} - -pub fn apply_lowered_fission_civic_reconciliation( - campaign: &mut Campaign, - transition: &LoweredLegacyTransition, - now: DateTime, -) -> Result { - let snapshot = component_snapshot_for_reconciliation(campaign)?; - let application = - apply_component_world_batch(&snapshot, &transition.authority, &transition.batch, now)?; - for system in application.state.civic_systems.values() { - if campaign - .civic_systems - .get(&system.jurisdiction_location_id) - .is_some_and(|current| current != system) - { - campaign - .civic_systems - .insert(system.jurisdiction_location_id.clone(), system.clone()); - } - } - Ok(application.receipt) -} - -pub fn apply_lowered_fission( - campaign: &mut Campaign, - preview: &GestaltFissionPreview, - transition: &LoweredLegacyTransition, - now: DateTime, -) -> Result { - apply_lowered_fission_with_validation(campaign, preview, transition, now, false) -} - -pub fn apply_lowered_elaborated_fission( - campaign: &mut Campaign, - preview: &GestaltFissionPreview, - transition: &LoweredLegacyTransition, - now: DateTime, -) -> Result { - apply_lowered_fission_with_validation(campaign, preview, transition, now, true) -} - -fn apply_lowered_fission_with_validation( - campaign: &mut Campaign, - preview: &GestaltFissionPreview, - transition: &LoweredLegacyTransition, - now: DateTime, - allow_semantic_additions: bool, -) -> Result { - if allow_semantic_additions { - crate::resolution::validate_elaborated_fission(campaign, preview)?; - } else { - crate::resolution::validate_fission(campaign, preview)?; - } - let snapshot = component_snapshot(campaign)?; - let application = - apply_component_world_batch(&snapshot, &transition.authority, &transition.batch, now)?; - project_accepted_fission(campaign, preview, &application.state)?; - Ok(application.receipt) -} - -pub fn lower_region_expansion( - campaign: &Campaign, - expansion: &crate::domain::RegionExpansion, - expires_at: DateTime, -) -> Result { - crate::compiler::validate_region_expansion(campaign, expansion)?; - let expansion_digest = digest_serializable(expansion)?; - let source_receipt_id = format!( - "region-expansion:{}", - expansion_digest.trim_start_matches("sha256:") - ); - let mut mutations = Vec::new(); - for location in &expansion.locations { - mutations.push(WorldMutation::AdmitEntity { - subject: place_subject(&location.id), - initial_components: BTreeSet::from([ - WorldComponentKind::PlaceProfile, - WorldComponentKind::Topology, - ]), - initial_place: None, - initial_profile: Some(AdmittedEntityProfile::Place { - name: location.name.clone(), - container: location.container_id.as_deref().map(place_subject), - persistent_features: location.persistent_features.iter().cloned().collect(), - }), - admission_receipt_id: source_receipt_id.clone(), - }); - } - for fact in &expansion.facts { - mutations.push(WorldMutation::AdmitEntity { - subject: proposition_subject(&fact.id), - initial_components: BTreeSet::from([ - WorldComponentKind::Knowledge, - WorldComponentKind::PropositionContent, - ]), - initial_place: None, - initial_profile: Some(AdmittedEntityProfile::Proposition { - statement: fact.statement.clone(), - scope: fact.scope.clone(), - evidence_receipt_ids: fact.evidence_receipt_ids.iter().cloned().collect(), - discoverable_at_places: fact - .discoverable_at_location_ids - .iter() - .map(|id| place_subject(id)) - .collect(), - }), - admission_receipt_id: source_receipt_id.clone(), - }); - } - for population in &expansion.populations { - let subject = population_subject(&population.id); - mutations.push(WorldMutation::AdmitEntity { - subject: subject.clone(), - initial_components: BTreeSet::from([ - WorldComponentKind::Identity, - WorldComponentKind::Occupancy, - WorldComponentKind::Capability, - WorldComponentKind::Knowledge, - WorldComponentKind::Commitment, - WorldComponentKind::Pressure, - ]), - initial_place: Some(place_subject(&population.home_location_id)), - initial_profile: None, - admission_receipt_id: source_receipt_id.clone(), - }); - mutations.push(WorldMutation::ChangeIdentity { - subject: subject.clone(), - operation: IdentityMutationOperation::Adopt, - handle_id: format!("identity:canonical:{}", population.id), - handle_value: Some(population.name.clone()), - audience: Vec::new(), - }); - for capability in &population.shared_capabilities { - mutations.push(WorldMutation::ChangeCapability { - subject: subject.clone(), - operation: CapabilityMutationOperation::Grant, - capability_id: capability.clone(), - description: Some(capability.clone()), - }); - } - for statement in &population.shared_knowledge { - let fact = expansion - .facts - .iter() - .chain(campaign.facts.values()) - .find(|fact| fact.statement == *statement) - .ok_or_else(|| { - anyhow!("destination population knowledge lacks an admitted fact") - })?; - mutations.push(WorldMutation::ChangeKnowledge { - operation: KnowledgeMutationOperation::Acquire, - proposition: proposition_subject(&fact.id), - knower: Some(subject.clone()), - speaker: None, - recipients: Vec::new(), - channel: None, - }); - } - for (index, goal) in population.goals.iter().enumerate() { - mutations.push(WorldMutation::ChangeCommitment { - subject: subject.clone(), - operation: CommitmentMutationOperation::Create, - kind: CommitmentKind::Goal, - commitment_id: format!("goal:compiler:{index}:{}", short_digest(goal)), - counterparty: None, - description: Some(goal.clone()), - }); - } - for pressure in &population.pressures { - mutations.push(WorldMutation::ChangePressure { - pressure: gestalt_pressure_subject(&population.id, pressure), - owner: subject.clone(), - operation: PressureMutationOperation::Create, - amount: Some(4), - label: Some(pressure.clone()), - }); - } - for resource in &population.resources { - mutations.push(WorldMutation::MutateResource { - resource: resource_subject(campaign, &subject, resource), - operation: ResourceMutationOperation::Create, - custodian: Some(subject.clone()), - related_resources: Vec::new(), - resource_kind: Some("population_resource".into()), - resource_label: Some(resource.clone()), - recipe_id: None, - quantity: Some(1), - integrity: Some(100), - }); - } - } - for institution in &expansion.institutions { - let subject = institution_subject(&institution.id); - mutations.push(WorldMutation::AdmitEntity { - subject: subject.clone(), - initial_components: BTreeSet::from([ - WorldComponentKind::Identity, - WorldComponentKind::Posture, - WorldComponentKind::Commitment, - ]), - initial_place: None, - initial_profile: None, - admission_receipt_id: source_receipt_id.clone(), - }); - mutations.push(WorldMutation::ChangeIdentity { - subject: subject.clone(), - operation: IdentityMutationOperation::Adopt, - handle_id: format!("identity:canonical:{}", institution.id), - handle_value: Some(institution.name.clone()), - audience: Vec::new(), - }); - mutations.push(WorldMutation::ChangePosture { - subject: subject.clone(), - posture: institution.posture.clone(), - }); - for (index, goal) in institution.goals.iter().enumerate() { - mutations.push(WorldMutation::ChangeCommitment { - subject: subject.clone(), - operation: CommitmentMutationOperation::Create, - kind: CommitmentKind::Goal, - commitment_id: format!("goal:compiler:{index}:{}", short_digest(goal)), - counterparty: None, - description: Some(goal.clone()), - }); - } - for resource in &institution.resources { - mutations.push(WorldMutation::MutateResource { - resource: resource_subject(campaign, &subject, resource), - operation: ResourceMutationOperation::Create, - custodian: Some(subject.clone()), - related_resources: Vec::new(), - resource_kind: Some("institution_resource".into()), - resource_label: Some(resource.clone()), - recipe_id: None, - quantity: Some(1), - integrity: Some(100), - }); - } - } - let origin = place_subject(&expansion.origin_location_id); - for (route_id, route) in &expansion.origin_routes { - mutations.push(WorldMutation::ChangeTopology { - operation: TopologyMutationOperation::Add, - edge_id: component_route_id(&expansion.origin_location_id, route_id), - from_place: origin.clone(), - to_place: place_subject(&route.destination_id), - distance: Some(route.distance.clone()), - travel_minutes: Some(i64::from(route.travel_minutes)), - }); - } - for location in &expansion.locations { - for (route_id, route) in &location.routes { - mutations.push(WorldMutation::ChangeTopology { - operation: TopologyMutationOperation::Add, - edge_id: component_route_id(&location.id, route_id), - from_place: place_subject(&location.id), - to_place: place_subject(&route.destination_id), - distance: Some(route.distance.clone()), - travel_minutes: Some(i64::from(route.travel_minutes)), - }); - } - } - for relation in &expansion.migration_relations { - mutations.push(WorldMutation::ChangeRelationship { - source: population_subject(&relation.from_subject_id), - target: population_subject(&relation.to_subject_id), - operation: RelationshipMutationOperation::Create, - relationship_id: relation.id.clone(), - description: Some("migration".into()), - strength_delta: Some(i64::from(relation.strength)), - }); - } - for relation in &expansion.local_relations { - mutations.push(WorldMutation::ChangeRelationship { - source: expansion_agency_subject(campaign, expansion, &relation.from_subject_id)?, - target: expansion_agency_subject(campaign, expansion, &relation.to_subject_id)?, - operation: RelationshipMutationOperation::Create, - relationship_id: relation.id.clone(), - description: Some(agency_relation_kind_label(&relation.kind).into()), - strength_delta: Some(i64::from(relation.strength)), - }); - } - if let Some(system) = &expansion.civic_system { - let new_population_ids = expansion - .populations - .iter() - .map(|population| population.id.as_str()) - .collect::>(); - for resident_id in &system.resident_population_ids { - if new_population_ids.contains(resident_id.as_str()) { - continue; - } - let resident = campaign.gestalts.get(resident_id).ok_or_else(|| { - anyhow!("civic manifest references an unknown existing resident population") - })?; - for fact_id in system - .public_authority_fact_ids - .iter() - .chain(system.public_selection_fact_ids.iter()) - .chain(system.public_resource_fact_ids.iter()) - .chain(system.public_redress_fact_ids.iter()) - { - let fact = expansion - .facts - .iter() - .find(|fact| fact.id == *fact_id) - .or_else(|| campaign.facts.get(fact_id)) - .ok_or_else(|| anyhow!("civic manifest references an unknown fact"))?; - if !resident.shared_knowledge.contains(&fact.statement) { - mutations.push(WorldMutation::ChangeKnowledge { - operation: KnowledgeMutationOperation::Acquire, - proposition: proposition_subject(fact_id), - knower: Some(population_subject(resident_id)), - speaker: None, - recipients: Vec::new(), - channel: None, - }); - } - } - } - mutations.push(WorldMutation::SetCivicSystem { - jurisdiction: place_subject(&system.jurisdiction_location_id), - system: system.clone(), - }); - } - lower_exact_mutations( - campaign, - mutations, - MutationProcedure::CompilerAdmission, - None, - MutationOutcomeBinding::Deterministic, - None, - "Admit only the approved place profiles, proposition contents, population leaves, institutions, agency inputs, and exact local or migration relations, then add the exact approved route edges without rewriting existing geography or moving any existing subject.", - &source_receipt_id, - Some(digest_serializable(&( - "compile_destination", - &expansion.origin_location_id, - ))?), - Some(expansion_digest), - expires_at, - ) -} - -pub fn apply_lowered_region_expansion( - campaign: &mut Campaign, - expansion: &crate::domain::RegionExpansion, - transition: &LoweredLegacyTransition, - now: DateTime, -) -> Result { - crate::compiler::validate_region_expansion(campaign, expansion)?; - let snapshot = component_snapshot(campaign)?; - let application = - apply_component_world_batch(&snapshot, &transition.authority, &transition.batch, now)?; - project_accepted_region_expansion(campaign, expansion, &application.state)?; - Ok(application.receipt) -} - -fn project_accepted_region_expansion( - campaign: &mut Campaign, - expansion: &crate::domain::RegionExpansion, - next: &ComponentWorldState, -) -> Result<()> { - for requested in &expansion.locations { - let subject = place_subject(&requested.id); - let profile = next - .place_profiles - .get(&subject) - .ok_or_else(|| anyhow!("accepted expansion lost a place profile"))?; - let routes = requested - .routes - .keys() - .map(|route_id| { - let edge_id = component_route_id(&requested.id, route_id); - let edge = next - .topology - .get(&edge_id) - .filter(|edge| edge.from_place == subject && edge.open) - .ok_or_else(|| anyhow!("accepted expansion lost a local route"))?; - Ok(( - route_id.clone(), - crate::domain::Route { - destination_id: edge.to_place.id.clone(), - distance: edge.distance.clone(), - travel_minutes: u32::try_from(edge.travel_minutes).map_err(|_| { - anyhow!("accepted expansion travel time exceeds aggregate storage") - })?, - }, - )) - }) - .collect::>>()?; - campaign.locations.insert( - subject.id.clone(), - crate::domain::Location { - id: subject.id, - name: profile.name.clone(), - container_id: profile - .container - .as_ref() - .map(|container| container.id.clone()), - routes, - persistent_features: profile.persistent_features.iter().cloned().collect(), - }, - ); - } - let origin = campaign - .locations - .get_mut(&expansion.origin_location_id) - .ok_or_else(|| anyhow!("accepted expansion origin vanished"))?; - for route_id in expansion.origin_routes.keys() { - let edge_id = component_route_id(&expansion.origin_location_id, route_id); - let edge = next - .topology - .get(&edge_id) - .filter(|edge| edge.from_place.id == expansion.origin_location_id && edge.open) - .ok_or_else(|| anyhow!("accepted expansion lost an origin route"))?; - origin.routes.insert( - route_id.clone(), - crate::domain::Route { - destination_id: edge.to_place.id.clone(), - distance: edge.distance.clone(), - travel_minutes: u32::try_from(edge.travel_minutes) - .map_err(|_| anyhow!("accepted origin route exceeds aggregate storage"))?, - }, - ); - } - for requested in &expansion.facts { - let subject = proposition_subject(&requested.id); - let value = next - .propositions - .get(&subject) - .ok_or_else(|| anyhow!("accepted expansion lost proposition content"))?; - campaign.facts.insert( - subject.id.clone(), - crate::domain::WorldFact { - id: subject.id, - statement: value.statement.clone(), - scope: value.scope.clone(), - evidence_receipt_ids: value.evidence_receipt_ids.iter().cloned().collect(), - discoverable_at_location_ids: value - .discoverable_at_places - .iter() - .map(|place| place.id.clone()) - .collect(), - }, - ); - } - for requested in &expansion.populations { - let subject = population_subject(&requested.id); - let place = next - .occupancy - .get(&subject) - .filter(|place| place.kind == SubjectKind::Place) - .ok_or_else(|| anyhow!("accepted destination population lost occupancy"))?; - let identity = next - .identities - .get(&format!("identity:canonical:{}", requested.id)) - .filter(|identity| identity.subject == subject && identity.active) - .ok_or_else(|| anyhow!("accepted destination population lost identity"))?; - let mut population = requested.clone(); - population.name = identity.value.clone(); - population.home_location_id = place.id.clone(); - campaign.gestalts.insert(population.id.clone(), population); - } - for requested in &expansion.population_profiles { - let mut profile: AgencyProfile = requested.clone(); - profile.location_ids = BTreeSet::from([campaign - .gestalts - .get(&profile.subject_id) - .ok_or_else(|| anyhow!("accepted destination profile lost population"))? - .home_location_id - .clone()]); - campaign - .agency_profiles - .insert(profile.subject_id.clone(), profile); - } - for requested in &expansion.institutions { - let subject = institution_subject(&requested.id); - let identity = next - .identities - .get(&format!("identity:canonical:{}", requested.id)) - .filter(|identity| identity.subject == subject && identity.active) - .ok_or_else(|| anyhow!("accepted destination institution lost identity"))?; - let posture = next - .postures - .get(&subject) - .ok_or_else(|| anyhow!("accepted destination institution lost posture"))?; - let mut institution = requested.clone(); - institution.name = identity.value.clone(); - institution.posture = posture.clone(); - campaign - .institutions - .insert(institution.id.clone(), institution); - } - for requested in &expansion.institution_profiles { - campaign - .agency_profiles - .insert(requested.subject_id.clone(), requested.clone()); - } - for requested in &expansion.local_relations { - let source = expansion_agency_subject(campaign, expansion, &requested.from_subject_id)?; - let target = expansion_agency_subject(campaign, expansion, &requested.to_subject_id)?; - let value = next - .relationships - .get(&requested.id) - .filter(|value| value.source == source && value.target == target) - .ok_or_else(|| anyhow!("accepted destination local relation vanished"))?; - let mut relation: AgencyRelation = requested.clone(); - relation.strength = u8::try_from( - value - .strength - .ok_or_else(|| anyhow!("accepted destination relation lost strength"))?, - ) - .map_err(|_| anyhow!("accepted destination relation exceeds aggregate storage"))?; - campaign - .agency_relations - .insert(relation.id.clone(), relation); - } - if let Some(requested) = &expansion.civic_system { - let jurisdiction = place_subject(&requested.jurisdiction_location_id); - let accepted = next - .civic_systems - .get(&jurisdiction) - .filter(|system| *system == requested) - .ok_or_else(|| anyhow!("accepted destination civic system vanished"))?; - campaign - .civic_systems - .insert(accepted.jurisdiction_location_id.clone(), accepted.clone()); - for resident_id in &accepted.resident_population_ids { - let resident = campaign - .gestalts - .get_mut(resident_id) - .ok_or_else(|| anyhow!("accepted civic resident population vanished"))?; - for fact_id in accepted - .public_authority_fact_ids - .iter() - .chain(accepted.public_selection_fact_ids.iter()) - .chain(accepted.public_resource_fact_ids.iter()) - .chain(accepted.public_redress_fact_ids.iter()) - { - let proposition = proposition_subject(fact_id); - if !next - .knowledge - .contains_key(&crate::transition::KnowledgeKey { - knower: population_subject(resident_id), - proposition: proposition.clone(), - }) - { - return Err(anyhow!("accepted civic resident lost public knowledge")); - } - resident.shared_knowledge.insert( - next.propositions - .get(&proposition) - .ok_or_else(|| anyhow!("accepted civic fact lost proposition content"))? - .statement - .clone(), - ); - } - } - } - for requested in &expansion.migration_relations { - let value = next - .relationships - .get(&requested.id) - .filter(|value| { - value.source == population_subject(&requested.from_subject_id) - && value.target == population_subject(&requested.to_subject_id) - }) - .ok_or_else(|| anyhow!("accepted destination migration relation vanished"))?; - let mut relation: AgencyRelation = requested.clone(); - relation.strength = u8::try_from( - value - .strength - .ok_or_else(|| anyhow!("accepted destination relation lost strength"))?, - ) - .map_err(|_| anyhow!("accepted destination relation exceeds aggregate storage"))?; - campaign - .agency_relations - .insert(relation.id.clone(), relation); - } - if !expansion.populations.is_empty() || !expansion.institutions.is_empty() { - campaign.resolution_cover = None; - campaign.resolution_policy.resolution_epoch = campaign - .resolution_policy - .resolution_epoch - .saturating_add(1); - } - Ok(()) -} - -fn verify_fission_child_components( - next: &ComponentWorldState, - child: &GestaltPersonaState, -) -> Result<()> { - let subject = population_subject(&child.id); - let capabilities = next - .capabilities - .iter() - .filter(|(key, value)| key.subject == subject && !value.suspended) - .map(|(key, value)| { - if value.description != key.entry_id { - return Err(anyhow!( - "accepted fission capability identity diverged from its description" - )); - } - Ok(key.entry_id.clone()) - }) - .collect::>>()?; - let knowledge = next - .knowledge - .iter() - .filter(|(key, value)| key.knower == subject && value.status == "known") - .map(|(key, _)| { - next.propositions - .get(&key.proposition) - .map(|value| value.statement.clone()) - .ok_or_else(|| anyhow!("accepted fission knowledge lost proposition content")) - }) - .collect::>>()?; - let goals = next - .commitments - .iter() - .filter(|(key, value)| { - key.subject == subject && value.kind == CommitmentKind::Goal && value.status == "active" - }) - .map(|(_, value)| value.description.clone()) - .collect::>(); - let pressures = next - .pressures - .values() - .filter(|value| value.owner == subject && !value.resolved) - .map(|value| value.label.clone()) - .collect::>(); - if capabilities != child.shared_capabilities - || knowledge != child.shared_knowledge - || goals != child.goals.iter().cloned().collect() - || pressures != child.pressures.iter().cloned().collect() - { - return Err(anyhow!( - "accepted fission component semantics diverged from the approved child" - )); - } - Ok(()) -} - -fn project_elaborated_fission_facts( - campaign: &mut Campaign, - preview: &GestaltFissionPreview, - next: &ComponentWorldState, -) -> Result<()> { - let parent = campaign - .gestalts - .get(&preview.parent_gestalt_id) - .ok_or_else(|| anyhow!("accepted complexity fact lost its fission parent"))?; - let mut admitted = BTreeMap::new(); - for child in &preview.children { - let knower = population_subject(&child.id); - for statement in child.shared_knowledge.difference(&parent.shared_knowledge) { - let (proposition_id, needs_admission) = - elaborated_fission_proposition(campaign, statement)?; - if !needs_admission { - continue; - } - let knowledge_key = KnowledgeKey { - knower: knower.clone(), - proposition: proposition_id.clone(), - }; - if !next.knowledge.contains_key(&knowledge_key) { - return Err(anyhow!( - "accepted complexity fact was not acquired by its approved child" - )); - } - let proposition = next - .propositions - .get(&proposition_id) - .ok_or_else(|| anyhow!("accepted complexity fact lost proposition content"))?; - admitted.insert( - proposition_id.id.clone(), - WorldFact { - id: proposition_id.id.clone(), - statement: proposition.statement.clone(), - scope: proposition.scope.clone(), - evidence_receipt_ids: proposition - .evidence_receipt_ids - .iter() - .cloned() - .collect(), - discoverable_at_location_ids: proposition - .discoverable_at_places - .iter() - .map(|place| place.id.clone()) - .collect(), - }, - ); - } - } - campaign.facts.extend(admitted); - Ok(()) -} - -fn project_accepted_fission( - campaign: &mut Campaign, - preview: &GestaltFissionPreview, - next: &ComponentWorldState, -) -> Result<()> { - let parent = campaign - .gestalts - .get(&preview.parent_gestalt_id) - .cloned() - .ok_or_else(|| anyhow!("accepted fission parent vanished"))?; - let inherited_relations = campaign - .agency_relations - .values() - .filter(|relation| { - relation.active - && (relation.from_subject_id == preview.parent_gestalt_id - || relation.to_subject_id == preview.parent_gestalt_id) - }) - .cloned() - .collect::>(); - project_elaborated_fission_facts(campaign, preview, next)?; - - for approved in &preview.children { - let subject = population_subject(&approved.id); - let place = next - .occupancy - .get(&subject) - .filter(|place| place.kind == SubjectKind::Place) - .ok_or_else(|| anyhow!("accepted fission child lacks exact occupancy"))?; - let identity = next - .identities - .get(&format!("identity:canonical:{}", approved.id)) - .filter(|identity| identity.subject == subject && identity.active) - .ok_or_else(|| anyhow!("accepted fission child lacks exact identity"))?; - verify_fission_child_components(next, approved)?; - let mut accepted = approved.clone(); - accepted.name = identity.value.clone(); - accepted.home_location_id = place.id.clone(); - accepted.resources.clear(); - campaign.gestalts.insert(approved.id.clone(), accepted); - } - - let member_ids = campaign - .gestalt_members - .values() - .filter(|member| member.gestalt_id == preview.parent_gestalt_id) - .map(|member| member.id.clone()) - .collect::>(); - for member_id in member_ids { - let expected_destination = preview - .member_child_assignments - .get(&member_id) - .unwrap_or(&preview.residual_child_id); - let actor = actor_subject(&crate::domain::gestalt_member_subject_id(&member_id)); - let active_destinations = next - .memberships - .iter() - .filter(|(key, value)| key.actor == actor && value.active) - .map(|(key, _)| key.population.id.as_str()) - .collect::>(); - if active_destinations != [expected_destination.as_str()] { - return Err(anyhow!( - "accepted fission member does not have one exact destination" - )); - } - project_member_population_transfer( - campaign, - &member_id, - &preview.parent_gestalt_id, - expected_destination, - )?; - let member = campaign - .gestalt_members - .get_mut(&member_id) - .expect("member was projected"); - member.version = member.version.saturating_add(1); - } - - project_all_resources(campaign, next)?; - for child in &preview.children { - if campaign.gestalts[&child.id].resources != child.resources { - return Err(anyhow!( - "accepted fission resource custody does not match the approved partition" - )); - } - } - campaign - .gestalts - .get_mut(&preview.parent_gestalt_id) - .expect("parent existence checked") - .version = parent.version.saturating_add(1); - - for relation in inherited_relations { - for child in &preview.children { - let id = format!("{}:fission:{}", relation.id, child.id); - let component = next - .relationships - .get(&id) - .ok_or_else(|| anyhow!("accepted fission lost inherited agency relation"))?; - let mut inherited = relation.clone(); - inherited.id = id.clone(); - if inherited.from_subject_id == preview.parent_gestalt_id { - inherited.from_subject_id = child.id.clone(); - } - if inherited.to_subject_id == preview.parent_gestalt_id { - inherited.to_subject_id = child.id.clone(); - } - if component.source.id != inherited.from_subject_id - || component.target.id != inherited.to_subject_id - || component.strength != Some(i64::from(inherited.strength)) - { - return Err(anyhow!("accepted fission agency relation was rewritten")); - } - campaign.agency_relations.insert(id, inherited); - } - campaign.agency_relations.remove(&relation.id); - } - for system in next.civic_systems.values() { - if campaign - .civic_systems - .get(&system.jurisdiction_location_id) - .is_some_and(|current| current != system) - { - campaign - .civic_systems - .insert(system.jurisdiction_location_id.clone(), system.clone()); - } - } - campaign.gestalt_lineages.insert( - preview.parent_gestalt_id.clone(), - GestaltLineage { - schema: "ghostlight.gestalt_lineage.v1".into(), - parent_gestalt_id: preview.parent_gestalt_id.clone(), - child_gestalt_ids: preview - .children - .iter() - .map(|child| child.id.clone()) - .collect(), - partition_axis: preview.partition_axis.clone(), - partition_values: preview.child_partition_values.clone(), - residual_child_id: preview.residual_child_id.clone(), - source_revision: campaign.revision, - }, - ); - crate::resolution::project_fission_resolution(campaign, preview)?; - Ok(()) -} - -#[allow(clippy::too_many_arguments)] -fn lower_exact_mutations( - campaign: &Campaign, - mutations: Vec, - procedure: MutationProcedure, - source_subject: Option, - outcome: MutationOutcomeBinding, - resolution_epoch: Option, - effect_ceiling: &str, - source_receipt_id: &str, - means_digest: Option, - intended_effect_digest: Option, - expires_at: DateTime, -) -> Result { - let mut permits = Vec::with_capacity(mutations.len()); - let mut permitted = Vec::with_capacity(mutations.len()); - for (index, mutation) in mutations.into_iter().enumerate() { - let permit_id = format!("permit:{source_receipt_id}:{index}"); - permits.push(exact_mutation_permit(permit_id.clone(), &mutation)?); - permitted.push(PermittedWorldMutation { - permit_id, - mutation, - }); - } - let mut authority = MutationAuthorityEnvelope { - schema: "ghostlight.mutation_authority_envelope.v1".into(), - id: format!( - "authority:{}:{}:{}", - campaign.id, - campaign.revision, - short_digest(source_receipt_id) - ), - campaign_id: campaign.id, - world_revision: campaign.revision, - resolution_epoch, - procedure, - source_subject, - outcome, - effect_ceiling: effect_ceiling.into(), - permits, - authority_receipt_ids: BTreeSet::from([source_receipt_id.into()]), - expires_at, - digest: String::new(), - }; - authority.digest = envelope_digest(&authority)?; - let mut batch = WorldMutationBatch { - schema: "ghostlight.world_mutation_batch.v1".into(), - id: format!( - "batch:{}:{}:{}", - campaign.id, - campaign.revision, - short_digest(source_receipt_id) - ), - campaign_id: campaign.id, - expected_world_revision: campaign.revision, - expected_resolution_epoch: resolution_epoch, - authority_envelope_digest: authority.digest.clone(), - source_receipt_id: source_receipt_id.into(), - means_digest, - intended_effect_digest, - mutations: permitted, - digest: String::new(), - }; - batch.digest = mutation_batch_digest(&batch)?; - Ok(LoweredLegacyTransition { authority, batch }) -} - -pub fn apply_lowered_transition( - campaign: &mut Campaign, - transition: &LoweredLegacyTransition, - now: DateTime, -) -> Result { - let snapshot = component_snapshot(campaign)?; - let mut application = - apply_component_world_batch(&snapshot, &transition.authority, &transition.batch, now)?; - project_mutated_components(campaign, &application.state, &transition.batch)?; - application.receipt.derived_event_ids = - crate::clock::materialize_due_clock_consequences(campaign)?; - Ok(application.receipt) -} - -pub fn lower_reaction_wave( - campaign: &Campaign, - witnessed_memory: &str, - reactions: &[ActorReaction], - source_receipt_id: &str, - expires_at: DateTime, -) -> Result { - let mut mutations = Vec::new(); - for reaction in reactions { - let actor = campaign - .actors - .get(&reaction.actor_id) - .ok_or_else(|| anyhow!("reaction actor is unknown"))?; - let subject = actor_subject(&reaction.actor_id); - if actor.memories.len() < 64 - && !actor.memories.iter().any(|value| value == witnessed_memory) - { - mutations.push(WorldMutation::ChangeMemory { - subject: subject.clone(), - operation: MemoryMutationOperation::Record, - memory_id: format!( - "memory:reaction:{}:{}", - campaign.revision + 1, - short_digest(&reaction.actor_id) - ), - event_id: Some(format!("reaction-wave:{}", campaign.revision + 1)), - summary: Some(witnessed_memory.into()), - }); - } - if let Some(identity) = reaction.private_delta.identity_adoption.as_deref() - && identity != actor.name - { - let handle_id = format!( - "identity:adopted:{}:{}", - reaction.actor_id, - short_digest(identity) - ); - let audience = campaign - .actors - .values() - .filter(|observer| { - observer.id != reaction.actor_id && observer.location_id == actor.location_id - }) - .map(|observer| actor_subject(&observer.id)) - .collect::>(); - mutations.push(WorldMutation::ChangeIdentity { - subject: subject.clone(), - operation: IdentityMutationOperation::Adopt, - handle_id: handle_id.clone(), - handle_value: Some(identity.into()), - audience: Vec::new(), - }); - if !audience.is_empty() { - mutations.push(WorldMutation::ChangeIdentity { - subject: subject.clone(), - operation: IdentityMutationOperation::Disclose, - handle_id, - handle_value: Some(identity.into()), - audience, - }); - } - } - for condition in &reaction.private_delta.conditions_add { - mutations.push(WorldMutation::ChangeCondition { - subject: subject.clone(), - operation: if actor.conditions.contains(condition) { - ConditionMutationOperation::Alter - } else { - ConditionMutationOperation::Apply - }, - condition_id: condition.clone(), - description: Some(condition.clone()), - severity: None, - }); - } - for condition in &reaction.private_delta.conditions_remove { - mutations.push(WorldMutation::ChangeCondition { - subject: subject.clone(), - operation: ConditionMutationOperation::Clear, - condition_id: condition.clone(), - description: None, - severity: None, - }); - } - for goal in &reaction.private_delta.goals_add { - if actor.goals.contains(goal) { - continue; - } - mutations.push(WorldMutation::ChangeCommitment { - subject: subject.clone(), - operation: CommitmentMutationOperation::Create, - kind: CommitmentKind::Goal, - commitment_id: format!( - "goal:reaction:{}:{}", - campaign.revision + 1, - short_digest(goal) - ), - counterparty: None, - description: Some(goal.clone()), - }); - } - for (target_id, description) in &reaction.private_delta.relationship_updates { - let target = resolve_subject(campaign, target_id) - .ok_or_else(|| anyhow!("reaction relationship target is unknown"))?; - mutations.push(WorldMutation::ChangeRelationship { - source: subject.clone(), - target, - operation: if actor.relationships.contains_key(target_id) { - RelationshipMutationOperation::Alter - } else { - RelationshipMutationOperation::Create - }, - relationship_id: relationship_id(&reaction.actor_id, target_id), - description: Some(description.clone()), - strength_delta: None, - }); - } - } - lower_exact_mutations( - campaign, - mutations, - MutationProcedure::ReactionAppraisal, - None, - MutationOutcomeBinding::Deterministic, - None, - "Each exact reacting actor may update only their own public self-identity, private memory, conditions, goals, and directed relationships.", - source_receipt_id, - Some(digest_serializable(reactions)?), - None, - expires_at, - ) -} - -pub fn lower_strategic_wave( - campaign: &Campaign, - plan: &StrategicTickPlan, - source_receipt_id: &str, - expires_at: DateTime, -) -> Result> { - let mut mutations = vec![WorldMutation::AdvanceWorldTime { - campaign: campaign_subject(campaign), - minutes: i64::from(campaign.tick_hours).saturating_mul(60), - }]; - for clock in campaign - .clocks - .values() - .filter(|clock| clock.progress < clock.threshold) - { - mutations.push(WorldMutation::ChangePressure { - pressure: pressure_subject(&clock.id), - owner: campaign_subject(campaign), - operation: PressureMutationOperation::Advance, - amount: Some(1), - label: None, - }); - } - for action in &plan.selected_actions { - let subject = if campaign.actors.contains_key(&action.subject_id) { - Some(actor_subject(&action.subject_id)) - } else if let Some(member_id) = action.subject_id.strip_prefix("member:") - && campaign.gestalt_members.contains_key(member_id) - { - Some(actor_subject(&action.subject_id)) - } else { - None - }; - let Some(subject) = subject else { - continue; - }; - let action_digest = crate::resolution::cell_action_digest(action)?; - let summary = format!( - "I chose to {}. I intended to {}.", - action.intent.trim(), - action.intended_effect.trim() - ); - if action.intent.trim().is_empty() - || action.intended_effect.trim().is_empty() - || summary.chars().count() > 1_000 - { - return Err(anyhow!( - "strategic choice cannot be retained as bounded actor memory" - )); - } - mutations.push(WorldMutation::ChangeMemory { - subject, - operation: MemoryMutationOperation::Record, - memory_id: format!( - "memory:strategic-choice:{}:{}", - campaign.revision + 1, - short_digest(&action_digest) - ), - event_id: Some(action_digest), - summary: Some(summary), - }); - } - for action in &plan.institution_actions { - mutations.push(WorldMutation::ChangePosture { - subject: institution_subject(&action.institution_id), - posture: action.posture.clone(), - }); - } - for action in &plan.gestalt_actions { - let owner = population_subject(&action.gestalt_id); - for label in &action.pressure_additions { - mutations.push(WorldMutation::ChangePressure { - pressure: gestalt_pressure_subject(&action.gestalt_id, label), - owner: owner.clone(), - operation: PressureMutationOperation::Create, - amount: Some(4), - label: Some(label.clone()), - }); - } - for label in &action.pressure_resolutions { - mutations.push(WorldMutation::ChangePressure { - pressure: gestalt_pressure_subject(&action.gestalt_id, label), - owner: owner.clone(), - operation: PressureMutationOperation::Resolve, - amount: None, - label: None, - }); - } - } - for action in &plan.gestalt_migrations { - let source = campaign - .gestalts - .get(&action.gestalt_id) - .ok_or_else(|| anyhow!("strategic population source is unknown"))?; - mutations.push(WorldMutation::Relocate { - subject: population_subject(&action.gestalt_id), - from_place: place_subject(&source.home_location_id), - to_place: place_subject(&action.destination_location_id), - route_id: exact_route_id( - campaign, - &source.home_location_id, - &action.destination_location_id, - )?, - }); - } - for action in &plan.actor_moves { - let actor = campaign - .actors - .get(&action.actor_id) - .ok_or_else(|| anyhow!("strategic movement actor is unknown"))?; - mutations.push(WorldMutation::Relocate { - subject: actor_subject(&action.actor_id), - from_place: place_subject(&actor.location_id), - to_place: place_subject(&action.destination_id), - route_id: exact_route_id(campaign, &actor.location_id, &action.destination_id)?, - }); - } - for action in &plan.member_migrations { - let member = campaign - .gestalt_members - .get(&action.member_id) - .ok_or_else(|| anyhow!("strategic member is unknown"))?; - let source = campaign - .gestalts - .get(&action.source_gestalt_id) - .ok_or_else(|| anyhow!("strategic member source population is unknown"))?; - let origin = member - .last_location_id - .as_deref() - .unwrap_or(&source.home_location_id); - let subject = actor_subject(&crate::domain::gestalt_member_subject_id(&action.member_id)); - if origin != action.destination_location_id { - mutations.push(WorldMutation::Relocate { - subject: subject.clone(), - from_place: place_subject(origin), - to_place: place_subject(&action.destination_location_id), - route_id: exact_route_id(campaign, origin, &action.destination_location_id)?, - }); - } - mutations.push(WorldMutation::ChangePopulationMembership { - actor: subject, - operation: PopulationMembershipOperation::Transfer, - source_population: Some(population_subject(&action.source_gestalt_id)), - destination_population: Some(population_subject(&action.destination_gestalt_id)), - }); - } - - let mut bindings = Vec::with_capacity(plan.activity_outcomes.len()); - for outcome in &plan.activity_outcomes { - bindings.push(StrategicOutcomeSourceBinding { - action_digest: outcome.action_digest.clone(), - band: outcome.band.clone(), - }); - push_strategic_outcome_mutations(campaign, outcome, &mut mutations)?; - } - if mutations.is_empty() { - return Ok(None); - } - Ok(Some(lower_exact_mutations( - campaign, - mutations, - MutationProcedure::StrategicOutcome, - None, - MutationOutcomeBinding::StrategicWave(bindings), - Some(campaign.resolution_policy.resolution_epoch), - "The strategic wave may commit only the exact admitted movements, posture changes, population transitions, and constituent-attributed consequences selected by its resolution receipt.", - source_receipt_id, - Some(digest_serializable(plan)?), - None, - expires_at, - )?)) -} - -fn push_strategic_outcome_mutations( - campaign: &Campaign, - outcome: &StrategicActivityOutcome, - mutations: &mut Vec, -) -> Result<()> { - match &outcome.effect { - StrategicOutcomeEffect::NoMaterialChange { .. } => {} - StrategicOutcomeEffect::ResourceCreated { - owner_subject_id, - resource, - } => { - let owner = resolve_subject(campaign, owner_subject_id) - .ok_or_else(|| anyhow!("strategic resource owner is unknown"))?; - mutations.push(WorldMutation::MutateResource { - resource: resource_subject(campaign, &owner, resource), - operation: ResourceMutationOperation::Create, - custodian: Some(owner), - related_resources: Vec::new(), - resource_kind: Some("legacy_named_resource".into()), - resource_label: Some(resource.clone()), - recipe_id: None, - quantity: Some(1), - integrity: Some(100), - }); - } - StrategicOutcomeEffect::ResourceConsumed { - owner_subject_id, - resource, - } => { - let owner = resolve_subject(campaign, owner_subject_id) - .ok_or_else(|| anyhow!("strategic resource owner is unknown"))?; - mutations.push(WorldMutation::MutateResource { - resource: resource_subject(campaign, &owner, resource), - operation: ResourceMutationOperation::Consume, - custodian: Some(owner), - related_resources: Vec::new(), - resource_kind: None, - resource_label: None, - recipe_id: None, - quantity: Some(1), - integrity: None, - }); - } - StrategicOutcomeEffect::ResourceTransferred { - from_subject_id, - to_subject_id, - resource, - } => { - let from = resolve_subject(campaign, from_subject_id) - .ok_or_else(|| anyhow!("strategic resource source is unknown"))?; - let to = resolve_subject(campaign, to_subject_id) - .ok_or_else(|| anyhow!("strategic resource recipient is unknown"))?; - mutations.push(WorldMutation::TransferCustody { - resource: resource_subject(campaign, &from, resource), - from_custodian: from, - to_custodian: to, - }); - } - StrategicOutcomeEffect::GestaltPressure { - gestalt_id, - pressure_additions, - pressure_resolutions, - } => { - let owner = population_subject(gestalt_id); - if !campaign.gestalts.contains_key(gestalt_id) { - return Err(anyhow!("strategic pressure owner is unknown")); - } - for label in pressure_additions { - mutations.push(WorldMutation::ChangePressure { - pressure: gestalt_pressure_subject(gestalt_id, label), - owner: owner.clone(), - operation: PressureMutationOperation::Create, - amount: Some(4), - label: Some(label.clone()), - }); - } - for label in pressure_resolutions { - mutations.push(WorldMutation::ChangePressure { - pressure: gestalt_pressure_subject(gestalt_id, label), - owner: owner.clone(), - operation: PressureMutationOperation::Resolve, - amount: None, - label: None, - }); - } - } - StrategicOutcomeEffect::AgencyRelationShift { - relation_id, - strength_delta, - } => { - let relation = campaign - .agency_relations - .get(relation_id) - .ok_or_else(|| anyhow!("strategic agency relation is unknown"))?; - let source = resolve_subject(campaign, &relation.from_subject_id) - .ok_or_else(|| anyhow!("strategic relation source is unknown"))?; - let target = resolve_subject(campaign, &relation.to_subject_id) - .ok_or_else(|| anyhow!("strategic relation target is unknown"))?; - mutations.push(WorldMutation::ChangeRelationship { - source, - target, - operation: RelationshipMutationOperation::Alter, - relationship_id: relation_id.clone(), - description: None, - strength_delta: Some(i64::from(*strength_delta)), - }); - } - StrategicOutcomeEffect::MemberMemory { member_id, memory } => { - ensure_member(campaign, member_id)?; - mutations.push(WorldMutation::ChangeMemory { - subject: actor_subject(&crate::domain::gestalt_member_subject_id(member_id)), - operation: MemoryMutationOperation::Record, - memory_id: format!( - "memory:strategic:{}:{}", - campaign.revision + 1, - short_digest(memory) - ), - event_id: Some(outcome.action_digest.clone()), - summary: Some(memory.clone()), - }); - } - StrategicOutcomeEffect::MemberObligation { - member_id, - obligation, - } => { - ensure_member(campaign, member_id)?; - mutations.push(WorldMutation::ChangeCommitment { - subject: actor_subject(&crate::domain::gestalt_member_subject_id(member_id)), - operation: CommitmentMutationOperation::Create, - kind: CommitmentKind::Obligation, - commitment_id: format!( - "obligation:strategic:{}:{}", - campaign.revision + 1, - short_digest(obligation) - ), - counterparty: None, - description: Some(obligation.clone()), - }); - } - StrategicOutcomeEffect::MemberRelationship { - member_id, - other_subject_id, - description, - } => { - let member = ensure_member(campaign, member_id)?; - let target = resolve_subject(campaign, other_subject_id) - .ok_or_else(|| anyhow!("strategic member relationship target is unknown"))?; - let source = actor_subject(&crate::domain::gestalt_member_subject_id(member_id)); - mutations.push(WorldMutation::ChangeRelationship { - source: source.clone(), - target, - operation: if member.relationships.contains_key(other_subject_id) { - RelationshipMutationOperation::Alter - } else { - RelationshipMutationOperation::Create - }, - relationship_id: relationship_id(&source.id, other_subject_id), - description: Some(description.clone()), - strength_delta: None, - }); - } - StrategicOutcomeEffect::KnowledgeLearned { - owner_subject_id, - fact_id, - } => { - let knower = resolve_subject(campaign, owner_subject_id) - .ok_or_else(|| anyhow!("strategic knowledge owner is unknown"))?; - if !campaign.facts.contains_key(fact_id) { - return Err(anyhow!("strategic proposition is unknown")); - } - mutations.push(WorldMutation::ChangeKnowledge { - operation: KnowledgeMutationOperation::Acquire, - proposition: proposition_subject(fact_id), - knower: Some(knower), - speaker: None, - recipients: Vec::new(), - channel: None, - }); - } - StrategicOutcomeEffect::KnowledgeCommunicated { - from_subject_id, - to_subject_ids, - fact_id, - } => { - let speaker = resolve_subject(campaign, from_subject_id) - .ok_or_else(|| anyhow!("strategic knowledge speaker is unknown"))?; - let recipients = to_subject_ids - .iter() - .map(|subject_id| { - resolve_subject(campaign, subject_id) - .ok_or_else(|| anyhow!("strategic knowledge recipient is unknown")) - }) - .collect::>>()?; - if !campaign.facts.contains_key(fact_id) { - return Err(anyhow!("strategic proposition is unknown")); - } - mutations.push(WorldMutation::ChangeKnowledge { - operation: KnowledgeMutationOperation::Communicate, - proposition: proposition_subject(fact_id), - knower: None, - speaker: Some(speaker), - recipients, - channel: None, - }); - } - } - Ok(()) -} - -fn exact_route_id(campaign: &Campaign, origin: &str, destination: &str) -> Result { - campaign - .locations - .get(origin) - .and_then(|location| { - location.routes.iter().find_map(|(route_id, route)| { - (route.destination_id == destination).then(|| component_route_id(origin, route_id)) - }) - }) - .ok_or_else(|| anyhow!("strategic relocation has no exact topology edge")) -} - -fn component_route_id(origin: &str, local_route_id: &str) -> String { - format!("route:{}:{origin}:{local_route_id}", origin.len()) -} - -pub fn digest_serializable(value: &T) -> Result { - let bytes = rmp_serde::to_vec_named(value)?; - Ok(format!("sha256:{:x}", Sha256::digest(bytes))) -} - -fn foreground_mutations( - campaign: &Campaign, - effect: &WorldEffectDelta, - source_receipt_id: &str, -) -> Result> { - let mut mutations = Vec::new(); - for (actor_id, delta) in &effect.actor_conditions { - let actor = campaign - .actors - .get(actor_id) - .ok_or_else(|| anyhow!("outcome actor vanished"))?; - for condition in &delta.add { - mutations.push(WorldMutation::ChangeCondition { - subject: actor_subject(actor_id), - operation: if actor.conditions.contains(condition) { - ConditionMutationOperation::Alter - } else { - ConditionMutationOperation::Apply - }, - condition_id: condition.clone(), - description: Some(condition.clone()), - severity: None, - }); - } - for condition in &delta.remove { - mutations.push(WorldMutation::ChangeCondition { - subject: actor_subject(actor_id), - operation: ConditionMutationOperation::Clear, - condition_id: condition.clone(), - description: None, - severity: None, - }); - } - } - for (actor_id, delta) in &effect.actor_commitments { - let actor = campaign - .actors - .get(actor_id) - .ok_or_else(|| anyhow!("outcome actor vanished"))?; - let subject = actor_subject(actor_id); - for goal in &delta.goals_add { - if actor.goals.contains(goal) { - return Err(anyhow!("outcome commitment already exists")); - } - mutations.push(WorldMutation::ChangeCommitment { - subject: subject.clone(), - operation: CommitmentMutationOperation::Create, - kind: CommitmentKind::Goal, - commitment_id: format!( - "goal:foreground:{}:{}", - campaign.revision, - short_digest(goal) - ), - counterparty: None, - description: Some(goal.clone()), - }); - } - for goal in &delta.goals_retire { - let index = actor - .goals - .iter() - .position(|existing| existing == goal) - .ok_or_else(|| anyhow!("outcome commitment does not exist"))?; - mutations.push(WorldMutation::ChangeCommitment { - subject: subject.clone(), - operation: CommitmentMutationOperation::Retire, - kind: CommitmentKind::Goal, - commitment_id: format!("goal:{index}:{}", short_digest(goal)), - counterparty: None, - description: None, - }); - } - for obligation in &delta.obligations_add { - if actor.obligations.contains(obligation) { - return Err(anyhow!("outcome commitment already exists")); - } - mutations.push(WorldMutation::ChangeCommitment { - subject: subject.clone(), - operation: CommitmentMutationOperation::Create, - kind: CommitmentKind::Obligation, - commitment_id: format!( - "obligation:foreground:{}:{}", - campaign.revision, - short_digest(obligation) - ), - counterparty: None, - description: Some(obligation.clone()), - }); - } - for obligation in &delta.obligations_retire { - if !actor.obligations.contains(obligation) { - return Err(anyhow!("outcome commitment does not exist")); - } - mutations.push(WorldMutation::ChangeCommitment { - subject: subject.clone(), - operation: CommitmentMutationOperation::Retire, - kind: CommitmentKind::Obligation, - commitment_id: format!("obligation:{}", short_digest(obligation)), - counterparty: None, - description: None, - }); - } - } - for (actor_id, additions) in &effect.actor_knowledge_additions { - if !campaign.actors.contains_key(actor_id) { - return Err(anyhow!("outcome actor vanished")); - } - for statement in additions { - let fact = campaign - .facts - .values() - .find(|fact| fact.statement == *statement) - .ok_or_else(|| anyhow!("outcome knowledge has no canonical proposition"))?; - mutations.push(WorldMutation::ChangeKnowledge { - operation: KnowledgeMutationOperation::Acquire, - proposition: proposition_subject(&fact.id), - knower: Some(actor_subject(actor_id)), - speaker: None, - recipients: Vec::new(), - channel: None, - }); - } - } - for (actor_id, observations) in &effect.actor_observations { - let actor = campaign - .actors - .get(actor_id) - .ok_or_else(|| anyhow!("outcome observation actor vanished"))?; - for statement in observations { - if campaign - .facts - .values() - .any(|fact| fact.statement == statement.as_str()) - || actor.knowledge.contains(statement) - { - return Err(anyhow!("outcome observation is not a new proposition")); - } - let proposition_id = format!( - "fact:branch-observation:{:x}", - Sha256::digest(statement.as_bytes()) - ); - if campaign.facts.contains_key(&proposition_id) { - return Err(anyhow!("outcome observation proposition id collided")); - } - let proposition = proposition_subject(&proposition_id); - mutations.push(WorldMutation::AdmitEntity { - subject: proposition.clone(), - initial_components: BTreeSet::from([ - WorldComponentKind::Knowledge, - WorldComponentKind::PropositionContent, - ]), - initial_place: None, - initial_profile: Some(AdmittedEntityProfile::Proposition { - statement: statement.clone(), - scope: FactScope::BranchLocal, - evidence_receipt_ids: BTreeSet::new(), - discoverable_at_places: BTreeSet::from([place_subject(&actor.location_id)]), - }), - admission_receipt_id: source_receipt_id.into(), - }); - mutations.push(WorldMutation::ChangeKnowledge { - operation: KnowledgeMutationOperation::Acquire, - proposition, - knower: Some(actor_subject(actor_id)), - speaker: None, - recipients: Vec::new(), - channel: None, - }); - } - } - for (actor_id, relationships) in &effect.actor_relationship_updates { - let actor = campaign - .actors - .get(actor_id) - .ok_or_else(|| anyhow!("outcome actor vanished"))?; - for (target_id, description) in relationships { - let target = resolve_subject(campaign, target_id) - .ok_or_else(|| anyhow!("relationship target vanished"))?; - mutations.push(WorldMutation::ChangeRelationship { - source: actor_subject(actor_id), - target, - operation: if actor.relationships.contains_key(target_id) { - RelationshipMutationOperation::Alter - } else { - RelationshipMutationOperation::Create - }, - relationship_id: relationship_id(actor_id, target_id), - description: Some(description.clone()), - strength_delta: None, - }); - } - } - for (actor_id, destination_id) in &effect.actor_moves { - let actor = campaign - .actors - .get(actor_id) - .ok_or_else(|| anyhow!("outcome actor vanished"))?; - let route_id = exact_route_id(campaign, &actor.location_id, destination_id) - .map_err(|_| anyhow!("outcome movement has no exact route"))?; - mutations.push(WorldMutation::Relocate { - subject: actor_subject(actor_id), - from_place: place_subject(&actor.location_id), - to_place: place_subject(destination_id), - route_id, - }); - } - let campaign_subject = campaign_subject(campaign); - for (clock_id, amount) in &effect.clock_advances { - mutations.push(WorldMutation::ChangePressure { - pressure: pressure_subject(clock_id), - owner: campaign_subject.clone(), - operation: PressureMutationOperation::Advance, - amount: Some(i64::from(*amount)), - label: None, - }); - } - for (clock_id, amount) in &effect.clock_reductions { - mutations.push(WorldMutation::ChangePressure { - pressure: pressure_subject(clock_id), - owner: campaign_subject.clone(), - operation: PressureMutationOperation::Reduce, - amount: Some(i64::from(*amount)), - label: None, - }); - } - for (institution_id, posture) in &effect.institution_postures { - if !campaign.institutions.contains_key(institution_id) { - return Err(anyhow!("outcome institution vanished")); - } - mutations.push(WorldMutation::ChangePosture { - subject: institution_subject(institution_id), - posture: posture.clone(), - }); - } - Ok(mutations) -} - -fn component_snapshot(campaign: &Campaign) -> Result { - component_snapshot_with_validation(campaign, true) -} - -fn component_snapshot_for_reconciliation(campaign: &Campaign) -> Result { - component_snapshot_with_validation(campaign, false) -} - -fn component_snapshot_with_validation( - campaign: &Campaign, - validate: bool, -) -> Result { - let version = campaign.revision; - let mut state = ComponentWorldState { - schema: "ghostlight.component_world_state.v1".into(), - campaign_id: campaign.id, - revision: campaign.revision, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - world_time: campaign.world_time, - subjects: BTreeMap::new(), - occupancy: BTreeMap::new(), - custody: BTreeMap::new(), - resources: BTreeMap::new(), - capabilities: BTreeMap::new(), - conditions: BTreeMap::new(), - commitments: BTreeMap::new(), - relationships: BTreeMap::new(), - pressures: BTreeMap::new(), - knowledge: BTreeMap::new(), - memories: BTreeMap::new(), - postures: BTreeMap::new(), - memberships: BTreeMap::new(), - population_lineages: BTreeMap::new(), - identities: BTreeMap::new(), - place_profiles: BTreeMap::new(), - propositions: BTreeMap::new(), - topology: BTreeMap::new(), - civic_systems: campaign - .civic_systems - .values() - .map(|system| { - ( - place_subject(&system.jurisdiction_location_id), - system.clone(), - ) - }) - .collect(), - }; - admit( - &mut state, - campaign_subject(campaign), - BTreeSet::from([WorldComponentKind::WorldTime]), - version, - ); - for location in campaign.locations.values() { - admit( - &mut state, - place_subject(&location.id), - BTreeSet::from([ - WorldComponentKind::PlaceProfile, - WorldComponentKind::Topology, - ]), - version, - ); - let place = place_subject(&location.id); - state.place_profiles.insert( - place.clone(), - PlaceComponentState { - place, - name: location.name.clone(), - container: location.container_id.as_deref().map(place_subject), - persistent_features: location.persistent_features.iter().cloned().collect(), - version, - }, - ); - } - for actor in campaign.actors.values() { - let subject = actor_subject(&actor.id); - admit( - &mut state, - subject.clone(), - BTreeSet::from([ - WorldComponentKind::Identity, - WorldComponentKind::Occupancy, - WorldComponentKind::Capability, - WorldComponentKind::Condition, - WorldComponentKind::Knowledge, - WorldComponentKind::Memory, - WorldComponentKind::Relationship, - WorldComponentKind::Commitment, - ]), - version, - ); - state - .occupancy - .insert(subject.clone(), place_subject(&actor.location_id)); - state.identities.insert( - format!("identity:canonical:{}", actor.id), - IdentityHandleState { - schema: "ghostlight.identity_handle.v1".into(), - id: format!("identity:canonical:{}", actor.id), - subject: subject.clone(), - value: actor.name.clone(), - active: true, - known_by: BTreeSet::from([subject.clone()]), - restricted_to: BTreeSet::new(), - source_revision: version, - }, - ); - for capability in &actor.capabilities { - state.capabilities.insert( - entry_key(&subject, capability), - CapabilityComponentState { - description: capability.clone(), - suspended: false, - version, - }, - ); - } - for condition in &actor.conditions { - state.conditions.insert( - entry_key(&subject, condition), - ConditionComponentState { - description: condition.clone(), - severity: None, - version, - }, - ); - } - for (index, goal) in actor.goals.iter().enumerate() { - state.commitments.insert( - entry_key(&subject, &format!("goal:{index}:{}", short_digest(goal))), - CommitmentComponentState { - kind: CommitmentKind::Goal, - description: goal.clone(), - counterparty: None, - status: "active".into(), - version, - }, - ); - } - for obligation in &actor.obligations { - state.commitments.insert( - entry_key( - &subject, - &format!("obligation:{}", short_digest(obligation)), - ), - CommitmentComponentState { - kind: CommitmentKind::Obligation, - description: obligation.clone(), - counterparty: None, - status: "active".into(), - version, - }, - ); - } - for (index, memory) in actor.memories.iter().enumerate() { - state.memories.insert( - entry_key( - &subject, - &format!("memory:{index}:{}", short_digest(memory)), - ), - MemoryComponentState { - event_id: None, - summary: memory.clone(), - version, - }, - ); - } - } - for institution in campaign.institutions.values() { - let subject = institution_subject(&institution.id); - admit( - &mut state, - subject.clone(), - BTreeSet::from([ - WorldComponentKind::Identity, - WorldComponentKind::Posture, - WorldComponentKind::Commitment, - ]), - version, - ); - state.postures.insert(subject, institution.posture.clone()); - } - for gestalt in campaign.gestalts.values() { - let subject = population_subject(&gestalt.id); - admit( - &mut state, - subject.clone(), - BTreeSet::from([ - WorldComponentKind::Identity, - WorldComponentKind::Occupancy, - WorldComponentKind::Capability, - WorldComponentKind::Knowledge, - WorldComponentKind::Pressure, - ]), - version, - ); - state - .occupancy - .insert(subject.clone(), place_subject(&gestalt.home_location_id)); - state.identities.insert( - format!("identity:canonical:{}", gestalt.id), - IdentityHandleState { - schema: "ghostlight.identity_handle.v1".into(), - id: format!("identity:canonical:{}", gestalt.id), - subject: subject.clone(), - value: gestalt.name.clone(), - active: true, - known_by: BTreeSet::from([subject.clone()]), - restricted_to: BTreeSet::new(), - source_revision: version, - }, - ); - for capability in &gestalt.shared_capabilities { - state.capabilities.insert( - entry_key(&subject, capability), - CapabilityComponentState { - description: capability.clone(), - suspended: false, - version, - }, - ); - } - for (index, goal) in gestalt.goals.iter().enumerate() { - state.commitments.insert( - entry_key(&subject, &format!("goal:{index}:{}", short_digest(goal))), - CommitmentComponentState { - kind: CommitmentKind::Goal, - description: goal.clone(), - counterparty: None, - status: "active".into(), - version, - }, - ); - } - for statement in &gestalt.shared_knowledge { - let proposition = ensure_proposition(&mut state, campaign, statement, version); - state.knowledge.insert( - KnowledgeKey { - knower: subject.clone(), - proposition, - }, - KnowledgeComponentState { - status: "known".into(), - source: None, - channel: None, - concealed_from: BTreeSet::new(), - version, - }, - ); - } - for pressure_label in &gestalt.pressures { - let pressure = gestalt_pressure_subject(&gestalt.id, pressure_label); - admit( - &mut state, - pressure.clone(), - BTreeSet::from([WorldComponentKind::Pressure]), - version, - ); - state.pressures.insert( - pressure.clone(), - PressureComponentState { - pressure, - owner: subject.clone(), - label: pressure_label.clone(), - progress: 0, - threshold: 4, - resolved: false, - version, - }, - ); - } - } - for member in campaign.gestalt_members.values() { - let subject = actor_subject(&crate::domain::gestalt_member_subject_id(&member.id)); - let gestalt = campaign - .gestalts - .get(&member.gestalt_id) - .ok_or_else(|| anyhow!("gestalt member baseline vanished"))?; - admit( - &mut state, - subject.clone(), - BTreeSet::from([ - WorldComponentKind::Identity, - WorldComponentKind::Occupancy, - WorldComponentKind::Capability, - WorldComponentKind::Condition, - WorldComponentKind::Knowledge, - WorldComponentKind::Memory, - WorldComponentKind::Relationship, - WorldComponentKind::Commitment, - WorldComponentKind::PopulationMembership, - ]), - version, - ); - state.occupancy.insert( - subject.clone(), - place_subject( - member - .last_location_id - .as_deref() - .unwrap_or(&gestalt.home_location_id), - ), - ); - let identity_id = format!("identity:canonical:{}", subject.id); - state - .identities - .entry(identity_id.clone()) - .or_insert_with(|| IdentityHandleState { - schema: "ghostlight.identity_handle.v1".into(), - id: identity_id, - subject: subject.clone(), - value: member.name.clone(), - active: true, - known_by: BTreeSet::from([subject.clone()]), - restricted_to: BTreeSet::new(), - source_revision: version, - }); - state.memberships.insert( - MembershipKey { - actor: subject.clone(), - population: population_subject(&member.gestalt_id), - }, - PopulationMembershipState { - active: true, - version, - }, - ); - for capability in &member.capability_additions { - state.capabilities.insert( - entry_key(&subject, capability), - CapabilityComponentState { - description: capability.clone(), - suspended: false, - version, - }, - ); - } - for condition in &member.conditions { - state.conditions.insert( - entry_key(&subject, condition), - ConditionComponentState { - description: condition.clone(), - severity: None, - version, - }, - ); - } - for obligation in &member.obligations { - state.commitments.insert( - entry_key( - &subject, - &format!("obligation:{}", short_digest(obligation)), - ), - CommitmentComponentState { - kind: CommitmentKind::Obligation, - description: obligation.clone(), - counterparty: None, - status: "active".into(), - version, - }, - ); - } - for (index, goal) in member.goals.iter().enumerate() { - state.commitments.insert( - entry_key(&subject, &format!("goal:{index}:{}", short_digest(goal))), - CommitmentComponentState { - kind: CommitmentKind::Goal, - description: goal.clone(), - counterparty: None, - status: "active".into(), - version, - }, - ); - } - for (index, memory) in member.memories.iter().enumerate() { - state.memories.insert( - entry_key( - &subject, - &format!("memory:{index}:{}", short_digest(memory)), - ), - MemoryComponentState { - event_id: None, - summary: memory.clone(), - version, - }, - ); - } - for statement in crate::resolution::effective_member_knowledge(campaign, &member.id)? { - let proposition = ensure_proposition(&mut state, campaign, &statement, version); - state.knowledge.insert( - KnowledgeKey { - knower: subject.clone(), - proposition, - }, - KnowledgeComponentState { - status: "known".into(), - source: None, - channel: None, - concealed_from: BTreeSet::new(), - version, - }, - ); - } - for (target_id, description) in &member.relationships { - let Some(target) = resolve_subject(campaign, target_id) else { - continue; - }; - let id = relationship_id(&subject.id, target_id); - state.relationships.insert( - id, - RelationshipComponentState { - source: subject.clone(), - target, - description: description.clone(), - strength: None, - version, - }, - ); - } - } - for relation in campaign - .agency_relations - .values() - .filter(|relation| relation.active) - { - let Some(source) = resolve_subject(campaign, &relation.from_subject_id) else { - continue; - }; - let Some(target) = resolve_subject(campaign, &relation.to_subject_id) else { - continue; - }; - state.relationships.insert( - relation.id.clone(), - RelationshipComponentState { - source, - target, - description: format!("{:?}", relation.kind).to_lowercase(), - strength: Some(i64::from(relation.strength)), - version, - }, - ); - } - for fact in campaign.facts.values() { - let proposition = proposition_subject(&fact.id); - admit( - &mut state, - proposition.clone(), - BTreeSet::from([ - WorldComponentKind::Knowledge, - WorldComponentKind::PropositionContent, - ]), - version, - ); - state.propositions.insert( - proposition.clone(), - PropositionComponentState { - proposition, - statement: fact.statement.clone(), - scope: fact.scope.clone(), - evidence_receipt_ids: fact.evidence_receipt_ids.iter().cloned().collect(), - discoverable_at_places: fact - .discoverable_at_location_ids - .iter() - .map(|id| place_subject(id)) - .collect(), - version, - }, - ); - } - for clock in campaign.clocks.values() { - let pressure = pressure_subject(&clock.id); - admit( - &mut state, - pressure.clone(), - BTreeSet::from([WorldComponentKind::Pressure]), - version, - ); - state.pressures.insert( - pressure.clone(), - PressureComponentState { - pressure, - owner: campaign_subject(campaign), - label: clock.label.clone(), - progress: i64::from(clock.progress), - threshold: i64::from(clock.threshold), - resolved: clock.progress >= clock.threshold, - version, - }, - ); - } - for location in campaign.locations.values() { - for (route_id, route) in &location.routes { - let edge_id = component_route_id(&location.id, route_id); - state.topology.insert( - edge_id.clone(), - TopologyComponentState { - id: edge_id, - from_place: place_subject(&location.id), - to_place: place_subject(&route.destination_id), - distance: route.distance.clone(), - travel_minutes: i64::from(route.travel_minutes), - open: true, - version, - }, - ); - } - } - for actor in campaign.actors.values() { - let knower = actor_subject(&actor.id); - for statement in &actor.knowledge { - let proposition = if let Some(fact) = campaign - .facts - .values() - .find(|fact| fact.statement == *statement) - { - proposition_subject(&fact.id) - } else { - ensure_proposition(&mut state, campaign, statement, version) - }; - state.knowledge.insert( - KnowledgeKey { - knower: knower.clone(), - proposition, - }, - KnowledgeComponentState { - status: "known".into(), - source: None, - channel: None, - concealed_from: BTreeSet::new(), - version, - }, - ); - } - for (target_id, description) in &actor.relationships { - let Some(target) = resolve_subject(campaign, target_id) else { - continue; - }; - let id = relationship_id(&actor.id, target_id); - state.relationships.insert( - id, - RelationshipComponentState { - source: knower.clone(), - target, - description: description.clone(), - strength: None, - version, - }, - ); - } - } - for (owner, label) in legacy_resources(campaign) { - let resource = resource_subject(campaign, &owner, &label); - admit( - &mut state, - resource.clone(), - BTreeSet::from([ - WorldComponentKind::ResourceState, - WorldComponentKind::Custody, - ]), - version, - ); - state.custody.insert(resource.clone(), owner); - state.resources.insert( - resource.clone(), - ResourceComponentState { - schema: "ghostlight.resource_component.v1".into(), - resource, - resource_kind: "legacy_named_resource".into(), - label, - quantity: 1, - integrity: 100, - qualities: BTreeSet::new(), - version, - }, - ); - } - if validate { - validate_component_world(&state)?; - } - Ok(state) -} - -fn project_mutated_components( - campaign: &mut Campaign, - next: &ComponentWorldState, - batch: &WorldMutationBatch, -) -> Result<()> { - let mut resources_changed = false; - let mut resource_owners_changed = BTreeSet::new(); - let mut touched_members = BTreeSet::new(); - let mut touched_gestalts = BTreeSet::new(); - for permitted in &batch.mutations { - match &permitted.mutation { - WorldMutation::TransferCustody { - from_custodian, - to_custodian, - .. - } => { - resources_changed = true; - resource_owners_changed.insert(from_custodian.clone()); - resource_owners_changed.insert(to_custodian.clone()); - } - WorldMutation::MutateResource { custodian, .. } => { - resources_changed = true; - resource_owners_changed.extend(custodian.iter().cloned()); - } - WorldMutation::Relocate { subject, .. } if subject.kind == SubjectKind::Actor => { - let destination = next - .occupancy - .get(subject) - .ok_or_else(|| anyhow!("accepted relocation lost occupancy"))?; - if let Some(member_id) = subject.id.strip_prefix("member:") { - let member = campaign - .gestalt_members - .get_mut(member_id) - .ok_or_else(|| anyhow!("accepted relocation member vanished"))?; - member.last_location_id = Some(destination.id.clone()); - touched_members.insert(member_id.to_string()); - if let Some(actor) = campaign.actors.get_mut(&subject.id) { - actor.location_id = destination.id.clone(); - } - } else { - campaign - .actors - .get_mut(&subject.id) - .ok_or_else(|| anyhow!("accepted relocation actor vanished"))? - .location_id = destination.id.clone(); - } - } - WorldMutation::Relocate { subject, .. } if subject.kind == SubjectKind::Population => { - let destination = next - .occupancy - .get(subject) - .ok_or_else(|| anyhow!("accepted population relocation lost occupancy"))?; - let gestalt = campaign - .gestalts - .get_mut(&subject.id) - .ok_or_else(|| anyhow!("accepted relocation population vanished"))?; - gestalt.home_location_id = destination.id.clone(); - touched_gestalts.insert(subject.id.clone()); - let profile = campaign - .agency_profiles - .get_mut(&subject.id) - .ok_or_else(|| anyhow!("accepted relocation agency profile vanished"))?; - profile.location_ids = BTreeSet::from([destination.id.clone()]); - profile.profile_version = profile.profile_version.saturating_add(1); - } - WorldMutation::ChangeIdentity { - subject, - operation: IdentityMutationOperation::Adopt, - handle_id, - .. - } if subject.kind == SubjectKind::Actor => { - let identity = next - .identities - .get(handle_id) - .filter(|identity| identity.active && identity.subject == *subject) - .ok_or_else(|| anyhow!("accepted identity adoption vanished"))?; - if let Some(member_id) = subject.id.strip_prefix("member:") { - campaign - .gestalt_members - .get_mut(member_id) - .ok_or_else(|| anyhow!("accepted identity member vanished"))? - .name = identity.value.clone(); - touched_members.insert(member_id.to_string()); - } - campaign - .actors - .get_mut(&subject.id) - .ok_or_else(|| anyhow!("accepted identity actor vanished"))? - .name = identity.value.clone(); - } - WorldMutation::ChangeIdentity { - subject, - operation: IdentityMutationOperation::Disclose, - .. - } if subject.kind == SubjectKind::Actor => { - // Exact audience knowledge lives in the component world. The - // aggregate actor/member projection has no rival audience map. - } - WorldMutation::ChangeCondition { - subject, - condition_id, - .. - } if subject.kind == SubjectKind::Actor => { - let actor = campaign - .actors - .get_mut(&subject.id) - .ok_or_else(|| anyhow!("accepted condition actor vanished"))?; - let key = entry_key(subject, condition_id); - if next.conditions.contains_key(&key) { - actor.conditions.insert(condition_id.clone()); - } else { - actor.conditions.remove(condition_id); - } - } - WorldMutation::AdmitEntity { - subject, - initial_profile: Some(AdmittedEntityProfile::Proposition { .. }), - .. - } if subject.kind == SubjectKind::Proposition => { - let proposition = next - .propositions - .get(subject) - .ok_or_else(|| anyhow!("accepted proposition admission vanished"))?; - if campaign.facts.contains_key(&subject.id) { - return Err(anyhow!( - "accepted proposition replaced an existing world fact" - )); - } - campaign.facts.insert( - subject.id.clone(), - WorldFact { - id: subject.id.clone(), - statement: proposition.statement.clone(), - scope: proposition.scope.clone(), - evidence_receipt_ids: proposition - .evidence_receipt_ids - .iter() - .cloned() - .collect(), - discoverable_at_location_ids: proposition - .discoverable_at_places - .iter() - .map(|place| place.id.clone()) - .collect(), - }, - ); - } - WorldMutation::ChangeKnowledge { - proposition, - knower, - recipients, - .. - } => { - let statement = campaign - .facts - .get(&proposition.id) - .map(|fact| fact.statement.clone()) - .ok_or_else(|| anyhow!("accepted proposition lost its world fact"))?; - for subject in knower.iter().chain(recipients) { - if !next.knowledge.contains_key(&KnowledgeKey { - knower: subject.clone(), - proposition: proposition.clone(), - }) { - continue; - } - match subject.kind { - SubjectKind::Actor => { - if let Some(member_id) = subject.id.strip_prefix("member:") { - let member = campaign - .gestalt_members - .get_mut(member_id) - .ok_or_else(|| anyhow!("accepted knowledge member vanished"))?; - member.knowledge_removals.remove(&statement); - member.knowledge_additions.insert(statement.clone()); - touched_members.insert(member_id.to_string()); - if let Some(actor) = campaign.actors.get_mut(&subject.id) { - actor.knowledge.insert(statement.clone()); - } - } else { - campaign - .actors - .get_mut(&subject.id) - .ok_or_else(|| anyhow!("accepted knowledge actor vanished"))? - .knowledge - .insert(statement.clone()); - } - } - SubjectKind::Population => { - let gestalt = campaign - .gestalts - .get_mut(&subject.id) - .ok_or_else(|| anyhow!("accepted knowledge gestalt vanished"))?; - gestalt.shared_knowledge.insert(statement.clone()); - let materialized_actor_ids = campaign - .gestalt_members - .values() - .filter(|member| { - member.gestalt_id == subject.id - && !member.knowledge_removals.contains(&statement) - }) - .filter_map(|member| member.materialized_actor_id.clone()) - .collect::>(); - for actor_id in materialized_actor_ids { - campaign - .actors - .get_mut(&actor_id) - .ok_or_else(|| { - anyhow!( - "accepted shared knowledge materialized actor vanished" - ) - })? - .knowledge - .insert(statement.clone()); - } - touched_gestalts.insert(subject.id.clone()); - } - _ => { - return Err(anyhow!( - "aggregate knowledge projection lacks subject kind {:?}", - subject.kind - )); - } - } - } - } - WorldMutation::ChangeRelationship { - relationship_id, .. - } if campaign.agency_relations.contains_key(relationship_id) => { - let value = next - .relationships - .get(relationship_id) - .ok_or_else(|| anyhow!("accepted agency relation vanished"))?; - let strength = value - .strength - .ok_or_else(|| anyhow!("accepted agency relation lost strength"))?; - campaign - .agency_relations - .get_mut(relationship_id) - .expect("existence checked") - .strength = u8::try_from(strength) - .map_err(|_| anyhow!("accepted agency strength exceeded storage"))?; - } - WorldMutation::ChangeRelationship { - source, - target, - relationship_id, - .. - } if source.kind == SubjectKind::Actor => { - if let Some(member_id) = source.id.strip_prefix("member:") { - let member = campaign - .gestalt_members - .get_mut(member_id) - .ok_or_else(|| anyhow!("accepted relationship member vanished"))?; - if let Some(value) = next.relationships.get(relationship_id) { - member - .relationships - .insert(target.id.clone(), value.description.clone()); - if let Some(actor) = campaign.actors.get_mut(&source.id) { - actor - .relationships - .insert(target.id.clone(), value.description.clone()); - } - } else { - member.relationships.remove(&target.id); - if let Some(actor) = campaign.actors.get_mut(&source.id) { - actor.relationships.remove(&target.id); - } - } - touched_members.insert(member_id.to_string()); - } else { - let actor = campaign - .actors - .get_mut(&source.id) - .ok_or_else(|| anyhow!("accepted relationship actor vanished"))?; - if let Some(value) = next.relationships.get(relationship_id) { - actor - .relationships - .insert(target.id.clone(), value.description.clone()); - } else { - actor.relationships.remove(&target.id); - } - } - } - WorldMutation::ChangeMemory { - subject, memory_id, .. - } if subject.kind == SubjectKind::Actor => { - let key = entry_key(subject, memory_id); - let value = next - .memories - .get(&key) - .ok_or_else(|| anyhow!("accepted memory vanished"))?; - if let Some(member_id) = subject.id.strip_prefix("member:") { - let member = campaign - .gestalt_members - .get_mut(member_id) - .ok_or_else(|| anyhow!("accepted memory member vanished"))?; - if !member.memories.contains(&value.summary) { - member.memories.push(value.summary.clone()); - touched_members.insert(member_id.to_string()); - } - if let Some(actor) = campaign.actors.get_mut(&subject.id) { - if actor.memories.len() < 64 && !actor.memories.contains(&value.summary) { - actor.memories.push(value.summary.clone()); - } - } - } else { - let actor = campaign - .actors - .get_mut(&subject.id) - .ok_or_else(|| anyhow!("accepted memory actor vanished"))?; - if actor.memories.len() < 64 && !actor.memories.contains(&value.summary) { - actor.memories.push(value.summary.clone()); - } - } - } - WorldMutation::ChangeCommitment { - subject, - kind, - commitment_id, - .. - } if subject.kind == SubjectKind::Actor => { - let key = entry_key(subject, commitment_id); - let value = next.commitments.get(&key); - if let Some(member_id) = subject.id.strip_prefix("member:") { - let member = campaign - .gestalt_members - .get_mut(member_id) - .ok_or_else(|| anyhow!("accepted commitment member vanished"))?; - match (kind, value) { - (CommitmentKind::Goal, Some(value)) => { - if !member.goals.contains(&value.description) { - member.goals.push(value.description.clone()); - } - } - (CommitmentKind::Obligation, Some(value)) => { - member.obligations.insert(value.description.clone()); - } - (CommitmentKind::Goal, None) => member - .goals - .retain(|goal| !campaign_commitment_matches(goal, commitment_id)), - (CommitmentKind::Obligation, None) => { - member.obligations.retain(|obligation| { - !campaign_commitment_matches(obligation, commitment_id) - }); - } - } - touched_members.insert(member_id.to_string()); - if let Some(actor) = campaign.actors.get_mut(&subject.id) { - match (kind, value) { - (CommitmentKind::Goal, Some(value)) => { - if !actor.goals.contains(&value.description) { - actor.goals.push(value.description.clone()); - } - } - (CommitmentKind::Obligation, Some(value)) => { - actor.obligations.insert(value.description.clone()); - } - (CommitmentKind::Goal, None) => actor - .goals - .retain(|goal| !campaign_commitment_matches(goal, commitment_id)), - (CommitmentKind::Obligation, None) => { - actor.obligations.retain(|obligation| { - !campaign_commitment_matches(obligation, commitment_id) - }); - } - } - } - } else { - let actor = campaign - .actors - .get_mut(&subject.id) - .ok_or_else(|| anyhow!("accepted commitment actor vanished"))?; - match (kind, value) { - (CommitmentKind::Goal, Some(value)) => { - if !actor.goals.contains(&value.description) { - actor.goals.push(value.description.clone()); - } - } - (CommitmentKind::Obligation, Some(value)) => { - actor.obligations.insert(value.description.clone()); - } - (CommitmentKind::Goal, None) => actor - .goals - .retain(|goal| !campaign_commitment_matches(goal, commitment_id)), - (CommitmentKind::Obligation, None) => { - actor.obligations.retain(|obligation| { - !campaign_commitment_matches(obligation, commitment_id) - }); - } - } - } - } - WorldMutation::ChangePressure { pressure, .. } - if pressure.kind == SubjectKind::Pressure => - { - let value = next - .pressures - .get(pressure) - .ok_or_else(|| anyhow!("accepted pressure vanished"))?; - if let Some(clock) = campaign.clocks.get_mut(&pressure.id) { - clock.progress = u8::try_from(value.progress) - .map_err(|_| anyhow!("accepted clock exceeded aggregate storage"))?; - } else if value.owner.kind == SubjectKind::Population { - let gestalt = campaign - .gestalts - .get_mut(&value.owner.id) - .ok_or_else(|| anyhow!("accepted pressure gestalt vanished"))?; - gestalt.pressures.retain(|label| label != &value.label); - if !value.resolved { - gestalt.pressures.push(value.label.clone()); - } - touched_gestalts.insert(value.owner.id.clone()); - } else { - return Err(anyhow!("aggregate pressure owner is unsupported")); - } - } - WorldMutation::ChangePosture { subject, .. } - if subject.kind == SubjectKind::Institution => - { - let posture = next - .postures - .get(subject) - .ok_or_else(|| anyhow!("accepted posture vanished"))?; - campaign - .institutions - .get_mut(&subject.id) - .ok_or_else(|| anyhow!("accepted institution vanished"))? - .posture = posture.clone(); - } - WorldMutation::ChangePopulationMembership { - actor, - operation: PopulationMembershipOperation::Transfer, - source_population: Some(source), - destination_population: Some(destination), - } if actor.kind == SubjectKind::Actor - && source.kind == SubjectKind::Population - && destination.kind == SubjectKind::Population => - { - let member_id = actor.id.strip_prefix("member:").ok_or_else(|| { - anyhow!("aggregate membership transfer requires a named member") - })?; - let source_key = MembershipKey { - actor: actor.clone(), - population: source.clone(), - }; - let destination_key = MembershipKey { - actor: actor.clone(), - population: destination.clone(), - }; - if next - .memberships - .get(&source_key) - .is_some_and(|membership| membership.active) - || !next - .memberships - .get(&destination_key) - .is_some_and(|membership| membership.active) - { - return Err(anyhow!( - "accepted population transfer has incoherent final membership" - )); - } - project_member_population_transfer( - campaign, - member_id, - &source.id, - &destination.id, - )?; - touched_members.insert(member_id.to_string()); - touched_gestalts.insert(source.id.clone()); - touched_gestalts.insert(destination.id.clone()); - } - WorldMutation::AdvanceWorldTime { .. } => { - campaign.world_time = next.world_time; - } - _ => { - return Err(anyhow!( - "aggregate projection does not yet support mutation {:?}", - permitted.mutation.operation() - )); - } - } - } - if resources_changed { - project_all_resources(campaign, next)?; - for owner in resource_owners_changed { - match owner.kind { - SubjectKind::Actor if owner.id.starts_with("member:") => { - touched_members.insert(owner.id.trim_start_matches("member:").to_string()); - } - SubjectKind::Population => { - touched_gestalts.insert(owner.id); - } - _ => {} - } - } - } - for member_id in touched_members { - if let Some(member) = campaign.gestalt_members.get_mut(&member_id) { - member.version = member.version.saturating_add(1); - } - } - for gestalt_id in touched_gestalts { - if let Some(gestalt) = campaign.gestalts.get_mut(&gestalt_id) { - gestalt.version = gestalt.version.saturating_add(1); - } - } - Ok(()) -} - -fn campaign_commitment_matches(value: &str, commitment_id: &str) -> bool { - commitment_id.ends_with(&short_digest(value)) -} - -fn project_member_population_transfer( - campaign: &mut Campaign, - member_id: &str, - source_population_id: &str, - destination_population_id: &str, -) -> Result<()> { - let member = campaign - .gestalt_members - .get(member_id) - .filter(|member| member.gestalt_id == source_population_id) - .ok_or_else(|| anyhow!("accepted member transfer has stale aggregate source"))?; - if let Some(actor_id) = &member.materialized_actor_id { - if actor_id != &crate::domain::gestalt_member_subject_id(member_id) - || !campaign.actors.contains_key(actor_id) - { - return Err(anyhow!( - "accepted materialized member transfer lost its stable actor" - )); - } - campaign - .gestalt_members - .get_mut(member_id) - .expect("member source was resolved") - .gestalt_id = destination_population_id.into(); - return Ok(()); - } - let source = campaign - .gestalts - .get(source_population_id) - .ok_or_else(|| anyhow!("accepted member transfer source vanished"))?; - let destination = campaign - .gestalts - .get(destination_population_id) - .ok_or_else(|| anyhow!("accepted member transfer destination vanished"))? - .clone(); - - // The member's exact effective state survives a change of aggregate - // baseline. Only its delta representation is recomputed. - let effective_capabilities = source - .shared_capabilities - .union(&member.capability_additions) - .filter(|value| !member.capability_removals.contains(*value)) - .cloned() - .collect::>(); - let effective_knowledge = source - .shared_knowledge - .union(&member.knowledge_additions) - .filter(|value| !member.knowledge_removals.contains(*value)) - .cloned() - .collect::>(); - let effective_goals = if member.goals.is_empty() { - source.goals.clone() - } else { - member.goals.clone() - }; - - let member = campaign - .gestalt_members - .get_mut(member_id) - .expect("member source was resolved"); - member.capability_additions = effective_capabilities - .difference(&destination.shared_capabilities) - .cloned() - .collect(); - member.capability_removals = destination - .shared_capabilities - .difference(&effective_capabilities) - .cloned() - .collect(); - member.knowledge_additions = effective_knowledge - .difference(&destination.shared_knowledge) - .cloned() - .collect(); - member.knowledge_removals = destination - .shared_knowledge - .difference(&effective_knowledge) - .cloned() - .collect(); - member.goals = if effective_goals == destination.goals { - Vec::new() - } else { - effective_goals - }; - member.gestalt_id = destination_population_id.into(); - Ok(()) -} - -fn project_all_resources(campaign: &mut Campaign, next: &ComponentWorldState) -> Result<()> { - for actor in campaign.actors.values_mut() { - actor.equipment.clear(); - } - for member in campaign.gestalt_members.values_mut() { - member.equipment.clear(); - } - for institution in campaign.institutions.values_mut() { - institution.resources.clear(); - } - for gestalt in campaign.gestalts.values_mut() { - gestalt.resources.clear(); - } - for location in campaign.locations.values_mut() { - location.persistent_features.clear(); - } - for (resource, value) in &next.resources { - let owner = next - .custody - .get(resource) - .ok_or_else(|| anyhow!("accepted resource lost custody"))?; - match owner.kind { - SubjectKind::Actor => { - if let Some(member_id) = owner.id.strip_prefix("member:") { - campaign - .gestalt_members - .get_mut(member_id) - .ok_or_else(|| anyhow!("accepted resource member vanished"))? - .equipment - .insert(value.label.clone()); - if let Some(actor) = campaign.actors.get_mut(&owner.id) { - actor.equipment.insert(value.label.clone()); - } - } else { - campaign - .actors - .get_mut(&owner.id) - .ok_or_else(|| anyhow!("accepted resource actor vanished"))? - .equipment - .insert(value.label.clone()); - } - } - SubjectKind::Institution => campaign - .institutions - .get_mut(&owner.id) - .ok_or_else(|| anyhow!("accepted resource institution vanished"))? - .resources - .push(value.label.clone()), - SubjectKind::Population => { - campaign - .gestalts - .get_mut(&owner.id) - .ok_or_else(|| anyhow!("accepted resource gestalt vanished"))? - .resources - .insert(value.label.clone()); - } - SubjectKind::Place => campaign - .locations - .get_mut(&owner.id) - .ok_or_else(|| anyhow!("accepted resource location vanished"))? - .persistent_features - .push(value.label.clone()), - _ => return Err(anyhow!("aggregate resource custodian is unsupported")), - } - } - for institution in campaign.institutions.values_mut() { - institution.resources.sort(); - institution.resources.dedup(); - } - for location in campaign.locations.values_mut() { - location.persistent_features.sort(); - location.persistent_features.dedup(); - } - Ok(()) -} - -fn admit( - state: &mut ComponentWorldState, - subject: SubjectRef, - admitted_components: BTreeSet, - version: u64, -) { - if let Some(existing) = state.subjects.get_mut(&subject) { - existing.admitted_components.extend(admitted_components); - existing.version = existing.version.max(version); - } else { - state.subjects.insert( - subject.clone(), - TypedSubject { - schema: "ghostlight.typed_subject.v1".into(), - subject, - lifecycle: LifecycleStatus::Active, - admitted_components, - version, - }, - ); - } -} - -fn resolve_subject(campaign: &Campaign, id: &str) -> Option { - if campaign.actors.contains_key(id) { - Some(actor_subject(id)) - } else if id - .strip_prefix("member:") - .is_some_and(|member_id| campaign.gestalt_members.contains_key(member_id)) - { - Some(actor_subject(id)) - } else if campaign.institutions.contains_key(id) { - Some(institution_subject(id)) - } else if campaign.gestalts.contains_key(id) { - Some(population_subject(id)) - } else if campaign.locations.contains_key(id) { - Some(place_subject(id)) - } else if campaign.facts.contains_key(id) { - Some(proposition_subject(id)) - } else { - None - } -} - -fn expansion_agency_subject( - campaign: &Campaign, - expansion: &crate::domain::RegionExpansion, - id: &str, -) -> Result { - if expansion - .institutions - .iter() - .any(|institution| institution.id == id) - { - Ok(institution_subject(id)) - } else if expansion - .populations - .iter() - .any(|population| population.id == id) - { - Ok(population_subject(id)) - } else if let Some(subject) = resolve_subject(campaign, id) - && matches!( - subject.kind, - SubjectKind::Institution | SubjectKind::Population - ) - { - Ok(subject) - } else { - Err(anyhow!( - "local relation references a subject outside the expansion" - )) - } -} - -fn agency_relation_kind_label(kind: &crate::domain::AgencyRelationKind) -> &'static str { - use crate::domain::AgencyRelationKind::*; - match kind { - Containment => "containment", - Command => "command", - Membership => "membership", - Alliance => "alliance", - Rivalry => "rivalry", - Trade => "trade", - Migration => "migration", - Communication => "communication", - Coercion => "coercion", - SharedLocation => "shared_location", - } -} - -fn ensure_member<'a>( - campaign: &'a Campaign, - member_id: &str, -) -> Result<&'a crate::domain::GestaltMemberDelta> { - campaign - .gestalt_members - .get(member_id) - .ok_or_else(|| anyhow!("strategic member is unknown")) -} - -fn entry_key(subject: &SubjectRef, entry_id: &str) -> SubjectEntryKey { - SubjectEntryKey { - subject: subject.clone(), - entry_id: entry_id.into(), - } -} - -fn ensure_proposition( - state: &mut ComponentWorldState, - campaign: &Campaign, - statement: &str, - version: u64, -) -> SubjectRef { - let proposition = campaign - .facts - .values() - .find(|fact| fact.statement == statement) - .map(|fact| proposition_subject(&fact.id)) - .unwrap_or_else(|| { - proposition_subject(&format!("legacy-knowledge:{}", short_digest(statement))) - }); - admit( - state, - proposition.clone(), - BTreeSet::from([ - WorldComponentKind::Knowledge, - WorldComponentKind::PropositionContent, - ]), - version, - ); - state - .propositions - .entry(proposition.clone()) - .or_insert_with(|| PropositionComponentState { - proposition: proposition.clone(), - statement: statement.into(), - scope: crate::domain::FactScope::ProvisionalLocal, - evidence_receipt_ids: BTreeSet::new(), - discoverable_at_places: BTreeSet::new(), - version, - }); - proposition -} - -fn legacy_resources(campaign: &Campaign) -> BTreeSet<(SubjectRef, String)> { - let mut resources = BTreeSet::new(); - for actor in campaign.actors.values() { - for resource in &actor.equipment { - resources.insert((actor_subject(&actor.id), resource.clone())); - } - } - for institution in campaign.institutions.values() { - for resource in &institution.resources { - resources.insert((institution_subject(&institution.id), resource.clone())); - } - } - for gestalt in campaign.gestalts.values() { - for resource in &gestalt.resources { - resources.insert((population_subject(&gestalt.id), resource.clone())); - } - } - for member in campaign.gestalt_members.values() { - let owner = actor_subject(&crate::domain::gestalt_member_subject_id(&member.id)); - for resource in &member.equipment { - resources.insert((owner.clone(), resource.clone())); - } - } - for location in campaign.locations.values() { - for resource in &location.persistent_features { - resources.insert((place_subject(&location.id), resource.clone())); - } - } - resources -} - -fn relationship_id(source: &str, target: &str) -> String { - format!( - "relationship:{}", - short_digest(&(source.to_owned() + "\0" + target)) - ) -} - -fn campaign_subject(campaign: &Campaign) -> SubjectRef { - SubjectRef { - kind: SubjectKind::Campaign, - id: campaign.id.to_string(), - } -} - -fn actor_subject(id: &str) -> SubjectRef { - SubjectRef { - kind: SubjectKind::Actor, - id: id.into(), - } -} - -fn population_subject(id: &str) -> SubjectRef { - SubjectRef { - kind: SubjectKind::Population, - id: id.into(), - } -} - -fn institution_subject(id: &str) -> SubjectRef { - SubjectRef { - kind: SubjectKind::Institution, - id: id.into(), - } -} - -fn place_subject(id: &str) -> SubjectRef { - SubjectRef { - kind: SubjectKind::Place, - id: id.into(), - } -} - -fn pressure_subject(id: &str) -> SubjectRef { - SubjectRef { - kind: SubjectKind::Pressure, - id: id.into(), - } -} - -fn gestalt_pressure_subject(gestalt_id: &str, label: &str) -> SubjectRef { - pressure_subject(&format!( - "gestalt-pressure:{}:{}", - gestalt_id, - short_digest(label) - )) -} - -fn resource_subject(campaign: &Campaign, custodian: &SubjectRef, label: &str) -> SubjectRef { - SubjectRef { - kind: SubjectKind::Resource, - id: format!( - "resource:{}", - short_digest(&format!( - "{}\0{:?}\0{}\0{}", - campaign.id, custodian.kind, custodian.id, label - )) - ), - } -} - -fn proposition_subject(id: &str) -> SubjectRef { - SubjectRef { - kind: SubjectKind::Proposition, - id: id.into(), - } -} - -fn short_digest(value: &str) -> String { - format!("{:x}", Sha256::digest(value.as_bytes())) - .chars() - .take(16) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::domain::{ - ActorState, BranchOrigin, CommitmentDelta, ConditionDelta, GestaltMemberDelta, - InstitutionState, Location, ResolutionPolicy, Route, StrategicCellEffect, - StrategicOutcomeBand, WorldClock, WorldFact, - }; - use chrono::Duration; - use uuid::Uuid; - - fn campaign() -> Campaign { - let id = Uuid::new_v4(); - Campaign { - schema: "ghostlight.campaign.v1".into(), - id, - name: "Transition fixture".into(), - revision: 4, - branch_origin: BranchOrigin { - canon_cutoff: "fixture".into(), - evidence_receipt_ids: vec![], - }, - world_time: Utc::now(), - tick_hours: 6, - player_actor_id: "player".into(), - locations: BTreeMap::from([ - ( - "room".into(), - Location { - id: "room".into(), - name: "Room".into(), - container_id: None, - routes: BTreeMap::from([( - "door".into(), - Route { - destination_id: "hall".into(), - distance: "nearby".into(), - travel_minutes: 2, - }, - )]), - persistent_features: vec![], - }, - ), - ( - "hall".into(), - Location { - id: "hall".into(), - name: "Hall".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - ), - ]), - actors: BTreeMap::from([ - ( - "player".into(), - ActorState { - id: "player".into(), - name: "Player".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ), - ( - "witness".into(), - ActorState { - id: "witness".into(), - name: "Witness".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ), - ]), - institutions: BTreeMap::from([( - "watch".into(), - InstitutionState { - id: "watch".into(), - name: "Watch".into(), - resources: vec![], - goals: vec![], - posture: "guarded".into(), - }, - )]), - clocks: BTreeMap::from([( - "alarm".into(), - WorldClock { - id: "alarm".into(), - label: "Alarm".into(), - progress: 2, - threshold: 6, - consequence: "The doors lock.".into(), - consequence_scope: Default::default(), - }, - )]), - facts: BTreeMap::from([( - "fact:route".into(), - WorldFact { - id: "fact:route".into(), - statement: "The west stair bypasses the checkpoint.".into(), - scope: crate::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["room".into()]), - }, - )]), - civic_systems: BTreeMap::new(), - transcript: vec![], - last_player_activity: Utc::now(), - pending_ticks: 0, - away_ticks_processed: 0, - events: vec![], - news: vec![], - canon_candidates: BTreeMap::new(), - gestalts: BTreeMap::new(), - gestalt_members: BTreeMap::new(), - pending_world_proposals: vec![], - agency_profiles: BTreeMap::new(), - agency_relations: BTreeMap::new(), - gestalt_lineages: BTreeMap::new(), - resolution_policy: ResolutionPolicy::default(), - resolution_pins: BTreeMap::new(), - resolution_cover: None, - nemesis_attention_history: Vec::new(), - strategic_tick_count: 0, - } - } - - #[test] - fn component_snapshot_projects_effective_member_knowledge() { - let mut campaign = campaign(); - let statement = campaign.facts["fact:route"].statement.clone(); - campaign.gestalts.insert( - "refugees".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "refugees".into(), - name: "Refugees".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::from([statement.clone()]), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - campaign.gestalt_members.insert( - "messenger".into(), - GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "messenger".into(), - gestalt_id: "refugees".into(), - version: 0, - name: "Messenger".into(), - capability_additions: BTreeSet::new(), - capability_removals: BTreeSet::new(), - knowledge_additions: BTreeSet::new(), - knowledge_removals: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - obligations: BTreeSet::new(), - memories: vec![], - last_location_id: Some("room".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }, - ); - - let snapshot = component_snapshot(&campaign).unwrap(); - let key = KnowledgeKey { - knower: actor_subject("member:messenger"), - proposition: proposition_subject("fact:route"), - }; - assert_eq!(snapshot.knowledge[&key].status, "known"); - - campaign - .gestalt_members - .get_mut("messenger") - .unwrap() - .knowledge_removals - .insert(statement); - assert!( - !component_snapshot(&campaign) - .unwrap() - .knowledge - .contains_key(&key) - ); - } - - #[test] - fn fission_rebinds_civic_residency_and_political_relations_atomically() { - let mut campaign = campaign(); - let public_fact = campaign.facts["fact:route"].statement.clone(); - campaign.gestalts.insert( - "residents".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "residents".into(), - name: "Residents".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::from([public_fact.clone()]), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - crate::resolution::ensure_agency_profiles(&mut campaign); - campaign.agency_relations.insert( - "relation:residents-watch".into(), - AgencyRelation { - schema: AgencyRelation::SCHEMA.into(), - id: "relation:residents-watch".into(), - from_subject_id: "residents".into(), - to_subject_id: "watch".into(), - kind: crate::domain::AgencyRelationKind::Membership, - strength: 60, - active: true, - evidence_receipt_ids: vec!["evidence:civic".into()], - }, - ); - campaign.civic_systems.insert( - "room".into(), - crate::domain::CivicSystemManifest { - schema: "ghostlight.civic_system_manifest.v1".into(), - version: 0, - jurisdiction_location_id: "room".into(), - governing_institution_ids: BTreeSet::from(["watch".into()]), - resident_population_ids: BTreeSet::from(["residents".into()]), - public_authority_fact_ids: BTreeSet::from(["fact:route".into()]), - public_selection_fact_ids: BTreeSet::from(["fact:route".into()]), - public_resource_fact_ids: BTreeSet::from(["fact:route".into()]), - public_redress_fact_ids: BTreeSet::from(["fact:route".into()]), - political_relation_ids: BTreeSet::from(["relation:residents-watch".into()]), - semantic_verification_receipt_id: "semantic:civic".into(), - }, - ); - let child = |id: &str, name: &str| GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: id.into(), - name: name.into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::from([public_fact.clone()]), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }; - let preview = GestaltFissionPreview { - schema: "ghostlight.gestalt_fission_preview.v1".into(), - campaign_id: campaign.id, - expected_world_revision: campaign.revision, - parent_gestalt_id: "residents".into(), - partition_axis: crate::domain::AgencyAxis::Ideology, - children: vec![ - child("resident-majority", "Resident majority"), - child("resident-dissenters", "Resident dissenters"), - ], - child_partition_values: BTreeMap::from([ - ("resident-majority".into(), "majority".into()), - ("resident-dissenters".into(), "other/unknown".into()), - ]), - residual_child_id: "resident-dissenters".into(), - member_child_assignments: BTreeMap::new(), - resource_child_assignments: BTreeMap::new(), - evidence_receipt_ids: vec![], - gaps: vec![], - canon_candidates: vec![], - requires_approval: true, - }; - - let transition = - lower_fission(&campaign, &preview, Utc::now() + Duration::minutes(5)).unwrap(); - assert!( - transition - .batch - .mutations - .iter() - .any(|mutation| matches!(mutation.mutation, WorldMutation::SetCivicSystem { .. })) - ); - apply_lowered_fission(&mut campaign, &preview, &transition, Utc::now()).unwrap(); - - let civic = &campaign.civic_systems["room"]; - assert_eq!( - civic.resident_population_ids, - BTreeSet::from(["resident-majority".into(), "resident-dissenters".into()]) - ); - assert_eq!( - civic.political_relation_ids, - BTreeSet::from([ - "relation:residents-watch:fission:resident-majority".into(), - "relation:residents-watch:fission:resident-dissenters".into(), - ]) - ); - assert_eq!(civic.version, 1); - assert!( - civic - .semantic_verification_receipt_id - .starts_with("fission-preview:") - ); - assert!( - !campaign - .agency_relations - .contains_key("relation:residents-watch") - ); - for relation_id in &civic.political_relation_ids { - assert!(campaign.agency_relations.contains_key(relation_id)); - } - let snapshot = component_snapshot(&campaign).unwrap(); - crate::transition::validate_component_world(&snapshot).unwrap(); - - campaign.revision += 1; - campaign.civic_systems.insert( - "room".into(), - crate::domain::CivicSystemManifest { - schema: "ghostlight.civic_system_manifest.v1".into(), - version: 0, - jurisdiction_location_id: "room".into(), - governing_institution_ids: BTreeSet::from(["watch".into()]), - resident_population_ids: BTreeSet::from(["residents".into()]), - public_authority_fact_ids: BTreeSet::from(["fact:route".into()]), - public_selection_fact_ids: BTreeSet::from(["fact:route".into()]), - public_resource_fact_ids: BTreeSet::from(["fact:route".into()]), - public_redress_fact_ids: BTreeSet::from(["fact:route".into()]), - political_relation_ids: BTreeSet::from(["relation:residents-watch".into()]), - semantic_verification_receipt_id: "semantic:stale".into(), - }, - ); - assert!(fission_civic_reconciliation_required(&campaign)); - let reconciliation = - lower_fission_civic_reconciliation(&campaign, Utc::now() + Duration::minutes(5)) - .unwrap() - .unwrap(); - let repaired_system = reconciliation - .batch - .mutations - .iter() - .find_map(|mutation| match &mutation.mutation { - WorldMutation::SetCivicSystem { system, .. } => Some(system), - _ => None, - }) - .unwrap(); - assert_eq!( - repaired_system.political_relation_ids, - BTreeSet::from([ - "relation:residents-watch:fission:resident-majority".into(), - "relation:residents-watch:fission:resident-dissenters".into(), - ]) - ); - let stale_snapshot = component_snapshot_for_reconciliation(&campaign).unwrap(); - for relation_id in &repaired_system.political_relation_ids { - assert!(stale_snapshot.relationships.contains_key(relation_id)); - } - apply_lowered_fission_civic_reconciliation(&mut campaign, &reconciliation, Utc::now()) - .unwrap(); - assert!(!fission_civic_reconciliation_required(&campaign)); - assert_eq!( - campaign.civic_systems["room"].resident_population_ids, - BTreeSet::from(["resident-majority".into(), "resident-dissenters".into()]) - ); - assert_eq!( - campaign.civic_systems["room"].political_relation_ids, - BTreeSet::from([ - "relation:residents-watch:fission:resident-majority".into(), - "relation:residents-watch:fission:resident-dissenters".into(), - ]) - ); - assert!( - campaign.civic_systems["room"] - .semantic_verification_receipt_id - .starts_with("fission-civic-reconciliation:") - ); - crate::transition::validate_component_world(&component_snapshot(&campaign).unwrap()) - .unwrap(); - } - - #[test] - fn elaborated_fission_commits_qualified_child_semantics_in_one_typed_batch() { - let mut campaign = campaign(); - let inherited_knowledge = campaign.facts["fact:route"].statement.clone(); - let parent = GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "residents".into(), - name: "Residents".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::from(["keep the public stair open".into()]), - shared_knowledge: BTreeSet::from([inherited_knowledge.clone()]), - resources: BTreeSet::new(), - goals: vec!["keep the hall inhabited".into()], - pressures: vec!["the night watch is thin".into()], - }; - campaign.gestalts.insert(parent.id.clone(), parent.clone()); - crate::resolution::ensure_agency_profiles(&mut campaign); - - let situated_knowledge = - "The eastern lintel rings when the sealed cistern changes pressure.".to_owned(); - let mut specific = parent.clone(); - specific.id = "lintel-keepers".into(); - specific.name = "Lintel Keepers".into(); - specific - .shared_capabilities - .insert("sound the lintel before opening the cistern".into()); - specific.shared_knowledge.insert(situated_knowledge.clone()); - specific - .goals - .push("win custody of the eastern cistern key".into()); - specific - .pressures - .push("the cistern key is promised to two rival crews".into()); - let mut residual = parent.clone(); - residual.id = "residents-unresolved".into(); - residual.name = "Unresolved Residents".into(); - let preview = GestaltFissionPreview { - schema: "ghostlight.gestalt_fission_preview.v1".into(), - campaign_id: campaign.id, - expected_world_revision: campaign.revision, - parent_gestalt_id: parent.id.clone(), - partition_axis: crate::domain::AgencyAxis::Ideology, - children: vec![specific.clone(), residual], - child_partition_values: BTreeMap::from([ - (specific.id.clone(), "lintel custody".into()), - ("residents-unresolved".into(), "other/unknown".into()), - ]), - residual_child_id: "residents-unresolved".into(), - member_child_assignments: BTreeMap::new(), - resource_child_assignments: BTreeMap::new(), - evidence_receipt_ids: vec![], - gaps: vec![], - canon_candidates: vec![], - requires_approval: true, - }; - - assert!(lower_fission(&campaign, &preview, Utc::now() + Duration::minutes(5)).is_err()); - let transition = - lower_elaborated_fission(&campaign, &preview, Utc::now() + Duration::minutes(5)) - .unwrap(); - assert!(transition.batch.mutations.iter().any(|mutation| matches!( - mutation.mutation, - WorldMutation::AdmitEntity { - initial_profile: Some(AdmittedEntityProfile::Proposition { .. }), - .. - } - ))); - assert!( - transition.batch.mutations.iter().any(|mutation| matches!( - mutation.mutation, - WorldMutation::ChangeCapability { .. } - )) - ); - assert!( - transition - .batch - .mutations - .iter() - .any(|mutation| matches!(mutation.mutation, WorldMutation::ChangeKnowledge { .. })) - ); - assert!( - transition.batch.mutations.iter().any(|mutation| matches!( - mutation.mutation, - WorldMutation::ChangeCommitment { .. } - )) - ); - assert!( - transition - .batch - .mutations - .iter() - .any(|mutation| matches!(mutation.mutation, WorldMutation::ChangePressure { .. })) - ); - - apply_lowered_elaborated_fission(&mut campaign, &preview, &transition, Utc::now()).unwrap(); - assert_eq!(campaign.gestalts[&specific.id], specific); - assert!(campaign.facts.values().any(|fact| { - fact.statement == situated_knowledge - && fact.scope == crate::domain::FactScope::ProvisionalLocal - })); - crate::transition::validate_component_world(&component_snapshot(&campaign).unwrap()) - .unwrap(); - } - - #[test] - fn shared_learning_updates_the_materialized_member_projection() { - let mut campaign = campaign(); - let statement = campaign.facts["fact:route"].statement.clone(); - campaign.gestalts.insert( - "refugees".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "refugees".into(), - name: "Refugees".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - campaign.gestalt_members.insert( - "messenger".into(), - GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "messenger".into(), - gestalt_id: "refugees".into(), - version: 0, - name: "Messenger".into(), - capability_additions: BTreeSet::new(), - capability_removals: BTreeSet::new(), - knowledge_additions: BTreeSet::new(), - knowledge_removals: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - obligations: BTreeSet::new(), - memories: vec![], - last_location_id: Some("room".into()), - materialized_actor_id: Some("member:messenger".into()), - last_relevant_revision: 4, - relevance_lease_until_revision: 9, - }, - ); - campaign.actors.insert( - "member:messenger".into(), - ActorState { - id: "member:messenger".into(), - name: "Messenger".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - let plan = StrategicTickPlan { - activity_outcomes: vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: "sha256:shared-learning".into(), - source_subject_id: "refugees".into(), - band: StrategicOutcomeBand::Success, - summary: "The refugees learn the west-stair route.".into(), - supporting_state_references: vec!["fact:fact:route".into()], - effect: StrategicOutcomeEffect::KnowledgeLearned { - owner_subject_id: "refugees".into(), - fact_id: "fact:route".into(), - }, - }], - ..StrategicTickPlan::default() - }; - let transition = lower_strategic_wave( - &campaign, - &plan, - "strategic:test", - Utc::now() + Duration::minutes(5), - ) - .unwrap() - .unwrap(); - - apply_lowered_transition(&mut campaign, &transition, Utc::now()).unwrap(); - - assert!( - campaign.gestalts["refugees"] - .shared_knowledge - .contains(&statement) - ); - assert!( - campaign.actors["member:messenger"] - .knowledge - .contains(&statement) - ); - assert!( - component_snapshot(&campaign) - .unwrap() - .knowledge - .contains_key(&KnowledgeKey { - knower: actor_subject("member:messenger"), - proposition: proposition_subject("fact:route"), - }) - ); - } - - #[test] - fn reaction_identity_adoption_updates_materialized_member_and_delta() { - let mut campaign = campaign(); - campaign.gestalts.insert( - "refugees".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "refugees".into(), - name: "Refugees".into(), - version: 0, - home_location_id: "room".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: 0, - name: "Refugee Convoy Oxygen Patient".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("room".into()), - materialized_actor_id: Some("member:oxygen_patient".into()), - last_relevant_revision: 4, - relevance_lease_until_revision: 6, - }, - ); - campaign.actors.insert( - "member:oxygen_patient".into(), - ActorState { - id: "member:oxygen_patient".into(), - name: "Refugee Convoy Oxygen Patient".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - let reactions = vec![ActorReaction { - actor_id: "member:oxygen_patient".into(), - speech: Some("My name is Taren.".into()), - deliberate_silence: false, - private_delta: crate::domain::ActorStateDelta { - identity_adoption: Some("Taren".into()), - ..Default::default() - }, - action_proposals: vec![], - }]; - let transition = lower_reaction_wave( - &campaign, - "Witnessed: the player asks your name.", - &reactions, - "reaction:test", - Utc::now() + Duration::minutes(5), - ) - .unwrap(); - assert!(transition.batch.mutations.iter().any(|permitted| matches!( - &permitted.mutation, - WorldMutation::ChangeIdentity { - operation: IdentityMutationOperation::Adopt, - handle_value: Some(value), - .. - } if value == "Taren" - ))); - assert!(transition.batch.mutations.iter().any(|permitted| matches!( - &permitted.mutation, - WorldMutation::ChangeIdentity { - operation: IdentityMutationOperation::Disclose, - handle_value: Some(value), - audience, - .. - } if value == "Taren" - && audience == &vec![actor_subject("player"), actor_subject("witness")] - ))); - apply_lowered_transition(&mut campaign, &transition, Utc::now()).unwrap(); - assert_eq!(campaign.actors["member:oxygen_patient"].name, "Taren"); - assert_eq!(campaign.gestalt_members["oxygen_patient"].name, "Taren"); - } - - #[test] - fn foreground_legacy_record_can_only_change_state_through_exact_mutations() { - let mut campaign = campaign(); - let effect = WorldEffectDelta { - actor_conditions: BTreeMap::from([( - "player".into(), - ConditionDelta { - add: BTreeSet::from(["winded".into()]), - remove: BTreeSet::new(), - }, - )]), - actor_commitments: BTreeMap::from([( - "witness".into(), - CommitmentDelta { - obligations_add: BTreeSet::from([ - "permit a supervised inventory inspection".into() - ]), - ..CommitmentDelta::default() - }, - )]), - actor_knowledge_additions: BTreeMap::from([( - "player".into(), - BTreeSet::from(["The west stair bypasses the checkpoint.".into()]), - )]), - actor_observations: BTreeMap::new(), - actor_relationship_updates: BTreeMap::from([( - "player".into(), - BTreeMap::from([("witness".into(), "owes a candid answer".into())]), - )]), - actor_moves: BTreeMap::from([("player".into(), "hall".into())]), - clock_advances: BTreeMap::from([("alarm".into(), 1)]), - clock_reductions: BTreeMap::new(), - institution_postures: BTreeMap::from([("watch".into(), "searching".into())]), - }; - let transition = lower_foreground_effect( - &campaign, - "player", - &effect, - OutcomeBand::Success, - MutationProcedure::ForegroundAttempt, - "The player reaches the hall but raises the alarm.", - "assessment:test", - None, - None, - Utc::now() + Duration::minutes(5), - ) - .unwrap(); - assert_eq!(transition.batch.mutations.len(), 7); - let receipt = apply_lowered_transition(&mut campaign, &transition, Utc::now()).unwrap(); - assert_eq!(receipt.previous_world_revision, 4); - assert_eq!(receipt.world_revision, 5); - assert_eq!(campaign.actors["player"].location_id, "hall"); - assert!(campaign.actors["player"].conditions.contains("winded")); - assert!( - campaign.actors["player"] - .knowledge - .contains("The west stair bypasses the checkpoint.") - ); - assert_eq!( - campaign.actors["player"].relationships["witness"], - "owes a candid answer" - ); - assert_eq!(campaign.clocks["alarm"].progress, 3); - assert_eq!(campaign.institutions["watch"].posture, "searching"); - assert!( - campaign.actors["witness"] - .obligations - .contains("permit a supervised inventory inspection") - ); - - let retirement = WorldEffectDelta { - actor_commitments: BTreeMap::from([( - "witness".into(), - CommitmentDelta { - obligations_retire: BTreeSet::from([ - "permit a supervised inventory inspection".into(), - ]), - ..CommitmentDelta::default() - }, - )]), - ..WorldEffectDelta::default() - }; - let transition = lower_foreground_effect( - &campaign, - "player", - &retirement, - OutcomeBand::Success, - MutationProcedure::ForegroundAttempt, - "The witness retires the supervised-inspection obligation.", - "assessment:retire", - None, - None, - Utc::now() + Duration::minutes(5), - ) - .unwrap(); - apply_lowered_transition(&mut campaign, &transition, Utc::now()).unwrap(); - assert!( - !campaign.actors["witness"] - .obligations - .contains("permit a supervised inventory inspection") - ); - } - - #[test] - fn foreground_observation_admits_one_branch_proposition_then_acquires_it() { - let mut campaign = campaign(); - let statement = "The regulator's left coupling carries the highest current thermal stress."; - let effect = WorldEffectDelta { - actor_observations: BTreeMap::from([( - "player".into(), - BTreeSet::from([statement.into()]), - )]), - ..WorldEffectDelta::default() - }; - let transition = lower_foreground_effect( - &campaign, - "player", - &effect, - OutcomeBand::Success, - MutationProcedure::ForegroundAttempt, - statement, - "assessment:bounded-observation", - Some("sha256:means".into()), - Some("sha256:intended-effect".into()), - Utc::now() + Duration::minutes(5), - ) - .unwrap(); - - assert_eq!(transition.batch.mutations.len(), 2); - let proposition_id = match &transition.batch.mutations[0].mutation { - WorldMutation::AdmitEntity { subject, .. } => subject.id.clone(), - mutation => panic!("expected proposition admission, got {mutation:?}"), - }; - assert!(matches!( - transition.batch.mutations[1].mutation, - WorldMutation::ChangeKnowledge { .. } - )); - - apply_lowered_transition(&mut campaign, &transition, Utc::now()).unwrap(); - let fact = &campaign.facts[&proposition_id]; - assert_eq!(fact.statement, statement); - assert_eq!(fact.scope, FactScope::BranchLocal); - assert_eq!( - fact.discoverable_at_location_ids, - BTreeSet::from(["room".into()]) - ); - assert!(campaign.actors["player"].knowledge.contains(statement)); - } - - #[test] - fn identical_resource_labels_remain_isolated_by_exact_custody() { - let mut campaign = campaign(); - campaign - .actors - .get_mut("player") - .unwrap() - .equipment - .insert("communication device".into()); - campaign - .actors - .get_mut("witness") - .unwrap() - .equipment - .insert("communication device".into()); - - let snapshot = component_snapshot(&campaign).unwrap(); - let matching_resources = snapshot - .resources - .iter() - .filter(|(_, resource)| resource.label == "communication device") - .map(|(resource, _)| { - ( - resource.clone(), - snapshot.custody.get(resource).cloned().unwrap(), - ) - }) - .collect::>(); - assert_eq!(matching_resources.len(), 2); - assert_eq!( - matching_resources - .iter() - .map(|(_, owner)| owner.clone()) - .collect::>(), - BTreeSet::from([actor_subject("player"), actor_subject("witness")]) - ); - - let plan = StrategicTickPlan { - activity_outcomes: vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: format!("sha256:{}", "a".repeat(64)), - source_subject_id: "witness".into(), - band: StrategicOutcomeBand::Success, - summary: "Witness expends a communication device.".into(), - supporting_state_references: vec!["resource:communication device".into()], - effect: StrategicOutcomeEffect::ResourceConsumed { - owner_subject_id: "witness".into(), - resource: "communication device".into(), - }, - }], - ..StrategicTickPlan::default() - }; - let transition = lower_strategic_wave( - &campaign, - &plan, - "strategic:test", - Utc::now() + Duration::minutes(5), - ) - .unwrap() - .unwrap(); - apply_lowered_transition(&mut campaign, &transition, Utc::now()).unwrap(); - - assert!( - campaign.actors["player"] - .equipment - .contains("communication device") - ); - assert!( - !campaign.actors["witness"] - .equipment - .contains("communication device") - ); - } - - #[test] - fn strategic_creation_at_a_place_persists_as_a_place_feature() { - let mut campaign = campaign(); - campaign - .locations - .get_mut("room") - .unwrap() - .persistent_features - .push("fixed wall lamp".into()); - let plan = StrategicTickPlan { - activity_outcomes: vec![StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: format!("sha256:{}", "b".repeat(64)), - source_subject_id: "witness".into(), - band: StrategicOutcomeBand::Success, - summary: "At Room, Witness establishes a public warning marker.".into(), - supporting_state_references: vec!["capability:field repairs".into()], - effect: StrategicOutcomeEffect::ResourceCreated { - owner_subject_id: "room".into(), - resource: "public warning marker".into(), - }, - }], - ..StrategicTickPlan::default() - }; - - let transition = lower_strategic_wave( - &campaign, - &plan, - "strategic:place-resource", - Utc::now() + Duration::minutes(5), - ) - .unwrap() - .unwrap(); - apply_lowered_transition(&mut campaign, &transition, Utc::now()).unwrap(); - - assert_eq!( - campaign.locations["room"].persistent_features, - ["fixed wall lamp", "public warning marker"] - ); - assert!( - !campaign.actors["witness"] - .equipment - .contains("public warning marker") - ); - let snapshot = component_snapshot(&campaign).unwrap(); - let marker = snapshot - .resources - .iter() - .find(|(_, resource)| resource.label == "public warning marker") - .map(|(subject, _)| subject) - .unwrap(); - assert_eq!(snapshot.custody.get(marker), Some(&place_subject("room"))); - } - - #[test] - fn strategic_choices_survive_as_exact_actor_and_member_memory() { - let mut campaign = campaign(); - campaign.gestalts.insert( - "refugees".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "refugees".into(), - name: "Refugees".into(), - version: 0, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - campaign.gestalt_members.insert( - "scout".into(), - GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "scout".into(), - gestalt_id: "refugees".into(), - version: 0, - name: "Refugee Scout".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("room".into()), - materialized_actor_id: None, - last_relevant_revision: campaign.revision, - relevance_lease_until_revision: campaign.revision, - }, - ); - let actor_intent = "inspect the hall before anyone else enters"; - let actor_effect = "identify immediate hazards without claiming the hall is safe"; - let member_intent = "check the room's marked exits"; - let member_effect = "report only routes personally inspected"; - let selected_actions = vec![ - crate::domain::CellActionProposal { - subject_id: "witness".into(), - intent: actor_intent.into(), - intended_effect: actor_effect.into(), - priority: 60, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::ActorMove { - actor_id: "witness".into(), - destination_id: "hall".into(), - }], - }, - crate::domain::CellActionProposal { - subject_id: "member:scout".into(), - intent: member_intent.into(), - intended_effect: member_effect.into(), - priority: 50, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::MemberActivity { - member_id: "scout".into(), - activity: crate::domain::StrategicActivityKind::Investigate, - target_subject_ids: vec![], - location_ids: vec!["room".into()], - }], - }, - ]; - let plan = - crate::resolution::project_selected_actions(&campaign, selected_actions).unwrap(); - let transition = lower_strategic_wave( - &campaign, - &plan, - "strategic:choice-memory", - Utc::now() + Duration::minutes(5), - ) - .unwrap() - .unwrap(); - - apply_lowered_transition(&mut campaign, &transition, Utc::now()).unwrap(); - - assert_eq!(campaign.actors["witness"].location_id, "hall"); - assert!(campaign.actors["witness"].memories.contains(&format!( - "I chose to {actor_intent}. I intended to {actor_effect}." - ))); - assert!( - campaign.gestalt_members["scout"] - .memories - .contains(&format!( - "I chose to {member_intent}. I intended to {member_effect}." - )) - ); - } - - #[test] - fn stale_or_tampered_lowering_cannot_partially_project() { - let mut campaign = campaign(); - let before = campaign.clone(); - let effect = WorldEffectDelta { - actor_moves: BTreeMap::from([("player".into(), "hall".into())]), - ..WorldEffectDelta::default() - }; - let mut transition = lower_foreground_effect( - &campaign, - "player", - &effect, - OutcomeBand::Success, - MutationProcedure::ForegroundAttempt, - "The player reaches the hall.", - "assessment:test", - None, - None, - Utc::now() + Duration::minutes(5), - ) - .unwrap(); - let WorldMutation::Relocate { to_place, .. } = &mut transition.batch.mutations[0].mutation - else { - unreachable!(); - }; - to_place.id = "forbidden".into(); - transition.batch.digest = mutation_batch_digest(&transition.batch).unwrap(); - assert!(apply_lowered_transition(&mut campaign, &transition, Utc::now()).is_err()); - assert_eq!(campaign, before); - } -} diff --git a/crates/ghostlight-dungeon/src/lib.rs b/crates/ghostlight-dungeon/src/lib.rs deleted file mode 100644 index 765e328..0000000 --- a/crates/ghostlight-dungeon/src/lib.rs +++ /dev/null @@ -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}; diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index e437e71..2c66dc3 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -1,7784 +1,12 @@ -use anyhow::Context; -use axum::{ - Json, Router, - body::Body, - extract::{Path, Query, State}, - http::{HeaderMap, HeaderValue, StatusCode, header}, - response::{ - IntoResponse, Response, - sse::{Event as SseEvent, KeepAlive, Sse}, - }, - routing::{get, post}, -}; -use chrono::{DateTime, Utc}; -#[cfg(test)] -use ghostlight_dungeon::domain::WorldCompilePreview; -use ghostlight_dungeon::{ - assessor::ActionAssessor, - compiler::{ - DestinationCompilationFailure, GestaltFissionRequest, OpeningRequest, OpeningSuggestion, - WorldCompiler, - }, - domain::{ - ActionIntent, Campaign, DestinationCompilationPreview, GestaltFissionPreview, - RejectedProposalReceipt, WorldCommand, - }, - gestalt::{GestaltPresencePlanner, required_addressed_promotions}, - idunn_health::{GHOSTLIGHT_IDUNN_HEALTH_CONTRACT, IdunnHealthPublisher}, - kernel::{CommandResult, KernelError}, - mesh::{ - COMMAND_BOUNDARY as EVE_COMMAND_BOUNDARY, COMMAND_RESULT_SCHEMA as EVE_RESULT_SCHEMA, - CampaignMeshSnapshot, MeshPublisher, MeshRuntimeIdentity, PROVIDER_ID as EVE_PROVIDER_ID, - SURFACE_ID as EVE_SURFACE_ID, SessionZeroMeshSnapshot, - }, - model::{MODEL_CAPABLE, MODEL_FAST, ModelPort, ModelRuntimeStatus}, - model_runtime::ModelRuntimeSelection, - persistence::CampaignStore, - persona::PersonaProjectionEngine, - registry::{CampaignRegistry, CampaignRuntime}, - session_zero::{ - BoundaryLevel, EntitlementPort, FixtureEntitlementPort, SessionZeroCommand, - SessionZeroDecisionResolution, SessionZeroDirector, SessionZeroRegistry, SessionZeroState, - publication_from_session, session_zero_surface, - }, - surface::{ - campaign_interface_version, player_surface_for_actor, rebase_campaign_surface_revision, - }, - turn::{SnapshotPermit, appraise_present, resolve_speech_addresses}, - vault::{VoidBotMcpVault, bundled_vault_manifests, canonical_vault_id}, -}; -use serde::Deserialize; -use serde::Serialize; -use std::{ - collections::{BTreeMap, BTreeSet}, - convert::Infallible, - net::SocketAddr, - path::PathBuf, - sync::Arc, - sync::atomic::{AtomicUsize, Ordering}, -}; -use tokio::sync::{Mutex, Notify, OwnedRwLockReadGuard, RwLock}; -use tower_http::services::ServeDir; -use tracing_subscriber::EnvFilter; - mod app_session; +mod eve; mod heimdall; -mod native_cultmesh; -use app_session::{AppSessionOwner, CommandReservation, NewSession, RefreshedSession, secret_hash}; -use heimdall::HeimdallClient; -use native_cultmesh::NativeAuthCompletionReceipt; - -#[derive(Clone)] -struct AppState { - registry: CampaignRegistry, - exports_root: PathBuf, - session_zeros: SessionZeroRegistry, - session_zero_director: Option>, - entitlements: Arc, - auth: Arc>, - heimdall: Arc, - model_status: ModelRuntimeStatus, - compiler: Option>, - assessor: Option>, - model: Option>, - expansion_previews: Arc>>>, - fission_previews: Arc>>, - live_turns: Arc, - live_turn_started: Arc, - live_turn_finished: Arc, - live_commit_gate: Arc>, - mesh: MeshPublisher, -} - -fn compiler_for_vault( - compiler: &Option>, - vault_id: &str, -) -> anyhow::Result> { - let compiler = compiler - .as_ref() - .ok_or_else(|| anyhow::anyhow!("world compiler is unavailable"))?; - Ok(Arc::new(compiler.for_vault(vault_id)?)) -} - -struct LiveTurnGuard { - counter: Arc, - finished: Arc, - mesh: MeshPublisher, - _commit_read: Option>, -} -impl LiveTurnGuard { - async fn enter(state: &AppState) -> Self { - let mut guard = Self { - counter: state.live_turns.clone(), - finished: state.live_turn_finished.clone(), - mesh: state.mesh.clone(), - _commit_read: None, - }; - let pressure = guard.counter.fetch_add(1, Ordering::SeqCst) + 1; - if let Err(error) = guard.mesh.publish_live_turn_pressure(pressure) { - tracing::warn!(%error, pressure, "live-turn pressure CultMesh publication failed"); - } - state.live_turn_started.notify_waiters(); - guard._commit_read = Some(state.live_commit_gate.clone().read_owned().await); - guard - } -} -impl Drop for LiveTurnGuard { - fn drop(&mut self) { - // Release the read side before announcing an idle boundary. Background - // aftermath may use that boundary only when no foreground commit guard - // remains held. - self._commit_read.take(); - let previous = self.counter.fetch_sub(1, Ordering::SeqCst); - let pressure = previous.saturating_sub(1); - if let Err(error) = self.mesh.publish_live_turn_pressure(pressure) { - tracing::warn!(%error, pressure, "live-turn pressure CultMesh release failed"); - } - if pressure == 0 { - self.finished.notify_waiters(); - } - } -} - -#[derive(Clone)] -struct OwnedPreview { - session_hash: String, - value: T, - model_receipts: Vec, -} - -#[derive(Clone)] -struct OwnedFissionPreview { - session_hash: String, - value: GestaltFissionPreview, - evidence_receipts: Vec, - model_receipts: Vec, -} - -#[derive(Deserialize)] -struct BeginSessionZeroRequest { - name: String, - vault_provider: String, - display_name: String, -} - -#[derive(Deserialize)] -struct SessionZeroInviteRequest { - count: u8, -} - -#[derive(Deserialize)] -struct JoinSessionZeroRequest { - display_name: String, -} - -#[derive(Deserialize)] -struct SessionZeroMessageRequest { - expected_revision: u64, - channel_id: String, - text: String, -} - -#[derive(Deserialize)] -struct SessionZeroBoundaryRequest { - expected_revision: u64, - boundary_id: Option, - topic: String, - level: BoundaryLevel, -} - -#[derive(Deserialize)] -struct SessionZeroDecisionRequest { - expected_revision: u64, - decision_id: String, - action: SessionZeroDecisionRequestAction, - counter: Option, -} - -#[derive(Clone, Copy, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum SessionZeroDecisionRequestAction { - Accept, - Decline, - Counter, - RetryCounter, -} - -#[derive(Deserialize)] -struct SessionZeroMemberRequest { - expected_revision: u64, - member_id: String, -} - -#[derive(Deserialize)] -struct SessionZeroRevisionRequest { - expected_revision: u64, -} - -#[derive(Deserialize)] -struct TimeAdvanceRequest { - expected_revision: u64, - minutes: u32, -} - -#[derive(Deserialize)] -struct GroupTravelRequest { - expected_revision: u64, - destination_location_id: String, -} - -#[derive(Deserialize)] -struct CellBudgetRequest { - expected_revision: u64, - expected_resolution_epoch: u64, - active_cell_budget: u8, -} - -#[derive(Clone, Serialize, Deserialize)] -struct LegacyAuthState { - schema: String, - session_hashes: BTreeSet, - #[serde(default)] - session_aliases: BTreeMap, - #[serde(default)] - session_campaigns: BTreeMap, - #[serde(default)] - session_campaign_ids: BTreeMap>, - #[serde(default)] - heimdall_attempts: BTreeMap, -} - -fn empty_legacy_auth_state() -> LegacyAuthState { - LegacyAuthState { - schema: "ghostlight.auth_state.v1".into(), - session_hashes: BTreeSet::new(), - session_aliases: BTreeMap::new(), - session_campaigns: BTreeMap::new(), - session_campaign_ids: BTreeMap::new(), - heimdall_attempts: BTreeMap::new(), - } -} - -#[derive(Clone, Serialize, Deserialize)] -struct GovernanceMigrationReceipt { - schema: String, - campaign_id: uuid::Uuid, - status: String, - account_hashes: Vec, - actor_id: String, - created_at: chrono::DateTime, -} +mod idunn_health; +mod mesh; +mod runtime; +mod world; #[tokio::main] async fn main() -> anyhow::Result<()> { - tracing_subscriber::fmt() - .with_env_filter(EnvFilter::from_default_env()) - .init(); - let runtime_root = std::env::var_os("GHOSTLIGHT_DUNGEON_ROOT") - .map(PathBuf::from) - .unwrap_or_else(default_runtime_root); - migrate_default_campaign(&runtime_root)?; - let registry = CampaignRegistry::new(runtime_root.join("campaigns"))?; - registry.load_existing().await?; - let session_zeros = SessionZeroRegistry::new(runtime_root.join("session-zero"))?; - session_zeros.load_existing().await?; - std::fs::create_dir_all(runtime_root.join("service"))?; - let legacy_auth_path = runtime_root.join("service/auth.cc"); - let legacy_auth_state = if legacy_auth_path.is_file() { - CampaignStore::open(&legacy_auth_path)? - .load::("auth_state.v1", "primary")? - .map(|(_, state)| state) - .unwrap_or_else(empty_legacy_auth_state) - } else { - empty_legacy_auth_state() - }; - migrate_legacy_campaign_memberships(®istry, &legacy_auth_state).await?; - let session_key_path = std::env::var_os("GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE") - .map(PathBuf::from) - .unwrap_or_else(|| runtime_root.join("secrets/session-wrapping.key")); - let mut app_sessions = AppSessionOwner::open( - runtime_root.join("service/app-sessions.cc"), - session_key_path, - )?; - for (account_hash, campaign_id) in &legacy_auth_state.session_campaigns { - app_sessions.migrate_preference(account_hash, *campaign_id)?; - } - let model_selection = ModelRuntimeSelection::from_environment(&runtime_root)?; - let (model_status, compiler, assessor, shared_model) = - if let Some(provider) = model_selection.open()? { - let vault_endpoint = std::env::var("GHOSTLIGHT_VAULT_MCP_URL") - .unwrap_or_else(|_| "http://127.0.0.1:17875/mcp".into()); - ( - model_selection.status("configured"), - Some(Arc::new(WorldCompiler::new( - Arc::new(VoidBotMcpVault::new(vault_endpoint)), - provider.clone(), - MODEL_FAST, - MODEL_CAPABLE, - ))), - Some(Arc::new(ActionAssessor::with_models( - provider.clone(), - MODEL_FAST, - MODEL_CAPABLE, - ))), - Some(provider), - ) - } else { - (model_selection.status("missing-secret"), None, None, None) - }; - let mesh_target = std::env::var("GHOSTLIGHT_ODIN_RUDP") - .ok() - .map(|value| value.parse()) - .transpose()?; - let mesh_identity = MeshRuntimeIdentity { - runtime_id: std::env::var("GHOSTLIGHT_RUNTIME_ID") - .unwrap_or_else(|_| "ghostlight-dungeon-starfire".into()), - service_id: std::env::var("GHOSTLIGHT_SERVICE_ID") - .unwrap_or_else(|_| "ghostlight-dungeon-starfire".into()), - located_service: std::env::var("GHOSTLIGHT_LOCATED_SERVICE") - .unwrap_or_else(|_| "starfire".into()), - }; - let mesh = MeshPublisher::open_with_identity( - runtime_root.join("service/mesh.cc"), - mesh_target, - mesh_identity.clone(), - )?; - let idunn_health = - std::env::var("GHOSTLIGHT_IDUNN_RUDP") - .ok() - .map(|endpoint| -> anyhow::Result { - let identity_store = std::env::var_os("GHOSTLIGHT_IDUNN_HEALTH_IDENTITY") - .map(PathBuf::from) - .ok_or_else(|| anyhow::anyhow!( - "GHOSTLIGHT_IDUNN_HEALTH_IDENTITY is required with GHOSTLIGHT_IDUNN_RUDP" - ))?; - Ok(IdunnHealthPublisher::open( - endpoint.parse()?, - std::env::var("GHOSTLIGHT_IDUNN_DAEMON") - .unwrap_or_else(|_| "yggdrasil-ghostlight".into()), - mesh_identity.runtime_id.clone(), - std::env::var("GHOSTLIGHT_IDUNN_HEALTH_CONTRACT") - .unwrap_or_else(|_| GHOSTLIGHT_IDUNN_HEALTH_CONTRACT.into()), - identity_store, - )?) - }) - .transpose()?; - let session_zero_director = shared_model.as_ref().map(|model| { - Arc::new(SessionZeroDirector::new( - model.clone(), - MODEL_FAST, - MODEL_CAPABLE, - MODEL_FAST, - )) - }); - let state = AppState { - registry, - exports_root: runtime_root.join("exports"), - session_zeros, - session_zero_director, - entitlements: Arc::new(FixtureEntitlementPort), - auth: Arc::new(Mutex::new(app_sessions)), - heimdall: Arc::new(HeimdallClient::from_env()?), - model_status, - compiler, - assessor, - model: shared_model, - expansion_previews: Arc::new(Mutex::new(BTreeMap::new())), - fission_previews: Arc::new(Mutex::new(BTreeMap::new())), - live_turns: Arc::new(AtomicUsize::new(0)), - live_turn_started: Arc::new(Notify::new()), - live_turn_finished: Arc::new(Notify::new()), - live_commit_gate: Arc::new(RwLock::new(())), - mesh, - }; - schedule_recovered_npc_initiatives(&state).await?; - native_cultmesh::start(state.clone())?; - refresh_mesh(&state).await?; - tokio::spawn(scheduler_loop(state.clone())); - tokio::spawn(app_session_refresh_loop(state.clone())); - let release_web_root = std::env::current_exe()? - .parent() - .map(|parent| parent.join("web")); - let web_root = release_web_root - .filter(|path| path.join("index.html").is_file()) - .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../web/dist")); - let app = app_router(state, web_root); - let address: SocketAddr = std::env::var("GHOSTLIGHT_DUNGEON_BIND") - .unwrap_or_else(|_| "0.0.0.0:8831".into()) - .parse()?; - let listener = tokio::net::TcpListener::bind(address).await?; - tracing::info!(%address, "GhostlightDungeon listening"); - if let Some(mut publisher) = idunn_health { - tokio::task::spawn_blocking(move || { - loop { - if let Err(error) = publisher.publish("active", "world-kernel-serving") { - tracing::warn!(%error, "signed Idunn health publication failed"); - } - std::thread::sleep(std::time::Duration::from_secs(10)); - } - }); - } - axum::serve( - listener, - app.into_make_service_with_connect_info::(), - ) - .await?; - Ok(()) -} - -fn default_runtime_root() -> PathBuf { - #[cfg(windows)] - { - PathBuf::from(r"F:\GameCult\GhostlightDungeon") - } - #[cfg(not(windows))] - { - PathBuf::from("/var/lib/gamecult/ghostlight-dungeon") - } -} - -fn app_router(state: AppState, web_root: PathBuf) -> Router { - Router::new() - .route("/health", get(health)) - .route("/api/eve/provider", get(eve_provider)) - .route("/api/eve/surfaces/{surface_id}", get(eve_surface)) - .route("/api/eve/commands", post(eve_command)) - .route("/api/eve/resources/{token}", get(eve_resource)) - .route("/api/eve/events", get(revision_events)) - .fallback_service(ServeDir::new(web_root).append_index_html_on_directories(true)) - .with_state(state) -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct EveCommandInvocation { - schema: String, - #[serde(rename = "providerId")] - provider_id: String, - #[serde(rename = "surfaceId")] - surface_id: String, - operation: EveOperation, - payload: serde_json::Value, - #[serde(rename = "issuedAt")] - issued_at: String, - #[serde(rename = "clientId")] - client_id: String, - #[serde(rename = "commandBoundary")] - command_boundary: String, - #[serde(rename = "receiptSchema")] - receipt_schema: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(deny_unknown_fields, rename_all = "camelCase")] -struct EveOperation { - operation_id: String, - schema_id: Option, - idempotency_key: Option, - #[serde(default)] - route_hint: EveRouteHint, -} - -#[derive(Clone, Debug, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -struct EveRouteHint { - source_version: Option, - transport: Option, -} - -async fn eve_provider(State(state): State) -> Response { - let updated = chrono::Utc::now().to_rfc3339(); - Json(state.mesh.provider_advertisement(&updated)).into_response() -} - -async fn eve_surface( - Path(surface_id): Path, - Query(query): Query, - headers: HeaderMap, - State(state): State, -) -> Response { - if surface_id != EVE_SURFACE_ID { - return StatusCode::NOT_FOUND.into_response(); - } - if authenticated_session(&headers, &state).await.is_none() { - return Json(anonymous_eve_surface()).into_response(); - } - surface(headers, State(state), query.invite.as_deref()).await -} - -#[derive(Default, Deserialize)] -struct EveSurfaceQuery { - invite: Option, -} - -fn anonymous_eve_surface() -> serde_json::Value { - serde_json::json!({ - "type":"surface-state", - "schema":"gamecult.eve.surface.v1", - "providerId":EVE_PROVIDER_ID, - "providerKind":"narrative.simulation", - "title":"Ghostlight Dungeon", - "version":0, - "updatedAtUtc":Utc::now().to_rfc3339(), - "surface":{"id":EVE_SURFACE_ID,"root":{ - "id":"ghostlight.root","kind":"surface","props":{},"children":[ - {"id":"ghostlight.access","kind":"heimdall.access_gate","props":{ - "state":"anonymous","title":"Enter Ghostlight","detail":"Sign in with Discord. Access currently requires the KLTST GameCult role." - },"children":[]}, - {"id":"ghostlight.auth.begin","kind":"control.button","props":{ - "label":"Continue with Discord","command":"heimdall.auth.begin" - },"children":[]} - ] - },"styles":{"tokens":{"colorBackground":"#0c1110","colorPanel":"#17201d","colorText":"#e8e1cf","colorMuted":"#9aa69f","colorAccent":"#d49b58"}}}, - "commands":[{ - "schema":"gamecult.eve.command.v1","command":"heimdall.auth.begin", - "payloadSchema":"heimdall.auth_begin_command.v1", - "transport":"https-json","authority":"Heimdall" - }] - }) -} - -async fn eve_command( - headers: HeaderMap, - State(state): State, - Json(invocation): Json, -) -> Response { - eve_command_for_transport(headers, state, invocation, "https-json").await -} - -async fn eve_command_for_transport( - headers: HeaderMap, - state: AppState, - invocation: EveCommandInvocation, - transport: &str, -) -> Response { - if let Err(error) = validate_eve_invocation(&invocation, transport) { - return Json(eve_result( - &invocation, - "denied", - error.to_string(), - None, - None, - None, - )) - .into_response(); - } - let operation = invocation.operation.operation_id.as_str(); - if operation == "heimdall.auth.begin" { - return match state.heimdall.begin(invocation.operation.idempotency_key.as_deref().unwrap()).await { - Ok(receipt) if receipt.status == "pending" - && !receipt.handle.is_empty() - && receipt.expires_at.parse::>().is_ok_and(|expiry| expiry > Utc::now()) => - { - Json(eve_result( - &invocation, - "accepted", - "Continue authentication with Heimdall.".into(), - None, - Some(serde_json::json!({ - "pluginId":"gamecult.heimdall.access", - "schemaId":"heimdall.auth_navigation_receipt.v1", - "payload":{ - "schema":"heimdall.auth_navigation_receipt.v1", - "handle":receipt.handle, - "navigation":{"url":receipt.navigation.url,"allowedOrigins":receipt.navigation.allowed_origins} - } - })), - None, - )).into_response() - } - Ok(_) => Json(eve_result(&invocation, "denied", "Heimdall returned an invalid authentication attempt.".into(), None, None, None)).into_response(), - Err(error) => Json(eve_result(&invocation, "denied", error.to_string(), None, None, None)).into_response(), - }; - } - if operation == "heimdall.auth.complete" { - return complete_eve_authentication(invocation, state).await; - } - let Some(account_hash) = authenticated_session(&headers, &state).await else { - return Json(eve_result( - &invocation, - "denied", - "Authentication is required.".into(), - None, - None, - None, - )) - .into_response(); - }; - if operation == "app.auth.logout" { - let raw = cookie_value(&headers).unwrap_or_default(); - let logout_session = state - .auth - .lock() - .await - .session_for_logout(raw) - .ok() - .flatten(); - let _ = state.auth.lock().await.revoke_cookie(raw); - if let Some(session) = logout_session { - let idempotency_key = format!( - "logout:{}:{}", - session.heimdall_session_id, session.access_revision - ); - let heimdall = state.heimdall.clone(); - tokio::spawn(async move { - match heimdall - .logout(&session.refresh_claim, &idempotency_key) - .await - { - Ok(receipt) - if receipt.status == "revoked" - && receipt.session_id == session.heimdall_session_id - && receipt.access_revision > session.access_revision - && receipt.revoked_at.parse::>().is_ok() => {} - Ok(_) => tracing::warn!( - session_id = %session.heimdall_session_id, - "Heimdall returned an invalid logout receipt; local session is already revoked" - ), - Err(error) => tracing::warn!( - %error, - session_id = %session.heimdall_session_id, - "Heimdall logout transport failed; local session is already revoked" - ), - } - }); - } - let mut response = Json(eve_result( - &invocation, - "accepted", - "Signed out.".into(), - None, - Some(serde_json::json!({ - "pluginId":"gamecult.heimdall.access", - "schemaId":"heimdall.auth_completion_status.v1", - "payload":{"schema":"heimdall.auth_completion_status.v1","status":"anonymous"} - })), - None, - )) - .into_response(); - response.headers_mut().insert( - header::SET_COOKIE, - HeaderValue::from_static( - "ghostlight_session=; Max-Age=0; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/", - ), - ); - return response; - } - let current_version = match current_eve_surface_version(&state, &account_hash).await { - Ok(value) => value, - Err(error) => { - return Json(eve_result( - &invocation, - "denied", - error.to_string(), - None, - None, - None, - )) - .into_response(); - } - }; - if invocation.operation.route_hint.source_version != Some(current_version) { - return Json(eve_result( - &invocation, - "denied", - format!( - "Stale Eve surface: expected version {current_version}. Refresh before retrying." - ), - None, - None, - None, - )) - .into_response(); - } - let idempotency_key = invocation.operation.idempotency_key.clone().unwrap(); - match state.auth.lock().await.reserve_command( - &account_hash, - &idempotency_key, - &invocation.operation.operation_id, - ) { - Ok(CommandReservation::Cached(result)) => return Json(result).into_response(), - Ok(CommandReservation::Pending) => { - return Json(eve_result( - &invocation, - "pending", - "This exact operation is already reserved. Refresh authoritative state; Ghostlight will not execute it twice.".into(), - None, - None, - None, - )).into_response(); - } - Ok(CommandReservation::Reserved) => {} - Err(error) => { - return Json(eve_result( - &invocation, - "denied", - error.to_string(), - None, - None, - None, - )) - .into_response(); - } - } - let operation_id = invocation.operation.operation_id.clone(); - let response = dispatch_eve_product_command(&headers, &state, &account_hash, invocation).await; - persist_reserved_eve_result( - &state, - &account_hash, - &idempotency_key, - &operation_id, - response, - ) - .await -} - -async fn persist_reserved_eve_result( - state: &AppState, - account_hash: &str, - idempotency_key: &str, - operation_id: &str, - response: Response, -) -> Response { - let status = response.status(); - let bytes = match axum::body::to_bytes(response.into_body(), 2 * 1024 * 1024).await { - Ok(value) => value, - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let result = match serde_json::from_slice::(&bytes) { - Ok(value) => value, - Err(error) => { - return ( - StatusCode::INTERNAL_SERVER_ERROR, - format!("Eve command boundary returned a non-typed result: {error}"), - ) - .into_response(); - } - }; - let persisted_result = persistable_eve_result(operation_id, &result); - if let Err(error) = state.auth.lock().await.record_command_result( - account_hash, - idempotency_key, - operation_id, - &persisted_result, - ) { - tracing::error!(%error, %operation_id, "Eve command committed but its reserved result could not be finalized; duplicate execution remains blocked"); - } - (status, Json(result)).into_response() -} - -fn persistable_eve_result(operation_id: &str, result: &serde_json::Value) -> serde_json::Value { - let mut persisted = result.clone(); - if matches!( - operation_id, - "session_zero.invites.create" | "campaign.export" - ) { - if let Some(value) = persisted.as_object_mut() { - value.remove("transientProjection"); - } - } - persisted -} - -async fn current_eve_surface_version(state: &AppState, account_hash: &str) -> anyhow::Result { - if let Some(id) = state - .session_zeros - .active_contract_review_for_account(account_hash) - .await? - { - return Ok(state.session_zeros.snapshot(id).await?.revision); - } - if let Some(runtime) = session_runtime(state, account_hash).await? { - let campaign = load_campaign(&runtime.store)?; - return Ok(campaign_interface_version(&campaign)); - } - if let Some(id) = state - .session_zeros - .session_for_account(account_hash) - .await? - { - return Ok(state.session_zeros.snapshot(id).await?.revision); - } - Ok(0) -} - -async fn complete_eve_authentication( - invocation: EveCommandInvocation, - state: AppState, -) -> Response { - let handle = invocation - .payload - .get("handle") - .and_then(serde_json::Value::as_str) - .unwrap_or(""); - if handle.is_empty() { - return Json(eve_result( - &invocation, - "denied", - "Authentication completion omitted its opaque handle.".into(), - None, - None, - None, - )) - .into_response(); - } - let completion = match state - .heimdall - .complete( - handle, - invocation.operation.idempotency_key.as_deref().unwrap(), - ) - .await - { - Ok(value) => value, - Err(error) => { - return Json(eve_result( - &invocation, - "denied", - error.to_string(), - None, - None, - None, - )) - .into_response(); - } - }; - if completion.status == "pending" { - return Json(eve_result(&invocation, "pending", "Heimdall is waiting for Discord.".into(), None, Some(serde_json::json!({ - "pluginId":"gamecult.heimdall.access","schemaId":"heimdall.auth_completion_status.v1", - "payload":{"schema":"heimdall.auth_completion_status.v1","status":"pending"} - })), None)).into_response(); - } - if completion.status == "denied" { - return Json(eve_result( - &invocation, - "denied", - completion.error.clone().unwrap_or_else(|| "Heimdall denied access.".into()), - None, - Some(serde_json::json!({ - "pluginId":"gamecult.heimdall.access","schemaId":"heimdall.auth_completion_status.v1", - "payload":{"schema":"heimdall.auth_completion_status.v1","status":"denied"} - })), - None, - )).into_response(); - } - let adopted = match adopt_heimdall_completion(&state, handle, completion).await { - Ok(value) => value, - Err(error) => return Json(eve_result(&invocation, "denied", error.to_string(), None, Some(serde_json::json!({ - "pluginId":"gamecult.heimdall.access","schemaId":"heimdall.auth_completion_status.v1", - "payload":{"schema":"heimdall.auth_completion_status.v1","status":"denied"} - })), None)).into_response(), - }; - let mut response = Json(eve_result( - &invocation, - "accepted", - "Authenticated.".into(), - None, - Some(serde_json::json!({ - "pluginId":"gamecult.heimdall.access","schemaId":"heimdall.auth_completion_status.v1", - "payload":{"schema":"heimdall.auth_completion_status.v1","status":"authenticated"} - })), - None, - )) - .into_response(); - response.headers_mut().insert( - header::SET_COOKIE, - app_session_cookie( - &adopted.session_token, - adopted.refresh_expires_at, - Utc::now(), - ), - ); - response -} - -struct AdoptedAppSession { - session_token: String, - refresh_expires_at: DateTime, -} - -async fn adopt_heimdall_completion( - state: &AppState, - expected_handle: &str, - completion: heimdall::AuthCompletionReceipt, -) -> anyhow::Result { - if completion.status != "authenticated" || completion.handle.as_deref() != Some(expected_handle) - { - anyhow::bail!("Heimdall completion did not match the pending Ghostlight attempt"); - } - let claims = state.heimdall.verify_completion(&completion).await?; - let session = completion - .session - .as_ref() - .context("Heimdall omitted its authenticated session")?; - if !completion - .shared_capabilities - .iter() - .any(|value| value == "app_access") - { - anyhow::bail!("Heimdall completion did not expose Ghostlight app_access"); - } - let refresh_expires_at = completion - .refresh - .as_ref() - .map(|value| value.expires_at.as_str()) - .unwrap_or(&session.expires_at) - .parse()?; - let refresh_token = completion - .refresh_token - .as_deref() - .context("Heimdall omitted its refresh claim")?; - let session_token = state.auth.lock().await.create_session(NewSession { - account_id: &claims.account_id, - heimdall_session_id: &claims.sid, - access_revision: claims.access_revision, - capabilities: claims.capabilities, - access_expires_at: DateTime::from_timestamp(claims.exp as i64, 0) - .context("Heimdall access expiry is invalid")?, - refresh_expires_at, - refresh_claim: refresh_token, - })?; - Ok(AdoptedAppSession { - session_token, - refresh_expires_at, - }) -} - -async fn complete_native_authentication( - state: &AppState, - handle: &str, - idempotency_key: &str, -) -> anyhow::Result { - let completion = state.heimdall.complete(handle, idempotency_key).await?; - match completion.status.as_str() { - "pending" => Ok(NativeAuthCompletionReceipt { - schema: "ghostlight.native_auth_completion_receipt.v1".into(), - status: "pending".into(), - message: "Heimdall is waiting for Discord authorization.".into(), - session_token: None, - refresh_expires_at: None, - }), - "denied" => Ok(NativeAuthCompletionReceipt { - schema: "ghostlight.native_auth_completion_receipt.v1".into(), - status: "denied".into(), - message: completion - .error - .unwrap_or_else(|| "Heimdall denied access.".into()), - session_token: None, - refresh_expires_at: None, - }), - "authenticated" => { - let adopted = adopt_heimdall_completion(state, handle, completion).await?; - Ok(NativeAuthCompletionReceipt { - schema: "ghostlight.native_auth_completion_receipt.v1".into(), - status: "authenticated".into(), - message: "Authenticated native Ghostlight client.".into(), - session_token: Some(adopted.session_token), - refresh_expires_at: Some(adopted.refresh_expires_at.to_rfc3339()), - }) - } - _ => anyhow::bail!("Heimdall returned an invalid authentication state"), - } -} - -fn app_session_cookie( - raw_cookie: &str, - refresh_expires_at: DateTime, - now: DateTime, -) -> HeaderValue { - let max_age = (refresh_expires_at - now).num_seconds().max(0); - HeaderValue::from_str(&format!( - "ghostlight_session={raw_cookie}; Max-Age={max_age}; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/" - )) - .expect("Ghostlight generated an invalid app-session cookie") -} - -fn validate_eve_invocation( - invocation: &EveCommandInvocation, - expected_transport: &str, -) -> anyhow::Result<()> { - if invocation.schema != "gamecult.eve.command_invocation.v1" - || invocation.provider_id != EVE_PROVIDER_ID - || invocation.surface_id != EVE_SURFACE_ID - || invocation.command_boundary != EVE_COMMAND_BOUNDARY - || invocation.receipt_schema != EVE_RESULT_SCHEMA - { - anyhow::bail!("Invocation does not match the Ghostlight Eve provider 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::>().is_err() - { - anyhow::bail!("Invocation metadata is incomplete"); - } - if contains_authority_field(&invocation.payload) { - anyhow::bail!("Player payloads may not supply actor, member, or account authority"); - } - if invocation.operation.route_hint.transport.as_deref() != Some(expected_transport) { - anyhow::bail!("Eve invocation does not match the admitted transport boundary"); - } - let expected_schema = eve_operation_schema(&invocation.operation.operation_id) - .ok_or_else(|| anyhow::anyhow!("Eve operation is not advertised by Ghostlight"))?; - if invocation.operation.schema_id.as_deref() != Some(expected_schema) { - anyhow::bail!( - "Eve operation payload schema does not match the advertised command descriptor" - ); - } - Ok(()) -} - -fn eve_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.v1", - "session_zero.begin" => "ghostlight.session_zero_begin.v1", - "session_zero.join" => "ghostlight.session_zero_join.v1", - "session_zero.invites.create" => "ghostlight.session_zero_invites_create.v1", - "session_zero.message.send" => "ghostlight.session_zero_message_send.v1", - "session_zero.boundary.set" => "ghostlight.session_zero_boundary_set.v1", - "session_zero.boundary.remove" => "ghostlight.session_zero_boundary_remove.v1", - "session_zero.leave" - | "session_zero.archive" - | "session_zero.roster.lock" - | "session_zero.compile" - | "session_zero.compilation_gaps.review" - | "session_zero.preview.discard" - | "session_zero.approve" - | "session_zero.publish" => "ghostlight.session_zero_revision_command.v1", - "session_zero.member.remove" => "ghostlight.session_zero_member_remove.v1", - "session_zero.decision.resolve" => "ghostlight.session_zero_decision_resolve.v1", - "campaign.entry" => "ghostlight.campaign_entry.v1", - "campaign.select" => "ghostlight.campaign_select.v1", - "campaign.export" => "ghostlight.campaign_export_request.v1", - "campaign.contract_review.begin" => "ghostlight.contract_review_begin.v1", - "world.speak" => "ghostlight.world_speak.v1", - "world.assess" => "ghostlight.player_action_assess.v1", - "world.attempt" => "ghostlight.player_action_attempt.v1", - "world.wait" => "ghostlight.world_wait.v1", - "governance.time.propose" => "ghostlight.time_advance_proposal.v1", - "governance.time.approve" => "ghostlight.time_advance_approval.v1", - "governance.travel.propose" => "ghostlight.group_travel_proposal.v1", - "governance.travel.approve" => "ghostlight.group_travel_approval.v1", - "governance.cells.propose" => "ghostlight.cell_budget_proposal.v1", - "governance.cells.approve" => "ghostlight.cell_budget_approval.v1", - "world.destination.compile" => "ghostlight.destination_compile.v1", - "world.destination.approve" => "ghostlight.destination_approval.v1", - "world.gestalt.fission.compile" => "ghostlight.gestalt_fission_compile.v1", - "world.gestalt.fission.approve" => "ghostlight.gestalt_fission_approval.v1", - _ => return None, - }) -} - -fn contains_authority_field(value: &serde_json::Value) -> bool { - match value { - serde_json::Value::Object(values) => values.iter().any(|(key, value)| { - matches!( - key.as_str(), - "actor_id" - | "actorId" - | "member_id" - | "memberId" - | "account_hash" - | "accountHash" - | "viewer_actor_id" - ) || contains_authority_field(value) - }), - serde_json::Value::Array(values) => values.iter().any(contains_authority_field), - _ => false, - } -} - -fn eve_result( - invocation: &EveCommandInvocation, - state: &str, - message: String, - transient_projection: Option, - plugin_payload: Option, - clear_bindings: Option>, -) -> serde_json::Value { - let source_version = invocation.operation.route_hint.source_version.unwrap_or(0); - let mut value = serde_json::json!({ - "schema":EVE_RESULT_SCHEMA, - "receipt":{ - "schema":"gamecult.eve.command_receipt.v1", - "receiptId":format!("eve-receipt:{}",uuid::Uuid::new_v4()), - "commandId":invocation.operation.idempotency_key.as_deref().unwrap_or(""), - "command":invocation.operation.operation_id, - "state":state, - "ownerRepo":"GameCult/Ghostlight", - "authority":"SessionZeroKernel or WorldKernel after server-side membership resolution", - "providerId":EVE_PROVIDER_ID, - "surfaceId":EVE_SURFACE_ID, - "message":message, - "diagnostics":[], - "issuedAtUtc":Utc::now().to_rfc3339(), - "sourceVersion":source_version - } - }); - if let Some(transient) = transient_projection { - value["transientProjection"] = transient; - } - if let Some(plugin) = plugin_payload { - value["pluginPayload"] = plugin; - } - if let Some(names) = clear_bindings { - value["draftDirective"] = serde_json::json!({"clear":true,"bindingNames":names}); - } - value -} - -async fn dispatch_eve_product_command( - headers: &HeaderMap, - state: &AppState, - account_hash: &str, - invocation: EveCommandInvocation, -) -> Response { - let operation = invocation.operation.operation_id.clone(); - let payload = captured_payload(&invocation.payload); - macro_rules! required_string { - ($name:literal) => { - match string_field(&payload, $name) { - Some(value) => value, - None => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!(concat!($name, " is required")), - ) - } - } - }; - } - macro_rules! required_u64 { - ($name:literal) => { - match u64_field(&payload, $name) { - Some(value) => value, - None => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!(concat!($name, " is required")), - ) - } - } - }; - } - let session_id = if operation.starts_with("session_zero.") - && !matches!( - operation.as_str(), - "session_zero.begin" | "session_zero.join" - ) { - match state.session_zeros.session_for_account(account_hash).await { - Ok(Some(value)) => Some(value), - Ok(None) => { - return Json(eve_result( - &invocation, - "denied", - "No active Session Zero belongs to this account.".into(), - None, - None, - None, - )) - .into_response(); - } - Err(error) => { - return Json(eve_result( - &invocation, - "denied", - error.to_string(), - None, - None, - None, - )) - .into_response(); - } - } - } else { - None - }; - let response = match operation.as_str() { - "session_zero.begin" => match decode_payload::(&payload) { - Ok(request) => { - begin_session_zero(headers.clone(), State(state.clone()), Json(request)).await - } - Err(error) => return invalid_eve_payload(&invocation, error), - }, - "session_zero.join" => { - let token = - string_field(&payload, "invite_token").or_else(|| string_field(&payload, "token")); - let request = decode_payload::(&payload); - match (token, request) { - (Some(token), Ok(request)) => { - join_session_zero( - Path(token), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - (None, _) => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!("invite_token is required"), - ); - } - (_, Err(error)) => return invalid_eve_payload(&invocation, error), - } - } - "session_zero.invites.create" => match decode_payload::(&payload) - { - Ok(request) => { - create_session_zero_invites( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - }, - "session_zero.message.send" => { - match decode_payload::(&payload) { - Ok(request) => { - post_session_zero_message( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - } - } - "session_zero.boundary.set" => match decode_payload::(&payload) - { - Ok(request) => { - set_session_zero_boundary( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - }, - "session_zero.boundary.remove" => { - let boundary_id = string_field(&payload, "target"); - let request = decode_payload::(&payload); - match (boundary_id, request) { - (Some(id), Ok(request)) => { - remove_session_zero_boundary( - Path((session_id.unwrap(), id)), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - (None, _) => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!("boundary target is required"), - ); - } - (_, Err(error)) => return invalid_eve_payload(&invocation, error), - } - } - "session_zero.leave" => match decode_payload::(&payload) { - Ok(request) => { - leave_session_zero( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - }, - "session_zero.archive" => match decode_payload::(&payload) { - Ok(request) => { - archive_session_zero( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - }, - "session_zero.member.remove" => { - let target = string_field(&payload, "target"); - let revision = u64_field(&payload, "expected_revision"); - match (target, revision) { - (Some(member_id), Some(expected_revision)) => { - remove_session_zero_member( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(SessionZeroMemberRequest { - expected_revision, - member_id, - }), - ) - .await - } - _ => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!("target and expected_revision are required"), - ); - } - } - } - "session_zero.decision.resolve" => { - match decode_payload::(&payload) { - Ok(request) => { - resolve_session_zero_decision( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - } - } - "session_zero.roster.lock" => { - match decode_payload::(&payload) { - Ok(request) => { - lock_session_zero_roster( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - } - } - "session_zero.compile" => match decode_payload::(&payload) { - Ok(request) => { - compile_session_zero( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - }, - "session_zero.compilation_gaps.review" => { - match decode_payload::(&payload) { - Ok(request) => { - review_session_zero_compilation_gaps( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - } - } - "session_zero.preview.discard" => { - match decode_payload::(&payload) { - Ok(request) => { - discard_session_zero_preview( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - } - } - "session_zero.approve" => match decode_payload::(&payload) { - Ok(request) => { - approve_session_zero( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - }, - "session_zero.publish" => match decode_payload::(&payload) { - Ok(request) => { - publish_session_zero( - Path(session_id.unwrap()), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - Err(error) => return invalid_eve_payload(&invocation, error), - }, - "campaign.contract_review.begin" => { - begin_contract_review(headers.clone(), State(state.clone())).await - } - "campaign.select" => match string_field(&payload, "campaign_id") - .and_then(|value| uuid::Uuid::parse_str(&value).ok()) - { - Some(campaign_id) => { - select_campaign_route(Path(campaign_id), headers.clone(), State(state.clone())) - .await - } - None => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!("campaign_id is required"), - ); - } - }, - "campaign.entry" => { - match state - .auth - .lock() - .await - .clear_selected_campaign(account_hash) - { - Ok(()) => StatusCode::NO_CONTENT.into_response(), - Err(error) => { - (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response() - } - } - } - "campaign.export" => { - let runtime = match session_runtime(state, account_hash).await { - Ok(Some(value)) => value, - Ok(None) => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!("No campaign is selected."), - ); - } - Err(error) => return invalid_eve_payload(&invocation, error), - }; - let campaign = match load_campaign(&runtime.store) { - Ok(value) => value, - Err(error) => return invalid_eve_payload(&invocation, error), - }; - if let Err(error) = campaign_member_for_account(&runtime.store, &campaign, account_hash) - { - return invalid_eve_payload(&invocation, error); - } - let path = match state - .registry - .export(campaign.id, &state.exports_root) - .await - { - Ok(value) => value, - Err(error) => return invalid_eve_payload(&invocation, error), - }; - let filename = match path - .file_name() - .and_then(|value| value.to_str()) - .map(str::to_owned) - { - Some(value) => value, - None => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!("Campaign export did not produce a portable filename."), - ); - } - }; - let size_bytes = std::fs::metadata(&path) - .map(|value| value.len()) - .unwrap_or(0); - let token = match state.auth.lock().await.issue_campaign_export_grant( - account_hash, - campaign.id, - path, - filename.clone(), - Utc::now(), - chrono::Duration::minutes(15), - ) { - Ok(value) => value, - Err(error) => return invalid_eve_payload(&invocation, error), - }; - Json(serde_json::json!({ - "message":"Campaign snapshot is ready. The download grant expires in 15 minutes and can be used once.", - "download_url":format!("/ghostlight/api/eve/resources/{token}"), - "filename":filename, - "size_bytes":size_bytes, - "campaign_revision":campaign.revision, - })) - .into_response() - } - "world.speak" | "world.assess" | "world.attempt" | "world.wait" => { - let (campaign, actor_id) = match current_player_context(state, account_hash).await { - Ok(value) => value, - Err(error) => return invalid_eve_payload(&invocation, error), - }; - let world_command = match operation.as_str() { - "world.speak" => WorldCommand::Speak { - expected_revision: required_u64!("expected_revision"), - actor_id, - text: required_string!("text"), - intended_effect: None, - persona_response_actor_ids: BTreeSet::new(), - }, - "world.assess" => WorldCommand::Assess { - expected_revision: required_u64!("expected_revision"), - intent: ActionIntent { - actor_id, - description: required_string!("description"), - intended_effect: required_string!("intended_effect"), - }, - proposal: None, - }, - "world.attempt" => WorldCommand::Attempt { - actor_id, - assessment_digest: required_string!("assessment_digest"), - }, - "world.wait" => WorldCommand::Wait { - expected_revision: required_u64!("expected_revision"), - minutes: required_u64!("minutes") as u32, - }, - _ => unreachable!(), - }; - let _ = campaign; - command(headers.clone(), State(state.clone()), Json(world_command)).await - } - "governance.time.propose" => match ( - u64_field(&payload, "expected_revision"), - u64_field(&payload, "time_advance_minutes"), - ) { - (Some(expected_revision), Some(minutes)) if u32::try_from(minutes).is_ok() => { - propose_time_advance( - headers.clone(), - State(state.clone()), - Json(TimeAdvanceRequest { - expected_revision, - minutes: minutes as u32, - }), - ) - .await - } - _ => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!("expected_revision and time_advance_minutes are required"), - ); - } - }, - "governance.time.approve" => { - let proposal = string_field(&payload, "proposal_id"); - let request = decode_payload::(&payload); - match (proposal, request) { - (Some(id), Ok(request)) => { - approve_time_advance( - Path(id), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - _ => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!("proposal_id and expected_revision are required"), - ); - } - } - } - "governance.travel.propose" => match decode_payload::(&payload) { - Ok(request) => { - propose_group_travel(headers.clone(), State(state.clone()), Json(request)).await - } - Err(error) => return invalid_eve_payload(&invocation, error), - }, - "governance.travel.approve" => { - let proposal = string_field(&payload, "proposal_id"); - let request = decode_payload::(&payload); - match (proposal, request) { - (Some(id), Ok(request)) => { - approve_group_travel( - Path(id), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - _ => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!("proposal_id and expected_revision are required"), - ); - } - } - } - "governance.cells.propose" => match decode_payload::(&payload) { - Ok(request) => { - propose_cell_budget(headers.clone(), State(state.clone()), Json(request)).await - } - Err(error) => return invalid_eve_payload(&invocation, error), - }, - "governance.cells.approve" => { - let proposal = string_field(&payload, "proposal_id"); - let request = decode_payload::(&payload); - match (proposal, request) { - (Some(id), Ok(request)) => { - approve_cell_budget( - Path(id), - headers.clone(), - State(state.clone()), - Json(request), - ) - .await - } - _ => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!("proposal_id and expected_revision are required"), - ); - } - } - } - "world.destination.compile" => { - let (campaign, actor_id) = match current_player_context(state, account_hash).await { - Ok(value) => value, - Err(error) => return invalid_eve_payload(&invocation, error), - }; - let origin_location_id = match campaign.actors.get(&actor_id) { - Some(actor) => actor.location_id.clone(), - None => { - return invalid_eve_payload( - &invocation, - anyhow::anyhow!("Assigned actor is missing."), - ); - } - }; - compile_destination( - headers.clone(), - State(state.clone()), - Json(DestinationRequest { - origin_location_id, - destination: required_string!("destination"), - }), - ) - .await - } - "world.destination.approve" => match string_field(&payload, "preview_id") { - Some(id) => approve_destination(Path(id), headers.clone(), State(state.clone())).await, - None => { - return invalid_eve_payload(&invocation, anyhow::anyhow!("preview_id is required")); - } - }, - "world.gestalt.fission.compile" => { - match decode_payload::(&payload) { - Ok(request) => { - compile_fission(headers.clone(), State(state.clone()), Json(request)).await - } - Err(error) => return invalid_eve_payload(&invocation, error), - } - } - "world.gestalt.fission.approve" => match string_field(&payload, "preview_id") { - Some(id) => approve_fission(Path(id), headers.clone(), State(state.clone())).await, - None => { - return invalid_eve_payload(&invocation, anyhow::anyhow!("preview_id is required")); - } - }, - _ => { - return Json(eve_result( - &invocation, - "denied", - format!("Unknown Eve operation {operation}."), - None, - None, - None, - )) - .into_response(); - } - }; - kernel_response_to_eve(invocation, response).await -} - -fn captured_payload(payload: &serde_json::Value) -> serde_json::Value { - let mut captured = payload.as_object().cloned().unwrap_or_default(); - if let Some(serde_json::Value::Object(bindings)) = captured.remove("bindings") { - for (name, value) in bindings { - captured.insert(name, value); - } - } - serde_json::Value::Object(captured) -} - -fn decode_payload( - payload: &serde_json::Value, -) -> anyhow::Result { - serde_json::from_value(payload.clone()).map_err(Into::into) -} - -fn string_field(payload: &serde_json::Value, name: &str) -> Option { - payload - .get(name) - .and_then(serde_json::Value::as_str) - .map(str::to_owned) -} - -fn u64_field(payload: &serde_json::Value, name: &str) -> Option { - payload.get(name).and_then(serde_json::Value::as_u64) -} - -fn invalid_eve_payload(invocation: &EveCommandInvocation, error: anyhow::Error) -> Response { - Json(eve_result( - invocation, - "denied", - format!("Invalid operation payload: {error}"), - None, - None, - None, - )) - .into_response() -} - -async fn current_player_context( - state: &AppState, - account_hash: &str, -) -> anyhow::Result<(Campaign, String)> { - let runtime = session_runtime(state, account_hash) - .await? - .ok_or_else(|| anyhow::anyhow!("No campaign is selected."))?; - let campaign = load_campaign(&runtime.store)?; - let member = campaign_member_for_account(&runtime.store, &campaign, account_hash)?; - Ok((campaign, member.actor_id)) -} - -async fn kernel_response_to_eve(invocation: EveCommandInvocation, response: Response) -> Response { - let status = response.status(); - let bytes = match axum::body::to_bytes(response.into_body(), 2 * 1024 * 1024).await { - Ok(value) => value, - Err(error) => { - return Json(eve_result( - &invocation, - "denied", - error.to_string(), - None, - None, - None, - )) - .into_response(); - } - }; - let value = serde_json::from_slice::(&bytes).ok(); - let fallback = String::from_utf8_lossy(&bytes).trim().to_owned(); - let message = value - .as_ref() - .and_then(|value| { - value - .get("error") - .or_else(|| value.get("message")) - .and_then(serde_json::Value::as_str) - }) - .map(str::to_owned) - .or_else(|| (!fallback.is_empty() && value.is_none()).then_some(fallback)) - .unwrap_or_else(|| { - if status.is_success() { - "Ghostlight committed the operation.".into() - } else { - format!("Ghostlight refused the operation ({status}).") - } - }); - let accepted = status.is_success(); - let transient = if accepted { - value.as_ref().and_then(|value| { - transient_result_projection( - &invocation.operation.operation_id, - value, - invocation.operation.route_hint.source_version.unwrap_or(0), - ) - }) - } else { - None - }; - let clear = accepted.then(|| { - invocation - .payload - .get("bindings") - .and_then(serde_json::Value::as_object) - .map(|values| values.keys().cloned().collect::>()) - .unwrap_or_default() - }); - Json(eve_result( - &invocation, - if accepted { "accepted" } else { "denied" }, - message, - transient, - None, - clear, - )) - .into_response() -} - -fn transient_result_projection( - operation: &str, - value: &serde_json::Value, - source_version: u64, -) -> Option { - let mut children = Vec::new(); - let mut result_version = source_version; - if operation == "session_zero.invites.create" { - let links = value - .get("invite_tokens")? - .as_array()? - .iter() - .filter_map(serde_json::Value::as_str) - .map(|token| format!("/ghostlight/?invite={token}")) - .collect::>(); - let text = (!links.is_empty()) - .then(|| format!("Single-use invitations:\n{}", links.join("\n")))?; - children.push(serde_json::json!({"id":"ghostlight.command-result.text","kind":"text","props":{"value":text},"children":[]})); - } else if operation == "campaign.export" { - let uri = value.get("download_url")?.as_str()?; - let filename = value.get("filename")?.as_str()?; - let size = value - .get("size_bytes") - .and_then(serde_json::Value::as_u64) - .unwrap_or(0); - let revision = value - .get("campaign_revision") - .and_then(serde_json::Value::as_u64) - .unwrap_or(0); - children.push(serde_json::json!({ - "id":"ghostlight.campaign-export.summary", - "kind":"text", - "props":{"value":format!("Campaign revision {revision} · {size} bytes · CultCache .cc")}, - "children":[] - })); - children.push(serde_json::json!({ - "id":"ghostlight.campaign-export.download", - "kind":"resource.download", - "props":{"label":"Download campaign export","uri":uri,"filename":filename}, - "children":[] - })); - } else if operation == "world.assess" - || value.get("kind").and_then(serde_json::Value::as_str) == Some("assessed") - { - let assessment = value.get("assessment")?; - result_version = assessment - .get("revision") - .and_then(serde_json::Value::as_u64) - .map(|revision| rebase_campaign_surface_revision(source_version, revision)) - .unwrap_or(source_version); - let digest = assessment.get("digest")?.as_str()?; - let admissible = assessment - .get("admissible") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false); - let modifier_details = assessment - .get("modifiers") - .and_then(serde_json::Value::as_array) - .map(|modifiers| { - if modifiers.is_empty() { - "Modifiers: none".to_string() - } else { - let lines = modifiers - .iter() - .map(|modifier| { - let label = modifier - .get("label") - .and_then(serde_json::Value::as_str) - .unwrap_or("context"); - let value = modifier - .get("value") - .and_then(serde_json::Value::as_i64) - .unwrap_or(0); - let references = modifier - .get("references") - .and_then(serde_json::Value::as_array) - .into_iter() - .flatten() - .filter_map(serde_json::Value::as_str) - .collect::>(); - if references.is_empty() { - format!("- {value:+} {label}") - } else { - format!("- {value:+} {label} [{}]", references.join(", ")) - } - }) - .collect::>() - .join("\n"); - format!("Modifiers:\n{lines}") - } - }) - .unwrap_or_else(|| "Modifiers: none".into()); - let bargains = assessment - .get("bargains") - .and_then(serde_json::Value::as_array) - .filter(|values| !values.is_empty()) - .map(|values| { - values - .iter() - .filter_map(serde_json::Value::as_str) - .map(|value| format!("- {value}")) - .collect::>() - .join("\n") - }) - .unwrap_or_default(); - let summary = if admissible { - format!( - "The attempt is admissible.\nDC {} · modifier {} · ceiling {}\n{}\nSuccess: {}\nMixed: {}\nFailure: {}", - assessment - .get("dc") - .and_then(serde_json::Value::as_u64) - .unwrap_or(0), - assessment - .get("modifier_total") - .and_then(serde_json::Value::as_i64) - .unwrap_or(0), - assessment - .get("effect_ceiling") - .and_then(serde_json::Value::as_str) - .unwrap_or("bounded"), - modifier_details, - assessment - .get("success_stake") - .and_then(serde_json::Value::as_str) - .unwrap_or(""), - assessment - .get("mixed_stake") - .and_then(serde_json::Value::as_str) - .unwrap_or(""), - assessment - .get("failure_stake") - .and_then(serde_json::Value::as_str) - .unwrap_or(""), - ) - } else { - format!( - "The attempt is not currently admissible. No roll occurs.\nMissing permission: {}\nEffect ceiling: {}\nResult: {}{}", - assessment - .get("missing_permission") - .and_then(serde_json::Value::as_str) - .unwrap_or("The intended effect is outside the actor's current authority."), - assessment - .get("effect_ceiling") - .and_then(serde_json::Value::as_str) - .unwrap_or("No canonical effect."), - assessment - .get("failure_stake") - .and_then(serde_json::Value::as_str) - .unwrap_or("The overreach is refused."), - (!bargains.is_empty()) - .then(|| format!("\nWays to make a narrower attempt possible:\n{bargains}")) - .unwrap_or_default(), - ) - }; - children.push(serde_json::json!({"id":"ghostlight.assessment.summary","kind":"text","props":{"value":summary},"children":[]})); - if admissible { - children.push(eve_button( - "ghostlight.assessment.confirm", - "Roll the d20", - "world.attempt", - serde_json::json!({"assessment_digest":digest}), - &[], - )); - } - } else if operation == "world.attempt" - && value.get("kind").and_then(serde_json::Value::as_str) == Some("committed") - { - let receipt = value.get("receipt")?; - let roll = receipt.get("roll")?; - result_version = receipt - .get("revision") - .and_then(serde_json::Value::as_u64) - .map(|revision| rebase_campaign_surface_revision(source_version, revision)) - .unwrap_or(source_version); - let d20 = roll.get("d20")?.as_u64()?; - let modifier = roll.get("modifier_total")?.as_i64()?; - let total = roll.get("total")?.as_i64()?; - let dc = roll.get("dc")?.as_u64()?; - let outcome = roll.get("outcome")?.as_str()?.replace('_', " "); - children.push(serde_json::json!({ - "id":"ghostlight.roll.summary", - "kind":"text", - "props":{ - "value":format!( - "d20 {d20} {modifier:+} = {total} against DC {dc} — {outcome}." - ) - }, - "children":[] - })); - } else if matches!( - operation, - "world.destination.compile" | "world.gestalt.fission.compile" - ) { - children.push(serde_json::json!({"id":"ghostlight.command-result.text","kind":"text","props":{"value":serde_json::to_string_pretty(value).ok()?},"children":[]})); - let preview_id = value.get("preview_id")?.as_str()?; - let approval_operation = if operation == "world.destination.compile" { - "world.destination.approve" - } else { - "world.gestalt.fission.approve" - }; - children.push(eve_button( - "ghostlight.preview.approve", - "Approve preview", - approval_operation, - serde_json::json!({"preview_id":preview_id}), - &[], - )); - } else { - return None; - } - Some(serde_json::json!({ - "type":"surface-state", - "schema":"gamecult.eve.surface.v1", - "providerId":EVE_PROVIDER_ID, - "providerKind":"narrative.simulation.command-result", - "title":"Ghostlight result", - "version":result_version, - "updatedAtUtc":Utc::now().to_rfc3339(), - "surface":{ - "id":"ghostlight.command-result", - "root":{"id":"ghostlight.command-result.root","kind":"card","props":{"title":"Result"},"children":children}, - "styles":{"tokens":{"colorBackground":"#0c1110","colorPanel":"#17201d","colorText":"#e8e1cf","colorMuted":"#9aa69f","colorAccent":"#d49b58"}} - }, - "commands":[ - eve_command_descriptor("world.attempt","ghostlight.player_action_attempt.v1",&[],"WorldKernel"), - eve_command_descriptor("world.destination.approve","ghostlight.destination_approval.v1",&[],"WorldKernel"), - eve_command_descriptor("world.gestalt.fission.approve","ghostlight.gestalt_fission_approval.v1",&[],"WorldKernel") - ] - })) -} - -async fn health(State(state): State) -> Response { - match state.mesh.health() { - Ok(value) => Json(value).into_response(), - Err(error) => (StatusCode::SERVICE_UNAVAILABLE, error.to_string()).into_response(), - } -} - -async fn eve_resource( - Path(token): Path, - headers: HeaderMap, - State(state): State, -) -> Response { - let Some(account_hash) = authenticated_session(&headers, &state).await else { - return StatusCode::UNAUTHORIZED.into_response(); - }; - let grant = match state.auth.lock().await.consume_campaign_export_grant( - &token, - &account_hash, - Utc::now(), - ) { - Ok(Some(value)) => value, - Ok(None) => return StatusCode::NOT_FOUND.into_response(), - Err(error) => { - tracing::warn!(%error, "campaign export grant consumption failed"); - return StatusCode::INTERNAL_SERVER_ERROR.into_response(); - } - }; - let exports_root = match std::fs::canonicalize(&state.exports_root) { - Ok(value) => value, - Err(error) => { - tracing::warn!(%error, "campaign export root is unavailable"); - return StatusCode::INTERNAL_SERVER_ERROR.into_response(); - } - }; - let export_path = match std::fs::canonicalize(&grant.export_path) { - Ok(value) if value.starts_with(&exports_root) => value, - Ok(_) => { - tracing::error!(campaign_id=%grant.campaign_id, "campaign export grant escaped its owned root"); - return StatusCode::INTERNAL_SERVER_ERROR.into_response(); - } - Err(error) => { - tracing::warn!(%error, campaign_id=%grant.campaign_id, "campaign export file is unavailable"); - return StatusCode::NOT_FOUND.into_response(); - } - }; - let bytes = match tokio::fs::read(export_path).await { - Ok(value) => value, - Err(error) => { - tracing::warn!(%error, campaign_id=%grant.campaign_id, "campaign export read failed"); - return StatusCode::INTERNAL_SERVER_ERROR.into_response(); - } - }; - Response::builder() - .status(StatusCode::OK) - .header(header::CONTENT_TYPE, "application/vnd.gamecult.cultcache") - .header(header::CONTENT_LENGTH, bytes.len().to_string()) - .header( - header::CONTENT_DISPOSITION, - format!("attachment; filename=\"{}\"", grant.filename), - ) - .header("cache-control", "private, no-store") - .body(Body::from(bytes)) - .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()) -} - -async fn begin_session_zero( - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - let account_hash = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let Some(vault_id) = canonical_vault_id(&request.vault_provider) else { - return ( - StatusCode::UNPROCESSABLE_ENTITY, - "Select one of the advertised lore Vaults.", - ) - .into_response(); - }; - let allowance = state.entitlements.persona_cell_allowance(&account_hash); - match SessionZeroState::new_with_allowance( - request.name, - vault_id.into(), - account_hash.clone(), - request.display_name, - allowance, - ) { - Ok(session_zero) => { - let id = session_zero.id; - match state.session_zeros.create(session_zero).await { - Ok(runtime) => match state.session_zeros.snapshot(id).await { - Ok(snapshot) => match session_zero_surface(&snapshot, &account_hash) { - Ok(surface) => { - if let Ok(compiler) = compiler_for_vault( - &state.compiler, - &snapshot.contract.vault_provider, - ) { - let mesh_state = state.clone(); - tokio::spawn(async move { - if let Err(error) = run_live_model_work( - &mesh_state, - populate_opening_suggestions( - compiler, - runtime, - snapshot, - mesh_state.clone(), - ), - ) - .await - { - tracing::warn!(%error, "inline Session Zero opening suggestions failed without draft mutation"); - } - }); - } - schedule_mesh_refresh(&state); - (StatusCode::CREATED, Json(surface)).into_response() - } - Err(error) => { - (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response() - } - }, - Err(error) => { - (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response() - } - }, - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - } - } - Err(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response(), - } -} - -async fn populate_opening_suggestions( - compiler: Arc, - runtime: ghostlight_dungeon::session_zero::SessionZeroRuntime, - snapshot: SessionZeroState, - state: AppState, -) -> anyhow::Result<()> { - let suggestions = compiler - .suggest_openings(OpeningRequest { - setting: snapshot.contract.vault_provider.clone(), - constraints: vec![format!( - "Offer source-grounded possibilities for the Session Zero draft named {}. They are discussion proposals, not accepted world truth.", - snapshot.name - )], - }) - .await?; - for receipt in &suggestions.evidence_receipts { - if runtime - .store - .load::( - "vault_evidence_receipt.v1", - &receipt.id, - )? - .is_none() - { - runtime.store.insert( - "vault_evidence_receipt.v1", - "ghostlight.vault_evidence_receipt.v1", - &receipt.id, - receipt, - )?; - } - } - let decisions = suggestions - .openings - .iter() - .map( - |opening| ghostlight_dungeon::session_zero::SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: format!("opening:{}", opening.id), - owner_member_id: None, - prompt: format!( - "Use '{}' as the starting frame for further Session Zero discussion?", - opening.title - ), - proposed_resolution: format!( - "{} — {} at {}, under pressure from {}. Player hook: {}", - opening.title, - opening.era, - opening.place, - opening.pressure, - opening.player_hook - ), - proposed_extraordinary_permission: None, - proposed_contract_patch: Some( - ghostlight_dungeon::session_zero::CampaignContractPatch { - premise: Some(opening.player_hook.clone()), - starting_where: Some(opening.place.clone()), - starting_when: Some(opening.era.clone()), - starting_pressure: Some(opening.pressure.clone()), - ..Default::default() - }, - ), - proposed_character_patch: None, - evidence_receipt_ids: opening.evidence_receipt_ids.clone(), - pending_counter: None, - material: false, - resolved: false, - }, - ) - .collect::>(); - let dm_speech = format!( - "I found three Vault-grounded starting frames. They are invitations, not decrees:\n{}\nChoose one to place it into our typed draft for discussion, counter it, or ignore all three and describe your own start.", - suggestions - .openings - .iter() - .map(|opening| format!( - "• {} — {} · {} · {}", - opening.title, opening.era, opening.place, opening.pressure - )) - .collect::>() - .join("\n") - ); - let mut model_receipts = suggestions.model_receipts; - model_receipts.push(suggestions.retrieval_receipt); - runtime - .kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: snapshot.shared_epoch, - expected_channel_revision: snapshot.channels["shared:table"].revision, - channel_id: "shared:table".into(), - member_id: None, - supersedes_countered_decision_id: None, - delta: ghostlight_dungeon::session_zero::SessionZeroDelta { - contract_patch: Default::default(), - character_patch: None, - decisions, - dm_speech, - suggested_replies: vec![ - "Let's discuss the first opening.".into(), - "Show me what evidence supports these.".into(), - "I want a fully custom start.".into(), - ], - }, - model_receipts, - }) - .await?; - schedule_mesh_refresh(&state); - Ok(()) -} - -fn accepted_opening_suggestion( - state: &SessionZeroState, - decision_id: &str, -) -> Option { - let decision = state.decisions.get(decision_id)?; - if !decision.resolved || !decision_id.starts_with("opening:") { - return None; - } - let patch = decision.proposed_contract_patch.as_ref()?; - Some(OpeningSuggestion { - id: decision_id.trim_start_matches("opening:").to_string(), - title: decision - .proposed_resolution - .split(" — ") - .next() - .unwrap_or("Suggested opening") - .to_string(), - era: patch.starting_when.clone()?, - place: patch.starting_where.clone()?, - pressure: patch.starting_pressure.clone()?, - player_hook: patch.premise.clone()?, - evidence_receipt_ids: decision.evidence_receipt_ids.clone(), - }) -} - -async fn populate_role_suggestions( - compiler: Arc, - runtime: ghostlight_dungeon::session_zero::SessionZeroRuntime, - snapshot: SessionZeroState, - opening: OpeningSuggestion, - state: AppState, -) -> anyhow::Result<()> { - let suggestions = compiler.suggest_roles(&opening).await?; - for receipt in &suggestions.evidence_receipts { - if runtime - .store - .load::( - "vault_evidence_receipt.v1", - &receipt.id, - )? - .is_none() - { - runtime.store.insert( - "vault_evidence_receipt.v1", - "ghostlight.vault_evidence_receipt.v1", - &receipt.id, - receipt, - )?; - } - } - let mut receipts = suggestions.model_receipts; - receipts.push(suggestions.retrieval_receipt); - let active_members = snapshot - .members - .values() - .filter(|member| member.active) - .cloned() - .collect::>(); - for (index, member) in active_members.into_iter().enumerate() { - let channel_id = format!("private:{}", member.id); - let decisions = suggestions - .roles - .iter() - .map( - |role| ghostlight_dungeon::session_zero::SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: format!("role:{}:{}", member.id, role.id), - owner_member_id: Some(member.id.clone()), - prompt: format!( - "Use '{}' as a starting character premise for further negotiation?", - role.name - ), - proposed_resolution: format!("{} — {}", role.name, role.premise), - proposed_extraordinary_permission: None, - proposed_contract_patch: None, - proposed_character_patch: Some( - ghostlight_dungeon::session_zero::CharacterDraftPatch { - name: Some(role.name.clone()), - public_premise: Some(role.premise.clone()), - capabilities_add: role.capabilities.clone(), - obligations_add: role.obligations.clone(), - ..Default::default() - }, - ), - evidence_receipt_ids: role.evidence_receipt_ids.clone(), - pending_counter: None, - material: false, - resolved: false, - }, - ) - .collect(); - runtime - .kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: snapshot.character_epochs[&member.id], - expected_channel_revision: snapshot.channels[&channel_id].revision, - channel_id, - member_id: Some(member.id.clone()), - supersedes_countered_decision_id: None, - delta: ghostlight_dungeon::session_zero::SessionZeroDelta { - contract_patch: Default::default(), - character_patch: None, - decisions, - dm_speech: format!( - "For {}, I found three source-grounded roles inside the chosen opening. Pick one to put it into your private draft for negotiation, counter it, or build your own.", - member.display_name - ), - suggested_replies: vec![ - "Let's negotiate the first role.".into(), - "I want a custom character.".into(), - ], - }, - model_receipts: if index == 0 { receipts.clone() } else { vec![] }, - }) - .await?; - } - schedule_mesh_refresh(&state); - Ok(()) -} - -async fn create_session_zero_invites( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - let account_hash = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let runtime = match state.session_zeros.runtime(session_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - match runtime - .kernel - .command(SessionZeroCommand::CreateInvites { - actor_account_hash: account_hash, - count: request.count, - }) - .await - { - Ok(result) => { - schedule_mesh_refresh(&state); - Json(serde_json::json!({ - "session_zero_id": session_id, - "revision": result.state.revision, - "invite_tokens": result.invite_tokens, - })) - .into_response() - } - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - } -} - -async fn join_session_zero( - Path(token): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - let account_hash = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let session_id = match state.session_zeros.session_for_invite(&token).await { - Ok(Some(value)) => value, - Ok(None) => { - return ( - StatusCode::NOT_FOUND, - "invite is invalid, expired, or consumed", - ) - .into_response(); - } - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let runtime = match state.session_zeros.runtime(session_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - match runtime - .kernel - .command(SessionZeroCommand::Join { - token, - account_hash: account_hash.clone(), - display_name: request.display_name, - cell_allowance: state.entitlements.persona_cell_allowance(&account_hash), - }) - .await - { - Ok(result) => { - schedule_mesh_refresh(&state); - match session_zero_surface(&result.state, &account_hash) { - Ok(surface) => (StatusCode::CREATED, Json(surface)).into_response(), - Err(error) => { - (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response() - } - } - } - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - } -} - -async fn post_session_zero_message( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - let account_hash = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let runtime = match state.session_zeros.runtime(session_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - let channel_id = request.channel_id.clone(); - let result = match runtime - .kernel - .command(SessionZeroCommand::PostPlayerMessage { - actor_account_hash: account_hash.clone(), - expected_revision: request.expected_revision, - channel_id: channel_id.clone(), - text: request.text, - }) - .await - { - Ok(value) => value, - Err(error) => return (StatusCode::CONFLICT, error.to_string()).into_response(), - }; - let member_id = result - .state - .member_for_account(&account_hash) - .map(|member| member.id.clone()); - let channel = result.state.channels.get(&channel_id).cloned(); - if let Some(channel) = channel { - let private_member = if channel.kind - == ghostlight_dungeon::session_zero::SessionZeroChannelKind::PrivateDm - { - member_id.clone() - } else { - None - }; - schedule_session_zero_dm_response( - &state, - &runtime, - result.state.clone(), - channel_id.clone(), - private_member, - None, - ); - } - schedule_mesh_refresh(&state); - ( - StatusCode::ACCEPTED, - Json(serde_json::json!({ - "schema": "ghostlight.session_zero_progress.v1", - "session_zero_id": session_id, - "revision": result.state.revision, - "status": "player_message_committed", - })), - ) - .into_response() -} - -fn schedule_session_zero_dm_response( - state: &AppState, - runtime: &ghostlight_dungeon::session_zero::SessionZeroRuntime, - snapshot: SessionZeroState, - channel_id: String, - member_id: Option, - supersedes_countered_decision_id: Option, -) { - let Some(director) = state.session_zero_director.clone() else { - tracing::warn!( - session_zero_id = %snapshot.id, - revision = snapshot.revision, - %channel_id, - "Session Zero DM response was not scheduled because the model director is unavailable" - ); - return; - }; - let Some(channel) = snapshot.channels.get(&channel_id).cloned() else { - tracing::warn!( - session_zero_id = %snapshot.id, - revision = snapshot.revision, - %channel_id, - "Session Zero DM response was not scheduled because the channel is absent" - ); - return; - }; - let component_epoch = member_id - .as_ref() - .and_then(|id| snapshot.character_epochs.get(id).copied()) - .unwrap_or(snapshot.shared_epoch); - let kernel = runtime.kernel.clone(); - let mesh_state = state.clone(); - tracing::info!( - session_zero_id = %snapshot.id, - revision = snapshot.revision, - %channel_id, - "Session Zero DM response queued" - ); - tokio::spawn(async move { - let _live = LiveTurnGuard::enter(&mesh_state).await; - tracing::info!( - session_zero_id = %snapshot.id, - revision = snapshot.revision, - %channel_id, - "Session Zero DM response started" - ); - let response = director - .respond( - &snapshot, - &channel_id, - member_id.as_deref(), - supersedes_countered_decision_id.as_deref(), - ) - .await; - match response { - Ok((delta, receipts)) => { - let applied = kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: component_epoch, - expected_channel_revision: channel.revision, - channel_id: channel_id.clone(), - member_id: member_id.clone(), - supersedes_countered_decision_id: supersedes_countered_decision_id.clone(), - delta, - model_receipts: receipts, - }) - .await; - if let Err(error) = applied { - tracing::info!(%error, "stale or invalid Session Zero DM proposal discarded"); - if supersedes_countered_decision_id.is_some() { - append_session_zero_dm_failure_notice( - &kernel, - &mesh_state, - component_epoch, - channel.revision, - channel_id, - member_id, - "I couldn't turn that counterproposal into a safe typed replacement. Your counter remains pending and the previous bargain cannot be accepted. Please discuss or counter it again.", - ) - .await; - } - } else { - schedule_mesh_refresh(&mesh_state); - } - } - Err(error) => { - tracing::warn!(%error, "Session Zero DM inference failed without draft mutation"); - append_session_zero_dm_failure_notice( - &kernel, - &mesh_state, - component_epoch, - channel.revision, - channel_id, - member_id, - "I couldn't finish that response. Your message is safely recorded and no draft state changed; please retry or rephrase when you're ready.", - ) - .await; - } - } - }); -} - -async fn append_session_zero_dm_failure_notice( - kernel: &ghostlight_dungeon::session_zero::SessionZeroKernel, - state: &AppState, - expected_component_epoch: u64, - expected_channel_revision: u64, - channel_id: String, - member_id: Option, - message: &str, -) { - let failure = ghostlight_dungeon::session_zero::SessionZeroDelta { - dm_speech: message.into(), - ..Default::default() - }; - if let Err(stale) = kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch, - expected_channel_revision, - channel_id, - member_id, - supersedes_countered_decision_id: None, - delta: failure, - model_receipts: Vec::new(), - }) - .await - { - tracing::info!(%stale, "stale Session Zero DM failure notice discarded"); - } else { - schedule_mesh_refresh(state); - } -} - -async fn set_session_zero_boundary( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - let account_hash = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let runtime = match state.session_zeros.runtime(session_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - let normalized_topic = request.topic.trim().to_lowercase(); - match runtime - .kernel - .command(SessionZeroCommand::SetBoundary { - actor_account_hash: account_hash, - expected_revision: request.expected_revision, - boundary_id: request.boundary_id, - topic: request.topic, - normalized_topic, - level: request.level, - }) - .await - { - Ok(result) => { - if let Err(error) = - mirror_contract_review_boundary_tightening(&state, &result.state).await - { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - schedule_mesh_refresh(&state); - Json(serde_json::json!({"revision":result.state.revision,"aggregate_boundaries":result.state.aggregate_boundaries})).into_response() - } - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - } -} - -async fn mirror_contract_review_boundary_tightening( - state: &AppState, - review: &SessionZeroState, -) -> anyhow::Result<()> { - let Some(campaign_id) = review.review_campaign_id else { - return Ok(()); - }; - let runtime = state.registry.runtime(campaign_id).await?; - let publication = runtime - .store - .load::( - "session_zero_publication.v1", - &campaign_id.to_string(), - )? - .map(|(_, value)| value) - .ok_or_else(|| anyhow::anyhow!("campaign publication state is missing"))?; - let existing = runtime - .store - .load::( - "active_contract_boundary_policy.v1", - &campaign_id.to_string(), - )?; - let mut strictest = - BTreeMap::::new(); - for boundary in publication - .approved_brief - .aggregate_boundaries - .iter() - .chain( - existing - .as_ref() - .into_iter() - .flat_map(|(_, policy)| policy.aggregate_boundaries.iter()), - ) - .chain(review.aggregate_boundaries.iter()) - { - let severity = |level: &BoundaryLevel| match level { - BoundaryLevel::AskFirst => 1, - BoundaryLevel::Veil => 2, - BoundaryLevel::Line => 3, - }; - let entry = strictest - .entry(boundary.normalized_topic.clone()) - .or_insert_with(|| boundary.clone()); - if severity(&boundary.level) > severity(&entry.level) { - *entry = boundary.clone(); - } - } - let policy = ghostlight_dungeon::session_zero::ActiveContractBoundaryPolicy { - schema: "ghostlight.active_contract_boundary_policy.v1".into(), - campaign_id, - review_session_zero_id: review.id, - aggregate_boundaries: strictest.into_values().collect(), - updated_at: chrono::Utc::now(), - }; - if let Some((row, _)) = existing { - runtime.store.replace( - &row, - "ghostlight.active_contract_boundary_policy.v1", - &policy, - )?; - } else { - runtime.store.insert( - "active_contract_boundary_policy.v1", - "ghostlight.active_contract_boundary_policy.v1", - &campaign_id.to_string(), - &policy, - )?; - } - Ok(()) -} - -async fn remove_session_zero_boundary( - Path((session_id, boundary_id)): Path<(uuid::Uuid, String)>, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - session_zero_simple_command(&headers, &state, session_id, |account_hash| { - SessionZeroCommand::RemoveBoundary { - actor_account_hash: account_hash, - expected_revision: request.expected_revision, - boundary_id, - } - }) - .await -} - -async fn leave_session_zero( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - session_zero_simple_command(&headers, &state, session_id, |account_hash| { - SessionZeroCommand::Leave { - actor_account_hash: account_hash, - expected_revision: request.expected_revision, - } - }) - .await -} - -async fn archive_session_zero( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - session_zero_simple_command(&headers, &state, session_id, |account_hash| { - SessionZeroCommand::Archive { - actor_account_hash: account_hash, - expected_revision: request.expected_revision, - } - }) - .await -} - -async fn remove_session_zero_member( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - session_zero_simple_command(&headers, &state, session_id, |account_hash| { - SessionZeroCommand::RemoveMember { - actor_account_hash: account_hash, - expected_revision: request.expected_revision, - member_id: request.member_id, - } - }) - .await -} - -async fn resolve_session_zero_decision( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - let account_hash = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let runtime = match state.session_zeros.runtime(session_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - if request.action == SessionZeroDecisionRequestAction::RetryCounter { - if request - .counter - .as_deref() - .is_some_and(|counter| !counter.trim().is_empty()) - { - return ( - StatusCode::BAD_REQUEST, - "a counter retry cannot include a new counterproposal", - ) - .into_response(); - } - let snapshot = match state.session_zeros.snapshot(session_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - let (channel_id, member_id) = match pending_counter_retry_target( - &snapshot, - &account_hash, - request.expected_revision, - &request.decision_id, - ) { - Ok(value) => value, - Err(error) => return (StatusCode::CONFLICT, error.to_string()).into_response(), - }; - schedule_session_zero_dm_response( - &state, - &runtime, - snapshot.clone(), - channel_id, - member_id, - Some(request.decision_id.clone()), - ); - return ( - StatusCode::ACCEPTED, - Json(serde_json::json!({ - "schema":"ghostlight.session_zero_progress.v1", - "session_zero_id":session_id, - "revision":snapshot.revision, - "status":"counter_retry_started", - "message":"Ghostlight started a revision-bound retry from the persisted counterproposal; no Session Zero state changed.", - })), - ) - .into_response(); - } - let resolution = match request.action { - SessionZeroDecisionRequestAction::Accept => SessionZeroDecisionResolution::Accept, - SessionZeroDecisionRequestAction::Decline => SessionZeroDecisionResolution::Decline, - SessionZeroDecisionRequestAction::Counter => SessionZeroDecisionResolution::Counter, - SessionZeroDecisionRequestAction::RetryCounter => unreachable!("retry returned above"), - }; - let decision_id = request.decision_id.clone(); - let accepted = resolution == SessionZeroDecisionResolution::Accept; - match runtime - .kernel - .command(SessionZeroCommand::ResolveDecision { - actor_account_hash: account_hash, - expected_revision: request.expected_revision, - decision_id: request.decision_id, - resolution, - counter: request.counter, - }) - .await - { - Ok(result) => { - if resolution == SessionZeroDecisionResolution::Counter - && let Some(decision) = result.state.decisions.get(&decision_id) - && decision.pending_counter.is_some() - { - let member_id = decision.owner_member_id.clone(); - let channel_id = member_id - .as_ref() - .map(|owner| format!("private:{owner}")) - .unwrap_or_else(|| "shared:table".into()); - schedule_session_zero_dm_response( - &state, - &runtime, - result.state.clone(), - channel_id, - member_id, - Some(decision_id.clone()), - ); - } - if accepted - && let Some(opening) = accepted_opening_suggestion(&result.state, &decision_id) - && let Ok(compiler) = - compiler_for_vault(&state.compiler, &result.state.contract.vault_provider) - { - let role_runtime = runtime.clone(); - let role_state = state.clone(); - let role_snapshot = result.state.clone(); - tokio::spawn(async move { - if let Err(error) = run_live_model_work( - &role_state, - populate_role_suggestions( - compiler, - role_runtime, - role_snapshot, - opening, - role_state.clone(), - ), - ) - .await - { - tracing::warn!(%error, "inline Session Zero role suggestions failed without draft mutation"); - } - }); - } - schedule_mesh_refresh(&state); - Json(serde_json::json!({"revision":result.state.revision,"decisions":result.state.decisions})).into_response() - } - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - } -} - -fn pending_counter_retry_target( - snapshot: &SessionZeroState, - account_hash: &str, - expected_revision: u64, - decision_id: &str, -) -> anyhow::Result<(String, Option)> { - if snapshot.revision != expected_revision { - anyhow::bail!( - "stale Session Zero revision: expected {}, current {}", - expected_revision, - snapshot.revision - ); - } - let member = snapshot - .member_for_account(account_hash) - .ok_or_else(|| anyhow::anyhow!("session member is missing"))?; - let decision = snapshot - .decisions - .get(decision_id) - .ok_or_else(|| anyhow::anyhow!("decision is missing"))?; - if decision.resolved { - anyhow::bail!("decision is already resolved"); - } - if decision.pending_counter.is_none() { - anyhow::bail!("decision has no pending counterproposal to retry"); - } - if decision - .owner_member_id - .as_deref() - .is_some_and(|owner| owner != member.id) - { - anyhow::bail!("decision belongs to another member"); - } - let member_id = decision.owner_member_id.clone(); - let channel_id = member_id - .as_ref() - .map(|owner| format!("private:{owner}")) - .unwrap_or_else(|| "shared:table".into()); - if !snapshot.channels.contains_key(&channel_id) { - anyhow::bail!("counterproposal channel is missing"); - } - Ok((channel_id, member_id)) -} - -async fn lock_session_zero_roster( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - session_zero_simple_command(&headers, &state, session_id, |account_hash| { - SessionZeroCommand::LockRoster { - actor_account_hash: account_hash, - expected_revision: request.expected_revision, - } - }) - .await -} - -async fn compile_session_zero( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - let account_hash = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let runtime = match state.session_zeros.runtime(session_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - let started = match runtime - .kernel - .command(SessionZeroCommand::BeginCompilation { - actor_account_hash: account_hash, - expected_revision: request.expected_revision, - }) - .await - { - Ok(value) => value, - Err(error) => return (StatusCode::CONFLICT, error.to_string()).into_response(), - }; - let brief = match started.state.compilation_brief() { - Ok(value) => value, - Err(error) => return (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response(), - }; - let expected_revision = started.state.revision; - if let Some(campaign_id) = started.state.review_campaign_id { - let campaign_runtime = match state.registry.runtime(campaign_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - let campaign = match load_campaign(&campaign_runtime.store) { - Ok(value) => value, - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - if Some(campaign.revision) != started.state.review_world_revision { - let _ = runtime - .kernel - .command(SessionZeroCommand::CompilationFailed { - expected_revision, - message: "The world changed during Contract Review. Start a fresh review against the current revision.".into(), - }) - .await; - return ( - StatusCode::CONFLICT, - "contract review world revision is stale", - ) - .into_response(); - } - let evidence_receipts = campaign_runtime - .store - .load_all::( - "vault_evidence_receipt.v1", - ) - .unwrap_or_default(); - let preview = ghostlight_dungeon::domain::WorldCompilePreview { - schema: "ghostlight.world_compile_preview.v1".into(), - title: format!("{} — Contract Review", campaign.name), - campaign, - evidence_receipts, - evidence_coverage: vec![], - gaps: vec![], - branch_assumptions: vec![ - "Contract Review amends forward-looking governance and approved character projections; established events, canon, knowledge, and geometry remain unchanged.".into(), - ], - requires_approval: true, - }; - return match runtime - .kernel - .command(SessionZeroCommand::InstallPreview { - expected_revision, - preview, - model_receipts: vec![], - }) - .await - { - Ok(result) => { - schedule_mesh_refresh(&state); - ( - StatusCode::ACCEPTED, - Json(serde_json::json!({ - "schema":"ghostlight.session_zero_progress.v1", - "session_zero_id":session_id, - "revision":result.state.revision, - "status":"review" - })), - ) - .into_response() - } - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - }; - } - let compiler = match compiler_for_vault(&state.compiler, &brief.contract.vault_provider) { - Ok(compiler) => compiler, - Err(error) => { - return (StatusCode::SERVICE_UNAVAILABLE, error.to_string()).into_response(); - } - }; - let kernel = runtime.kernel.clone(); - let mesh_state = state.clone(); - tokio::spawn(async move { - match run_live_model_work(&mesh_state, compiler.compile_approved_brief(&brief)).await { - Ok((preview, receipts)) => { - if let Err(error) = kernel - .command(SessionZeroCommand::InstallPreview { - expected_revision, - preview, - model_receipts: receipts, - }) - .await - { - tracing::info!(%error, "stale Session Zero compilation discarded"); - } else { - schedule_mesh_refresh(&mesh_state); - } - } - Err(error) => { - tracing::warn!(%error, "Session Zero compilation failed before preview publication"); - let result = if ghostlight_dungeon::vault::is_vault_unavailable(&error) { - kernel - .command(SessionZeroCommand::CompilationEvidenceUnavailable { - expected_revision, - }) - .await - } else { - kernel - .command(SessionZeroCommand::CompilationFailed { - expected_revision, - message: error.to_string(), - }) - .await - }; - if let Err(commit_error) = result { - tracing::info!(%commit_error, "stale Session Zero compiler failure discarded"); - } else { - schedule_mesh_refresh(&mesh_state); - } - } - } - }); - ( - StatusCode::ACCEPTED, - Json(serde_json::json!({ - "schema":"ghostlight.session_zero_progress.v1", - "session_zero_id":session_id, - "revision":expected_revision, - "status":"compiling" - })), - ) - .into_response() -} - -async fn approve_session_zero( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - session_zero_simple_command(&headers, &state, session_id, |account_hash| { - SessionZeroCommand::Approve { - actor_account_hash: account_hash, - expected_revision: request.expected_revision, - } - }) - .await -} - -async fn review_session_zero_compilation_gaps( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - session_zero_simple_command(&headers, &state, session_id, |account_hash| { - SessionZeroCommand::ReviewCompilationGaps { - actor_account_hash: account_hash, - expected_revision: request.expected_revision, - } - }) - .await -} - -async fn discard_session_zero_preview( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - session_zero_simple_command(&headers, &state, session_id, |account_hash| { - SessionZeroCommand::DiscardPreview { - actor_account_hash: account_hash, - expected_revision: request.expected_revision, - } - }) - .await -} - -async fn publish_session_zero( - Path(session_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - let account_hash = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let runtime = match state.session_zeros.runtime(session_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - let snapshot = match state.session_zeros.snapshot(session_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - if snapshot.revision != request.expected_revision { - return (StatusCode::CONFLICT, "stale Session Zero revision").into_response(); - } - if let Some(campaign_id) = snapshot.published_campaign_id { - return Json(serde_json::json!({"campaign_id":campaign_id,"status":"published"})) - .into_response(); - } - let member = match snapshot.member_for_account(&account_hash) { - Some(value) if value.is_host => value, - _ => return StatusCode::FORBIDDEN.into_response(), - }; - if let Some(campaign_id) = snapshot.review_campaign_id { - let campaign_runtime = match state.registry.runtime(campaign_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - let existing_publication = campaign_runtime - .store - .load::( - "session_zero_publication.v1", - &campaign_id.to_string(), - ) - .ok() - .flatten() - .map(|(_, value)| value); - let review_result = if existing_publication - .as_ref() - .is_some_and(|publication| publication.session_zero_id == snapshot.id) - { - let publication = existing_publication.unwrap(); - Ok(( - publication.approved_seed_digest, - publication - .membership - .members - .values() - .map(|member| member.account_hash.clone()) - .collect::>(), - )) - } else { - commit_contract_review(&campaign_runtime, &snapshot) - }; - let (seed_digest, member_accounts) = match review_result { - Ok(value) => value, - Err(error) => return (StatusCode::CONFLICT, error.to_string()).into_response(), - }; - for member_account in member_accounts { - if let Err(error) = select_campaign(&state, &member_account, campaign_id).await { - tracing::warn!(%error, %campaign_id, "contract-review campaign selection failed"); - } - } - return match runtime - .kernel - .command(SessionZeroCommand::MarkPublished { - actor_account_hash: member.account_hash.clone(), - expected_revision: snapshot.revision, - campaign_id, - seed_digest, - }) - .await - { - Ok(_) => { - if let Err(error) = refresh_mesh(&state).await { - tracing::warn!(%error, "Contract Review mesh refresh failed"); - } - Json(serde_json::json!({"campaign_id":campaign_id,"status":"contract_updated"})) - .into_response() - } - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - }; - } - let Some(preview) = snapshot.preview.clone() else { - return (StatusCode::CONFLICT, "final preview is missing").into_response(); - }; - let publication = match publication_from_session(&snapshot, preview.campaign.id) { - Ok(value) => value, - Err(error) => return (StatusCode::CONFLICT, error.to_string()).into_response(), - }; - let seed_digest = publication.approved_seed_digest.clone(); - let member_accounts = publication - .membership - .members - .values() - .map(|value| value.account_hash.clone()) - .collect::>(); - let campaign_id = preview.campaign.id; - let published = state - .registry - .publish_session_zero( - preview.campaign, - preview.evidence_receipts, - snapshot.preview_model_receipts.clone(), - publication, - ) - .await; - if let Err(error) = published { - return (StatusCode::CONFLICT, error.to_string()).into_response(); - } - for member_account in member_accounts { - if let Err(error) = select_campaign(&state, &member_account, campaign_id).await { - tracing::warn!(%error, %campaign_id, "published member campaign selection failed"); - } - } - match runtime - .kernel - .command(SessionZeroCommand::MarkPublished { - actor_account_hash: member.account_hash.clone(), - expected_revision: snapshot.revision, - campaign_id, - seed_digest, - }) - .await - { - Ok(_) => { - if let Err(error) = refresh_mesh(&state).await { - tracing::warn!(%error, "Session Zero publication mesh refresh failed"); - } - Json(serde_json::json!({"campaign_id":campaign_id,"status":"published"})) - .into_response() - } - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - } -} - -fn commit_contract_review( - runtime: &CampaignRuntime, - snapshot: &SessionZeroState, -) -> anyhow::Result<(String, Vec)> { - let campaign_id = snapshot - .review_campaign_id - .ok_or_else(|| anyhow::anyhow!("not a Contract Review"))?; - let (campaign_row, mut campaign) = runtime - .store - .load::("campaign.v1", &campaign_id.to_string())? - .ok_or_else(|| anyhow::anyhow!("reviewed campaign vanished"))?; - if Some(campaign.revision) != snapshot.review_world_revision { - anyhow::bail!( - "the world changed after Contract Review began; start a fresh review against revision {}", - campaign.revision - ); - } - let (_, baseline_membership) = runtime - .store - .load::( - "campaign_membership.v1", - &campaign_id.to_string(), - )? - .ok_or_else(|| anyhow::anyhow!("campaign membership vanished"))?; - let (_, baseline_contract) = runtime - .store - .load::( - "campaign_contract.v1", - &campaign_id.to_string(), - )? - .ok_or_else(|| anyhow::anyhow!("campaign contract vanished"))?; - if snapshot.contract.vault_provider != baseline_contract.vault_provider - || snapshot.contract.canon_horizon != baseline_contract.canon_horizon - || snapshot.contract.starting_where != baseline_contract.starting_where - || snapshot.contract.starting_when != baseline_contract.starting_when - { - anyhow::bail!( - "Contract Review cannot rewrite the Vault, canon horizon, starting time, or established geometry" - ); - } - let mut publication = publication_from_session(snapshot, campaign_id)?; - let baseline_bindings = baseline_membership - .members - .iter() - .map(|(id, member)| (id, (&member.account_hash, &member.actor_id, member.active))) - .collect::>(); - let proposed_bindings = publication - .membership - .members - .iter() - .map(|(id, member)| (id, (&member.account_hash, &member.actor_id, member.active))) - .collect::>(); - if baseline_bindings != proposed_bindings - || baseline_membership.host_member_id != publication.membership.host_member_id - { - anyhow::bail!("Contract Review cannot change campaign membership or actor custody"); - } - for draft in &publication.approved_brief.characters { - if draft.relationships.keys().any(|target| { - !campaign.actors.contains_key(target) - && !campaign.institutions.contains_key(target) - && !campaign.gestalts.contains_key(target) - }) { - anyhow::bail!("character amendment cites an unknown relationship target"); - } - let actor = campaign - .actors - .get_mut(&draft.actor_id) - .ok_or_else(|| anyhow::anyhow!("approved character actor vanished"))?; - actor.name = draft.name.clone(); - actor.capabilities = draft.capabilities.iter().cloned().collect(); - actor.equipment = draft.equipment.iter().cloned().collect(); - actor.conditions = draft.vulnerabilities.iter().cloned().collect(); - actor.obligations = draft.obligations.iter().cloned().collect(); - actor.relationships = draft.relationships.clone(); - actor.goals = draft.goals.clone(); - // Location, knowledge, and memories are established world/history state. - // The review draft may discuss them, but this command cannot rewrite them. - } - let next_governance_epoch = baseline_membership.governance_epoch.saturating_add(1); - publication.membership.governance_epoch = next_governance_epoch; - publication.governance.governance_epoch = next_governance_epoch; - publication.approved_seed_digest = ghostlight_dungeon::session_zero::seed_digest(&( - campaign_id, - &publication.approved_brief, - &publication.membership, - &publication.governance, - &publication.contract, - &publication.dm_persona, - &publication.boundaries, - ))?; - let previous_revision = campaign.revision; - campaign.revision = campaign.revision.saturating_add(1); - campaign.events.push(ghostlight_dungeon::domain::Event { - id: format!("contract-review:{}", campaign.revision), - at: campaign.world_time, - kind: "contract_review".into(), - summary: "The table unanimously adopts a revised campaign contract.".into(), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec![], - public_channels: vec![], - }); - let receipt = ghostlight_dungeon::domain::WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id, - previous_revision, - revision: campaign.revision, - command_kind: "unanimous_contract_review".into(), - committed_at: chrono::Utc::now(), - roll: None, - }; - runtime - .store - .commit_contract_review(&campaign_row, &campaign, &publication, &receipt)?; - Ok(( - publication.approved_seed_digest, - publication - .membership - .members - .values() - .map(|member| member.account_hash.clone()) - .collect(), - )) -} - -async fn session_zero_simple_command( - headers: &HeaderMap, - state: &AppState, - session_id: uuid::Uuid, - make: impl FnOnce(String) -> SessionZeroCommand, -) -> Response { - let account_hash = match authenticated_session(headers, state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let runtime = match state.session_zeros.runtime(session_id).await { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - match runtime.kernel.command(make(account_hash.clone())).await { - Ok(result) => { - schedule_mesh_refresh(state); - match session_zero_surface(&result.state, &account_hash) { - Ok(surface) => Json(surface).into_response(), - Err(error) => { - (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response() - } - } - } - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - } -} - -async fn surface( - headers: HeaderMap, - State(state): State, - invite: Option<&str>, -) -> Response { - let session = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - match state - .session_zeros - .active_contract_review_for_account(&session) - .await - { - Ok(Some(id)) => { - let projected = match state.session_zeros.snapshot(id).await { - Ok(snapshot) => { - session_zero_surface_with_campaign_choices(&state, &snapshot, &session).await - } - Err(error) => Err(error), - }; - return match projected { - Ok(surface) => Json(surface).into_response(), - Err(error) => { - (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response() - } - }; - } - Ok(None) => {} - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - } - let runtime = match session_runtime(&state, &session).await { - Ok(Some(value)) => value, - Ok(None) => { - return match state.session_zeros.session_for_account(&session).await { - Ok(Some(id)) => { - let projected = match state.session_zeros.snapshot(id).await { - Ok(snapshot) => { - session_zero_surface_with_campaign_choices(&state, &snapshot, &session) - .await - } - Err(error) => Err(error), - }; - match projected { - Ok(surface) => Json(surface).into_response(), - Err(error) => { - (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response() - } - } - } - Ok(None) => match session_zero_entry_surface(&state, &session, invite).await { - Ok(surface) => Json(surface).into_response(), - Err(error) => { - (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response() - } - }, - Err(error) => { - (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response() - } - }; - } - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - match load_campaign(&runtime.store) { - Ok(campaign) => { - let viewer_actor_id = - match campaign_member_for_account(&runtime.store, &campaign, &session) { - Ok(value) => value.actor_id, - Err(error) => { - return (StatusCode::FORBIDDEN, error.to_string()).into_response(); - } - }; - let mut projected = player_surface_for_actor(&campaign, &viewer_actor_id); - if let Ok(Some((_, membership))) = runtime - .store - .load::( - "campaign_membership.v1", - &campaign.id.to_string(), - ) { - let viewer_member_id = membership - .member_for_account(&session) - .map(|member| member.member_id.clone()); - let time_proposals = runtime - .store - .load_all::( - "time_advance_proposal.v1", - ) - .unwrap_or_default() - .into_iter() - .filter(|proposal| { - !proposal.committed && proposal.expected_world_revision == campaign.revision - }) - .collect::>(); - let travel_proposals = runtime - .store - .load_all::( - "group_travel_proposal.v1", - ) - .unwrap_or_default() - .into_iter() - .filter(|proposal| { - !proposal.committed && proposal.expected_world_revision == campaign.revision - }) - .collect::>(); - let cell_budget_proposals = runtime - .store - .load_all::( - "cell_budget_proposal.v1", - ) - .unwrap_or_default() - .into_iter() - .filter(|proposal| { - !proposal.committed - && proposal.expected_world_revision == campaign.revision - && proposal.expected_resolution_epoch - == campaign.resolution_policy.resolution_epoch - }) - .collect::>(); - projected["governance"] = serde_json::json!({ - "viewer_member_id":viewer_member_id, - "active_member_count":membership.members.values().filter(|member|member.active).count(), - "pooled_cell_allowance":membership.pooled_cell_allowance(), - "time_proposals":time_proposals, - "travel_proposals":travel_proposals, - "cell_budget_proposals":cell_budget_proposals, - }); - if let Some(children) = projected - .pointer_mut("/surface/root/children") - .and_then(serde_json::Value::as_array_mut) - { - for proposal in &time_proposals { - children.push(eve_button( - &format!("governance.time.approve.{}", proposal.id), - &format!("Approve time advance: {} minutes", proposal.minutes), - "governance.time.approve", - serde_json::json!({"expected_revision":campaign.revision,"proposal_id":proposal.id}), - &[], - )); - } - for proposal in &travel_proposals { - children.push(eve_button( - &format!("governance.travel.approve.{}", proposal.id), - "Approve group travel", - "governance.travel.approve", - serde_json::json!({"expected_revision":campaign.revision,"proposal_id":proposal.id}), - &[], - )); - } - for proposal in &cell_budget_proposals { - children.push(eve_button( - &format!("governance.cells.approve.{}", proposal.id), - &format!("Approve Persona-cell budget {}", proposal.active_cell_budget), - "governance.cells.approve", - serde_json::json!({"expected_revision":campaign.revision,"proposal_id":proposal.id}), - &[], - )); - } - } - } - Json(projected).into_response() - } - Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), - } -} - -async fn session_zero_entry_surface( - state: &AppState, - account_hash: &str, - invite: Option<&str>, -) -> anyhow::Result { - let campaign_choices = campaign_choice_components_for_account(state, account_hash).await?; - let vault_options = bundled_vault_manifests() - .into_iter() - .map(|manifest| { - serde_json::json!({ - "id":format!("entry.vault.option.{}", manifest.id), - "kind":"control.option", - "props":{"value":manifest.id,"label":manifest.title}, - "children":[] - }) - }) - .collect::>(); - let mut children = vec![ - serde_json::json!({"id":"entry.intro","kind":"card","props":{"title":"Begin Session Zero"},"children":[ - {"id":"entry.intro.text","kind":"text","props":{"value":"Build the campaign with the DM before the world becomes canonical. Tone, boundaries, characters, evidence gaps, and opening pressure remain negotiable until everyone approves."},"children":[]} - ]}), - serde_json::json!({"id":"entry.name","kind":"control.input.text","props":{"label":"Draft name","placeholder":"The campaign you are about to regret caring about"},"stateBindings":[eve_local_draft("name","string")],"children":[]}), - serde_json::json!({"id":"entry.vault","kind":"control.select","props":{"label":"Lore Vault","value":"aetheria"},"stateBindings":[eve_local_draft("vault_provider","choice")],"children":vault_options}), - serde_json::json!({"id":"entry.display-name","kind":"control.input.text","props":{"label":"Your display name"},"stateBindings":[eve_local_draft("display_name","string")],"children":[]}), - eve_button( - "entry.begin", - "Begin Session Zero", - "session_zero.begin", - serde_json::json!({}), - &["name", "vault_provider", "display_name"], - ), - serde_json::json!({"id":"entry.join-heading","kind":"text.title","props":{"value":"Join a table"},"children":[]}), - serde_json::json!({"id":"entry.invite","kind":"control.input.text","props":{"label":"Invitation token","value":invite.unwrap_or_default()},"stateBindings":[eve_local_draft("invite_token","string")],"children":[]}), - serde_json::json!({"id":"entry.join-name","kind":"control.input.text","props":{"label":"Your display name"},"stateBindings":[eve_local_draft("display_name","string")],"children":[]}), - eve_button( - "entry.join", - "Join Session Zero", - "session_zero.join", - serde_json::json!({}), - &["invite_token", "display_name"], - ), - ]; - if !campaign_choices.is_empty() { - children.push(serde_json::json!({"id":"entry.campaigns","kind":"card","props":{"title":"Your campaigns"},"children":campaign_choices})); - } - children.push(eve_button( - "entry.logout", - "Sign out", - "app.auth.logout", - serde_json::json!({}), - &[], - )); - Ok(serde_json::json!({ - "type":"surface-state","schema":"gamecult.eve.surface.v1","providerId":EVE_PROVIDER_ID,"providerKind":"narrative.session-zero-entry", - "title":"Ghostlight Dungeon","version":0,"updatedAtUtc":Utc::now().to_rfc3339(), - "surface":{"id":EVE_SURFACE_ID,"root":{"id":"entry.root","kind":"surface","props":{},"children":children},"styles":{"tokens":{"colorBackground":"#0c1110","colorPanel":"#17201d","colorText":"#e8e1cf","colorMuted":"#9aa69f","colorAccent":"#d49b58"}}}, - "commands":[ - eve_command_descriptor("session_zero.begin","ghostlight.session_zero_begin.v1", &["name","vault_provider","display_name"], "SessionZeroKernel"), - eve_command_descriptor("session_zero.join","ghostlight.session_zero_join.v1", &["invite_token","display_name"], "SessionZeroKernel"), - eve_command_descriptor("campaign.select","ghostlight.campaign_select.v1", &[], "campaign_membership.v1"), - eve_command_descriptor("app.auth.logout","ghostlight.app_logout.v1", &[], "ghostlight.app_session.v1") - ] - })) -} - -async fn session_zero_surface_with_campaign_choices( - state: &AppState, - session_zero: &SessionZeroState, - account_hash: &str, -) -> anyhow::Result { - let mut surface = session_zero_surface(session_zero, account_hash)?; - let choices = campaign_choice_components_for_account(state, account_hash).await?; - append_campaign_choices(&mut surface, choices)?; - Ok(surface) -} - -async fn campaign_choice_components_for_account( - state: &AppState, - account_hash: &str, -) -> anyhow::Result> { - let mut campaigns = Vec::new(); - for id in state.registry.list().await { - let runtime = state.registry.runtime(id).await?; - let campaign = load_campaign(&runtime.store)?; - if campaign_member_for_account(&runtime.store, &campaign, account_hash).is_ok() { - campaigns.push((id, campaign.name)); - } - } - campaigns.sort_by(|left, right| left.1.cmp(&right.1).then(left.0.cmp(&right.0))); - Ok(campaign_choice_components(campaigns)) -} - -fn campaign_choice_components( - campaigns: impl IntoIterator, -) -> Vec { - campaigns - .into_iter() - .map(|(id, name)| { - serde_json::json!({ - "id":format!("campaign-choice:{id}"), - "kind":"control.button", - "props":{ - "label":format!("Continue {name}"), - "command":"campaign.select", - "action":{"command":"campaign.select","campaign_id":id} - }, - "children":[] - }) - }) - .collect() -} - -fn append_campaign_choices( - surface: &mut serde_json::Value, - campaign_choices: Vec, -) -> anyhow::Result<()> { - if campaign_choices.is_empty() { - return Ok(()); - } - surface - .pointer_mut("/surface/root/children") - .and_then(serde_json::Value::as_array_mut) - .ok_or_else(|| anyhow::anyhow!("Session Zero surface has no root children"))? - .push(serde_json::json!({ - "id":"session-zero.campaigns", - "kind":"card", - "props":{"title":"Your existing campaigns"}, - "children":campaign_choices - })); - let commands = surface - .get_mut("commands") - .and_then(serde_json::Value::as_array_mut) - .ok_or_else(|| anyhow::anyhow!("Session Zero surface has no command catalog"))?; - if !commands.iter().any(|command| { - command.get("command").and_then(serde_json::Value::as_str) == Some("campaign.select") - }) { - commands.push(eve_command_descriptor( - "campaign.select", - "ghostlight.campaign_select.v1", - &[], - "campaign_membership.v1", - )); - } - Ok(()) -} - -fn eve_local_draft(name: &str, value_kind: &str) -> serde_json::Value { - serde_json::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 eve_button( - id: &str, - label: &str, - command: &str, - action: serde_json::Value, - bindings: &[&str], -) -> serde_json::Value { - let mut action = action.as_object().cloned().unwrap_or_default(); - action.insert("command".into(), serde_json::Value::String(command.into())); - serde_json::json!({"id":id,"kind":"control.button","props":{"label":label,"command":command,"action":action,"captureBindings":bindings},"children":[]}) -} - -fn eve_command_descriptor( - command: &str, - payload_schema: &str, - bindings: &[&str], - authority: &str, -) -> serde_json::Value { - serde_json::json!({"schema":"gamecult.eve.command.v1","command":command,"payloadSchema":payload_schema,"captureBindings":bindings,"transport":"https-json","authority":authority}) -} - -async fn revision_events(headers: HeaderMap, State(state): State) -> Response { - let account_hash = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let stream = async_stream::stream! { - let mut interval = tokio::time::interval(std::time::Duration::from_secs(2)); - interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - let mut previous = None::; - loop { - interval.tick().await; - let notice = match session_runtime(&state, &account_hash).await { - Ok(Some(runtime)) => load_campaign(&runtime.store).ok().map(|campaign| { - serde_json::json!({ - "kind":"campaign", - "id":campaign.id, - "revision":campaign.revision, - "resolution_epoch":campaign.resolution_policy.resolution_epoch, - "provider_configuration_epoch":campaign.resolution_policy.provider_configuration_epoch, - }) - }), - Ok(None) => match state.session_zeros.session_for_account(&account_hash).await { - Ok(Some(id)) => state.session_zeros.snapshot(id).await.ok().map(|session| { - serde_json::json!({"kind":"session_zero","id":id,"revision":session.revision}) - }), - _ => Some(serde_json::json!({"kind":"entry","revision":0})), - }, - Err(_) => None, - }; - let Some(notice) = notice else { continue }; - let encoded = notice.to_string(); - if previous.as_deref() == Some(encoded.as_str()) { - continue; - } - previous = Some(encoded.clone()); - yield Ok::(SseEvent::default().event("revision").data(encoded)); - } - }; - Sse::new(stream) - .keep_alive( - KeepAlive::new() - .interval(std::time::Duration::from_secs(15)) - .text("revision-heartbeat"), - ) - .into_response() -} - -#[derive(Deserialize)] -struct DestinationRequest { - origin_location_id: String, - destination: String, -} - -async fn compile_destination( - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - let session = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let _live = LiveTurnGuard::enter(&state).await; - let runtime = match session_runtime(&state, &session).await { - Ok(Some(value)) => value, - Ok(None) => { - return (StatusCode::NOT_FOUND, "session has no selected campaign").into_response(); - } - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let campaign = match load_campaign(&runtime.store) { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - let vault_id = match campaign_vault_id(&runtime.store, campaign.id) { - Ok(value) => value, - Err(error) => return (StatusCode::CONFLICT, error.to_string()).into_response(), - }; - let compiler = match compiler_for_vault(&state.compiler, &vault_id) { - Ok(value) => value, - Err(error) => { - return (StatusCode::SERVICE_UNAVAILABLE, error.to_string()).into_response(); - } - }; - match compiler - .compile_destination(&campaign, &request.origin_location_id, &request.destination) - .await - { - Ok((preview, model_receipts)) => { - let id = uuid::Uuid::new_v4().to_string(); - let mut previews = state.expansion_previews.lock().await; - previews.retain(|_, existing| existing.session_hash != session); - previews.insert( - id.clone(), - OwnedPreview { - session_hash: session, - value: preview.clone(), - model_receipts: model_receipts.clone(), - }, - ); - Json(serde_json::json!({ - "preview_id":id, - "preview":destination_compilation_preview_projection(&preview), - })) - .into_response() - } - Err(error) => { - if let Some(failure) = error.downcast_ref::() - && let Err(persistence_error) = runtime - .store - .persist_model_stage_receipts(&failure.model_receipts) - { - return ( - StatusCode::INTERNAL_SERVER_ERROR, - format!( - "{}; model-receipt persistence failed: {persistence_error}", - failure.message - ), - ) - .into_response(); - } - (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response() - } - } -} - -async fn approve_destination( - Path(preview_id): Path, - headers: HeaderMap, - State(state): State, -) -> Response { - let session = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let mut previews = state.expansion_previews.lock().await; - let Some(owned) = previews.get(&preview_id).cloned() else { - return (StatusCode::NOT_FOUND, "preview missing or already consumed").into_response(); - }; - if owned.session_hash != session { - return StatusCode::FORBIDDEN.into_response(); - } - previews.remove(&preview_id); - drop(previews); - let preview = owned.value; - let model_receipts = owned.model_receipts; - let runtime = match session_runtime(&state, &session).await { - Ok(Some(value)) => value, - Ok(None) => { - return (StatusCode::NOT_FOUND, "session has no selected campaign").into_response(); - } - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let command = match preview { - DestinationCompilationPreview::RegionExpansion(preview) => WorldCommand::ExpandRegion { - expected_revision: preview.expected_revision, - expansion: preview.expansion, - evidence_receipts: preview.evidence_receipts, - canon_candidates: preview.canon_candidates, - model_stage_receipts: model_receipts, - }, - DestinationCompilationPreview::LocalityElaboration(preview) => { - WorldCommand::ElaborateLocality { - expected_revision: preview.expected_revision, - elaboration: preview.elaboration, - evidence_receipts: preview.evidence_receipts, - canon_candidates: preview.canon_candidates, - model_stage_receipts: model_receipts, - } - } - }; - match runtime.kernel.command(command).await { - Ok(value) => Json(player_command_projection(&value)).into_response(), - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - } -} - -async fn compile_fission( - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - let session = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let _live = LiveTurnGuard::enter(&state).await; - let runtime = match session_runtime(&state, &session).await { - Ok(Some(value)) => value, - Ok(None) => { - return (StatusCode::NOT_FOUND, "session has no selected campaign").into_response(); - } - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let campaign = match load_campaign(&runtime.store) { - Ok(value) => value, - Err(error) => return (StatusCode::NOT_FOUND, error.to_string()).into_response(), - }; - let vault_id = match campaign_vault_id(&runtime.store, campaign.id) { - Ok(value) => value, - Err(error) => return (StatusCode::CONFLICT, error.to_string()).into_response(), - }; - let compiler = match compiler_for_vault(&state.compiler, &vault_id) { - Ok(value) => value, - Err(error) => { - return (StatusCode::SERVICE_UNAVAILABLE, error.to_string()).into_response(); - } - }; - match compiler.compile_fission(&campaign, request).await { - Ok((preview, evidence_receipts, model_receipts)) => { - let id = uuid::Uuid::new_v4().to_string(); - let mut previews = state.fission_previews.lock().await; - previews.retain(|_, existing| existing.session_hash != session); - previews.insert( - id.clone(), - OwnedFissionPreview { - session_hash: session, - value: preview.clone(), - evidence_receipts, - model_receipts: model_receipts.clone(), - }, - ); - Json(serde_json::json!({ - "preview_id":id, - "preview":gestalt_fission_preview_projection(&preview), - })) - .into_response() - } - Err(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response(), - } -} - -async fn approve_fission( - Path(preview_id): Path, - headers: HeaderMap, - State(state): State, -) -> Response { - let session = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let _live = LiveTurnGuard::enter(&state).await; - let mut previews = state.fission_previews.lock().await; - let Some(owned) = previews.get(&preview_id).cloned() else { - return (StatusCode::NOT_FOUND, "preview missing or already consumed").into_response(); - }; - if owned.session_hash != session { - return StatusCode::FORBIDDEN.into_response(); - } - previews.remove(&preview_id); - drop(previews); - let runtime = match session_runtime(&state, &session).await { - Ok(Some(value)) => value, - Ok(None) => { - return (StatusCode::NOT_FOUND, "session has no selected campaign").into_response(); - } - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - match runtime - .kernel - .command(WorldCommand::FissionGestalt { - expected_revision: owned.value.expected_world_revision, - preview: owned.value, - evidence_receipts: owned.evidence_receipts, - model_stage_receipts: owned.model_receipts, - }) - .await - { - Ok(value) => { - if let Err(error) = refresh_mesh(&state).await { - tracing::warn!(%error, "gestalt fission CultMesh publication failed"); - } - Json(player_command_projection(&value)).into_response() - } - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - } -} - -async fn resolve_npc_initiative( - state: &AppState, - runtime: &CampaignRuntime, - campaign: &Campaign, -) -> anyhow::Result { - if !has_current_npc_initiative(campaign) { - return Ok(true); - } - let Some(proposal) = ghostlight_dungeon::initiative::winner(&campaign.pending_world_proposals) - else { - return Ok(true); - }; - let current = load_campaign(&runtime.store)?; - if current.revision != campaign.revision - || !has_current_npc_initiative(¤t) - || ghostlight_dungeon::initiative::winner(¤t.pending_world_proposals) - != Some(proposal.clone()) - { - return Ok(true); - } - let assessor = state - .assessor - .as_ref() - .ok_or_else(|| anyhow::anyhow!("NPC initiative requires the action assessor"))?; - let intent = ActionIntent { - actor_id: proposal.actor_id.clone(), - description: proposal.intent.clone(), - intended_effect: proposal.intended_effect.clone(), - }; - let (contract, boundaries) = campaign_model_policy(&runtime.store, current.id); - let permissions = runtime - .store - .load::( - "campaign_membership.v1", - ¤t.id.to_string(), - )? - .and_then(|(_, membership)| { - membership - .extraordinary_permissions - .get(&intent.actor_id) - .cloned() - }) - .unwrap_or_default(); - let Some((assessment, receipt)) = await_background_work( - state, - true, - assessor.assess_with_context_cached( - &runtime.store, - ¤t, - intent, - &permissions, - contract.as_ref(), - &boundaries, - ), - ) - .await? - else { - return Ok(false); - }; - if state.live_turns.load(Ordering::SeqCst) > 0 { - return Ok(false); - } - let _background_commit = match state.live_commit_gate.clone().try_write_owned() { - Ok(guard) => guard, - Err(_) => return Ok(false), - }; - if state.live_turns.load(Ordering::SeqCst) > 0 { - return Ok(false); - } - let _ = runtime.store.insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - &receipt, - ); - runtime - .kernel - .command(WorldCommand::ResolveNpcAction { - expected_revision: current.revision, - proposal: proposal.clone(), - assessment, - }) - .await?; - Ok(true) -} - -fn has_current_npc_initiative(campaign: &Campaign) -> bool { - !campaign.pending_world_proposals.is_empty() - && campaign.events.last().is_some_and(|event| { - event.kind == "reaction_wave" - && event.id == format!("reaction-wave:{}", campaign.revision) - }) -} - -async fn await_live_turn_idle(state: &AppState) { - loop { - let finished = state.live_turn_finished.notified(); - tokio::pin!(finished); - finished.as_mut().enable(); - if state.live_turns.load(Ordering::SeqCst) == 0 { - return; - } - finished.await; - } -} - -fn schedule_npc_initiative( - state: &AppState, - runtime: &CampaignRuntime, - campaign: Campaign, - command_kind: String, -) { - let state = state.clone(); - let runtime = runtime.clone(); - tokio::spawn(async move { - loop { - await_live_turn_idle(&state).await; - match resolve_npc_initiative(&state, &runtime, &campaign).await { - Ok(true) => { - if let Err(error) = refresh_mesh(&state).await { - tracing::warn!(%error, "post-initiative CultMesh publication failed"); - } - return; - } - Ok(false) => tokio::task::yield_now().await, - Err(error) => { - record_rejected_proposal( - &runtime, - &format!("{command_kind}.npc_initiative"), - error.to_string(), - ); - tracing::warn!(%error, command_kind, "deferred NPC initiative stopped"); - if let Err(refresh_error) = refresh_mesh(&state).await { - tracing::warn!(%refresh_error, "post-initiative failure CultMesh publication failed"); - } - return; - } - } - } - }); -} - -async fn schedule_recovered_npc_initiatives(state: &AppState) -> anyhow::Result<()> { - for id in state.registry.list().await { - let runtime = state.registry.runtime(id).await?; - let campaign = load_campaign(&runtime.store)?; - if has_current_npc_initiative(&campaign) { - schedule_npc_initiative( - state, - &runtime, - campaign, - "startup.recovered_npc_initiative".into(), - ); - } - } - Ok(()) -} - -fn record_rejected_proposal(runtime: &CampaignRuntime, command_kind: &str, reason: String) { - if let Ok(campaign) = load_campaign(&runtime.store) { - let receipt = RejectedProposalReceipt { - schema: "ghostlight.rejected_proposal_receipt.v1".into(), - id: uuid::Uuid::new_v4().to_string(), - campaign_id: campaign.id, - revision: campaign.revision, - command_kind: command_kind.into(), - reason, - rejected_at: chrono::Utc::now(), - }; - let _ = runtime.store.insert( - "rejected_proposal_receipt.v1", - "ghostlight.rejected_proposal_receipt.v1", - &receipt.id, - &receipt, - ); - } -} - -async fn committed_after_failure( - state: &AppState, - runtime: &CampaignRuntime, - result: &CommandResult, - stage: &str, - reason: String, -) -> Response { - tracing::warn!(stage, %reason, "post-commit aftermath stopped"); - record_rejected_proposal(runtime, stage, reason.clone()); - if let Err(error) = refresh_mesh(state).await { - tracing::warn!(%error, "post-commit CultMesh publication failed"); - } - let message = format!( - "The player action committed, but {stage} stopped: {reason}. Every world change remains separately receipted." - ); - Json(player_command_projection_with_message(result, &message)).into_response() -} - -async fn propose_time_advance( - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - governed_campaign_command(&headers, &state, |member| { - WorldCommand::ProposeTimeAdvance { - expected_revision: request.expected_revision, - member_id: member.member_id, - minutes: request.minutes, - } - }) - .await -} - -async fn approve_time_advance( - Path(proposal_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - governed_campaign_command(&headers, &state, |member| { - WorldCommand::ApproveTimeAdvance { - expected_revision: request.expected_revision, - proposal_id, - member_id: member.member_id, - } - }) - .await -} - -async fn propose_group_travel( - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - governed_campaign_command(&headers, &state, |member| { - WorldCommand::ProposeGroupTravel { - expected_revision: request.expected_revision, - member_id: member.member_id, - destination_location_id: request.destination_location_id, - } - }) - .await -} - -async fn approve_group_travel( - Path(proposal_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - governed_campaign_command(&headers, &state, |member| { - WorldCommand::ApproveGroupTravel { - expected_revision: request.expected_revision, - proposal_id, - member_id: member.member_id, - } - }) - .await -} - -async fn propose_cell_budget( - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - governed_campaign_command(&headers, &state, |member| { - WorldCommand::ProposeResolutionBudget { - expected_revision: request.expected_revision, - expected_resolution_epoch: request.expected_resolution_epoch, - member_id: member.member_id, - active_cell_budget: request.active_cell_budget, - } - }) - .await -} - -async fn approve_cell_budget( - Path(proposal_id): Path, - headers: HeaderMap, - State(state): State, - Json(request): Json, -) -> Response { - governed_campaign_command(&headers, &state, |member| { - WorldCommand::ApproveResolutionBudget { - expected_revision: request.expected_revision, - proposal_id, - member_id: member.member_id, - } - }) - .await -} - -async fn governed_campaign_command( - headers: &HeaderMap, - state: &AppState, - make: impl FnOnce(ghostlight_dungeon::session_zero::CampaignMember) -> WorldCommand, -) -> Response { - let account_hash = match authenticated_session(headers, state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let runtime = match session_runtime(state, &account_hash).await { - Ok(Some(value)) => value, - Ok(None) => return (StatusCode::NOT_FOUND, "session has no campaign").into_response(), - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let campaign = match load_campaign(&runtime.store) { - Ok(value) => value, - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let member = match campaign_member_for_account(&runtime.store, &campaign, &account_hash) { - Ok(value) => value, - Err(error) => return (StatusCode::FORBIDDEN, error.to_string()).into_response(), - }; - match runtime.kernel.command(make(member)).await { - Ok(result) => { - if matches!(result, CommandResult::Committed { .. }) - && let Err(error) = refresh_mesh(state).await - { - tracing::warn!(%error, "governed time advance mesh refresh failed"); - } - Json(player_command_projection(&result)).into_response() - } - Err(KernelError::Stale { expected, actual }) => ( - StatusCode::CONFLICT, - Json(serde_json::json!({"error":"stale revision","expected":expected,"actual":actual})), - ) - .into_response(), - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - } -} - -async fn command( - headers: HeaderMap, - State(state): State, - Json(mut command): Json, -) -> Response { - let session = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let _live = LiveTurnGuard::enter(&state).await; - let runtime = match session_runtime(&state, &session).await { - Ok(Some(value)) => value, - Ok(None) => { - return ( - StatusCode::NOT_FOUND, - Json(ErrorBody { - error: "session has no selected campaign".into(), - }), - ) - .into_response(); - } - Err(error) => { - return ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(ErrorBody { - error: error.to_string(), - }), - ) - .into_response(); - } - }; - let admission_campaign = match load_campaign(&runtime.store) { - Ok(campaign) => campaign, - Err(error) => { - return ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(ErrorBody { - error: error.to_string(), - }), - ) - .into_response(); - } - }; - let player_id = match campaign_member_for_account(&runtime.store, &admission_campaign, &session) - { - Ok(member) => member.actor_id, - Err(error) => { - return ( - StatusCode::FORBIDDEN, - Json(ErrorBody { - error: error.to_string(), - }), - ) - .into_response(); - } - }; - let campaign_membership = runtime - .store - .load::( - "campaign_membership.v1", - &admission_campaign.id.to_string(), - ) - .ok() - .flatten() - .map(|(_, membership)| membership); - let cooperative_member_count = campaign_membership - .as_ref() - .map(|membership| { - membership - .members - .values() - .filter(|member| member.active) - .count() - }) - .unwrap_or(1); - if cooperative_member_count > 1 - && matches!( - command, - WorldCommand::Wait { .. } | WorldCommand::SetResolutionBudget { .. } - ) - { - return ( - StatusCode::FORBIDDEN, - Json(ErrorBody { - error: "co-op time and Persona-cell budget changes require unanimous governance" - .into(), - }), - ) - .into_response(); - } - if let WorldCommand::SetResolutionBudget { - active_cell_budget, .. - } = &command - && campaign_membership - .as_ref() - .is_some_and(|membership| *active_cell_budget > membership.pooled_cell_allowance()) - { - return ( - StatusCode::FORBIDDEN, - Json(ErrorBody { - error: "requested Persona-cell budget exceeds the campaign entitlement pool".into(), - }), - ) - .into_response(); - } - if !player_http_command_allowed(&command, &player_id) { - return ( - StatusCode::FORBIDDEN, - Json(ErrorBody { - error: "command is not admitted through the player HTTP boundary".into(), - }), - ) - .into_response(); - } - if let Err(error) = validate_player_http_command(&command) { - return (StatusCode::UNPROCESSABLE_ENTITY, Json(ErrorBody { error })).into_response(); - } - if player_command_requires_return_catch_up(&command) { - let catch_up_start_revision = admission_campaign.revision; - if let Err(error) = process_due_ticks( - &state, - &runtime, - ghostlight_dungeon::domain::TickSource::ReturnCatchUp, - false, - ) - .await - { - let current_revision = load_campaign(&runtime.store) - .map(|campaign| campaign.revision) - .unwrap_or(catch_up_start_revision); - let body = if current_revision > catch_up_start_revision { - player_safe_partial_catch_up_failure( - &error, - catch_up_start_revision, - current_revision, - ) - } else { - player_safe_strategic_failure(&error) - }; - return (StatusCode::CONFLICT, Json(body)).into_response(); - } - } - if let WorldCommand::Speak { - expected_revision, - actor_id, - text, - persona_response_actor_ids, - .. - } = &mut command - { - let campaign = match load_campaign(&runtime.store) { - Ok(value) => value, - Err(error) => { - return ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(ErrorBody { - error: error.to_string(), - }), - ) - .into_response(); - } - }; - if campaign.revision != *expected_revision { - return ( - StatusCode::CONFLICT, - Json(ErrorBody { - error: format!( - "stale revision: expected {expected_revision}, actual {}", - campaign.revision - ), - }), - ) - .into_response(); - } - if let Some(model) = &state.model { - match resolve_speech_addresses(model.clone(), MODEL_FAST, &campaign, actor_id, text) - .await - { - Ok((plan, receipts)) => { - for receipt in receipts { - let _ = runtime.store.insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - &receipt, - ); - } - *persona_response_actor_ids = plan.persona_response_actor_ids; - } - Err(error) => { - return ( - StatusCode::UNPROCESSABLE_ENTITY, - Json(ErrorBody { - error: format!("scene address resolution failed: {error}"), - }), - ) - .into_response(); - } - } - } - } - if let WorldCommand::Wait { - expected_revision, - minutes, - } = &command - { - let campaign = match load_campaign(&runtime.store) { - Ok(value) => value, - Err(error) => { - return ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(ErrorBody { - error: error.to_string(), - }), - ) - .into_response(); - } - }; - if *expected_revision != campaign.revision { - return ( - StatusCode::CONFLICT, - Json(ErrorBody { - error: format!( - "stale revision: expected {expected_revision}, actual {}", - campaign.revision - ), - }), - ) - .into_response(); - } - let strategic_minutes = u32::from(campaign.tick_hours).saturating_mul(60); - if *minutes > strategic_minutes { - return ( - StatusCode::UNPROCESSABLE_ENTITY, - Json(ErrorBody { - error: format!( - "one wait may cover at most one strategic horizon ({strategic_minutes} minutes); wait again after the world advances" - ), - }), - ) - .into_response(); - } - if *minutes == strategic_minutes { - return match advance_one_strategic_tick( - &state, - &runtime, - campaign, - ghostlight_dungeon::domain::TickSource::PlayerWait, - false, - ) - .await - { - Ok(Some(result)) => Json(player_command_projection(&result)).into_response(), - Ok(None) => ( - StatusCode::SERVICE_UNAVAILABLE, - Json(ErrorBody { - error: "strategic waiting yielded without advancing the world".into(), - }), - ) - .into_response(), - Err(error) => { - let body = player_safe_strategic_failure(&error); - (StatusCode::UNPROCESSABLE_ENTITY, Json(body)).into_response() - } - }; - } - } - if let WorldCommand::Assess { - intent, proposal, .. - } = &mut command - { - if proposal.is_none() { - let Some(assessor) = &state.assessor else { - return ( - StatusCode::SERVICE_UNAVAILABLE, - Json(ErrorBody { - error: "Model assessor is unavailable".into(), - }), - ) - .into_response(); - }; - let campaign = match load_campaign(&runtime.store) { - Ok(value) => value, - Err(error) => { - return ( - StatusCode::NOT_FOUND, - Json(ErrorBody { - error: error.to_string(), - }), - ) - .into_response(); - } - }; - let extraordinary_permissions = runtime - .store - .load::( - "campaign_membership.v1", - &campaign.id.to_string(), - ) - .ok() - .flatten() - .and_then(|(_, membership)| { - membership - .extraordinary_permissions - .get(&intent.actor_id) - .cloned() - }) - .unwrap_or_default(); - let (contract, boundaries) = campaign_model_policy(&runtime.store, campaign.id); - match assessor - .assess_with_context_cached( - &runtime.store, - &campaign, - intent.clone(), - &extraordinary_permissions, - contract.as_ref(), - &boundaries, - ) - .await - { - Ok((assessment, receipt)) => { - if let Ok(Some((_, membership))) = - runtime - .store - .load::( - "campaign_membership.v1", - &campaign.id.to_string(), - ) - && membership - .members - .values() - .filter(|member| member.active) - .count() - > 1 - { - let controlled = membership.controlled_actor_ids(); - if assessment_effects(&assessment) - .any(|effect| !effect.actor_moves.is_empty()) - { - return ( - StatusCode::UNPROCESSABLE_ENTITY, - Json(ErrorBody { - error: - "group travel requires a unanimous revision-bound proposal" - .into(), - }), - ) - .into_response(); - } - if assessment_effects(&assessment).any(|effect| { - effect - .actor_conditions - .keys() - .chain(effect.actor_commitments.keys()) - .chain(effect.actor_knowledge_additions.keys()) - .chain(effect.actor_observations.keys()) - .chain(effect.actor_relationship_updates.keys()) - .any(|target| { - target != &intent.actor_id && controlled.contains(target) - }) - }) { - return ( - StatusCode::UNPROCESSABLE_ENTITY, - Json(ErrorBody { - error: "effects on another player character are unsupported" - .into(), - }), - ) - .into_response(); - } - } - let _ = runtime.store.insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - &receipt, - ); - *proposal = Some(assessment); - } - Err(error) => { - let body = player_safe_assessment_failure(&error); - return (StatusCode::UNPROCESSABLE_ENTITY, Json(body)).into_response(); - } - } - } - } - let should_react = matches!( - &command, - WorldCommand::Attempt { .. } | WorldCommand::Speak { .. } - ); - let committed_reaction_stimulus = reaction_stimulus(&command); - let command_kind = serde_json::to_value(&command) - .ok() - .and_then(|value| { - value - .get("type") - .and_then(|value| value.as_str()) - .map(str::to_owned) - }) - .unwrap_or_else(|| "unknown".into()); - match runtime.kernel.command(command).await { - Ok(result) => { - if should_react { - if let ghostlight_dungeon::kernel::CommandResult::Committed { campaign, .. } = - &result - { - if let Some(model) = &state.model { - let summary = committed_reaction_stimulus.clone().unwrap_or_else(|| { - campaign - .transcript - .last() - .map(|turn| turn.text.clone()) - .unwrap_or_else(|| "A consequential event occurred.".into()) - }); - let mut reaction_campaign = campaign.clone(); - let mut presence_result = None; - match required_addressed_promotions(&reaction_campaign) { - Ok(plan) if !plan.promotions.is_empty() => { - match runtime - .kernel - .command(WorldCommand::ReconcileGestaltPresence { - expected_revision: reaction_campaign.revision, - reason: summary.clone(), - plan, - }) - .await - { - Ok(committed @ CommandResult::Committed { .. }) => { - if let CommandResult::Committed { campaign, .. } = - &committed - { - reaction_campaign = campaign.clone(); - } - presence_result = Some(committed); - } - Ok(_) => unreachable!(), - Err(error) => { - return committed_after_failure( - &state, - &runtime, - &result, - &format!("{command_kind}.addressed_gestalt_presence"), - error.to_string(), - ) - .await; - } - } - } - Ok(_) => {} - Err(error) => { - return committed_after_failure( - &state, - &runtime, - &result, - &format!("{command_kind}.addressed_gestalt_presence"), - error.to_string(), - ) - .await; - } - } - if !campaign.gestalts.is_empty() { - let planner = GestaltPresencePlanner { - model: model.clone(), - model_name: MODEL_FAST.into(), - }; - match planner.plan(&reaction_campaign, &summary).await { - Ok((plan, receipts)) => { - for receipt in receipts { - let _ = runtime.store.insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - &receipt, - ); - } - if !plan.individuations.is_empty() - || !plan.promotions.is_empty() - || !plan.demotions.is_empty() - { - match runtime.kernel.command(WorldCommand::ReconcileGestaltPresence { - expected_revision: reaction_campaign.revision, - reason: summary.clone(), - plan, - }).await { - Ok(committed @ ghostlight_dungeon::kernel::CommandResult::Committed { .. }) => { - if let ghostlight_dungeon::kernel::CommandResult::Committed { campaign, .. } = &committed { - reaction_campaign = campaign.clone(); - } - presence_result = Some(committed); - } - Ok(_) => unreachable!(), - Err(error) => { - tracing::warn!( - stage = %format!("{command_kind}.gestalt_presence"), - %error, - "optional post-commit presence proposal rejected; continuing present-actor appraisal" - ); - record_rejected_proposal( - &runtime, - &format!("{command_kind}.gestalt_presence"), - error.to_string(), - ); - } - } - } - } - Err(error) => { - tracing::warn!( - stage = %format!("{command_kind}.gestalt_presence_planner"), - %error, - "optional post-commit presence planning failed; continuing present-actor appraisal" - ); - record_rejected_proposal( - &runtime, - &format!("{command_kind}.gestalt_presence_planner"), - error.to_string(), - ); - } - } - } - if reaction_campaign.actors.len() > 1 - || !reaction_campaign.gestalts.is_empty() - { - let engine = PersonaProjectionEngine { - model: model.clone(), - permit: Arc::new(SnapshotPermit::new( - runtime.store.clone(), - reaction_campaign.id, - reaction_campaign.revision, - )), - projector_model: MODEL_FAST.into(), - persona_model: MODEL_CAPABLE.into(), - interpreter_model: MODEL_FAST.into(), - }; - match appraise_present(engine, &reaction_campaign, &summary).await { - Ok(wave) if !wave.reactions.is_empty() => { - for receipt in wave.receipts { - let _ = runtime.store.insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - &receipt, - ); - } - match runtime - .kernel - .command(WorldCommand::ResolveReactionWave { - expected_revision: reaction_campaign.revision, - event_summary: summary, - reactions: wave.reactions, - gestalt_reactions: wave.gestalt_reactions, - }) - .await - { - Ok(reaction) => { - if let CommandResult::Committed { campaign, .. } = - reaction - { - schedule_npc_initiative( - &state, - &runtime, - campaign, - command_kind.clone(), - ); - } - if let Err(error) = refresh_mesh(&state).await { - tracing::warn!(%error, "post-command CultMesh publication failed"); - } - return Json(player_command_projection(&result)) - .into_response(); - } - Err(error) => { - return committed_after_failure( - &state, - &runtime, - &result, - &format!("{command_kind}.reaction_commit"), - error.to_string(), - ) - .await; - } - } - } - Ok(_) => {} - Err(error) => { - return committed_after_failure( - &state, - &runtime, - &result, - &format!("{command_kind}.reaction_appraisal"), - error.to_string(), - ) - .await; - } - } - } - if presence_result.is_some() { - if let Err(error) = refresh_mesh(&state).await { - tracing::warn!(%error, "post-command CultMesh publication failed"); - } - return Json(player_command_projection(&result)).into_response(); - } - } - } - } - if matches!( - &result, - CommandResult::Committed { .. } | CommandResult::Created { .. } - ) { - if let Err(error) = refresh_mesh(&state).await { - tracing::warn!(%error, "post-command CultMesh publication failed"); - } - Json(player_command_projection(&result)).into_response() - } else { - Json(player_command_projection(&result)).into_response() - } - } - Err(error) => { - if let KernelError::StaleAssessment { intent, .. } = &error { - let Some(assessor) = &state.assessor else { - return ( - StatusCode::SERVICE_UNAVAILABLE, - Json(ErrorBody { - error: "Model assessor is unavailable".into(), - }), - ) - .into_response(); - }; - let campaign = match load_campaign(&runtime.store) { - Ok(value) => value, - Err(load_error) => { - return ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(ErrorBody { - error: load_error.to_string(), - }), - ) - .into_response(); - } - }; - let membership = runtime - .store - .load::( - "campaign_membership.v1", - &campaign.id.to_string(), - ) - .ok() - .flatten() - .map(|(_, value)| value); - let permissions = membership - .as_ref() - .and_then(|membership| { - membership.extraordinary_permissions.get(&intent.actor_id) - }) - .cloned() - .unwrap_or_default(); - let (contract, boundaries) = campaign_model_policy(&runtime.store, campaign.id); - match assessor - .assess_with_context_cached( - &runtime.store, - &campaign, - intent.clone(), - &permissions, - contract.as_ref(), - &boundaries, - ) - .await - { - Ok((assessment, receipt)) => { - let _ = runtime.store.insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - &receipt, - ); - return match runtime - .kernel - .command(WorldCommand::Assess { - expected_revision: campaign.revision, - intent: intent.clone(), - proposal: Some(assessment), - }) - .await - { - Ok(result) => Json(player_command_projection(&result)).into_response(), - Err(recompile_error) => ( - StatusCode::CONFLICT, - Json(ErrorBody { - error: recompile_error.to_string(), - }), - ) - .into_response(), - }; - } - Err(recompile_error) => { - return ( - StatusCode::BAD_GATEWAY, - Json(ErrorBody { - error: recompile_error.to_string(), - }), - ) - .into_response(); - } - } - } - record_rejected_proposal(&runtime, &command_kind, error.to_string()); - ( - StatusCode::CONFLICT, - Json(ErrorBody { - error: error.to_string(), - }), - ) - .into_response() - } - } -} - -fn assessment_effects( - assessment: &ghostlight_dungeon::domain::ActionAssessment, -) -> impl Iterator { - [ - &assessment.strong_effect, - &assessment.success_effect, - &assessment.mixed_effect, - &assessment.failure_effect, - ] - .into_iter() -} - -#[cfg(test)] -fn world_compile_preview_projection(preview: &WorldCompilePreview) -> serde_json::Value { - let campaign = &preview.campaign; - let player = &campaign.actors[&campaign.player_actor_id]; - let locations = campaign - .locations - .values() - .map(|location| { - serde_json::json!({ - "id":location.id, - "name":location.name, - "container_id":location.container_id, - "routes":location.routes, - "persistent_features":location.persistent_features, - }) - }) - .collect::>(); - let cast = campaign - .actors - .values() - .filter(|actor| actor.id != campaign.player_actor_id) - .map(|actor| { - serde_json::json!({ - "id":actor.id, - "name":actor.name, - "location_id":actor.location_id, - }) - }) - .collect::>(); - let institutions = campaign - .institutions - .values() - .map(|institution| { - serde_json::json!({ - "id":institution.id, - "name":institution.name, - }) - }) - .collect::>(); - let populations = campaign - .gestalts - .values() - .map(|gestalt| { - serde_json::json!({ - "id":gestalt.id, - "name":gestalt.name, - "home_location_id":gestalt.home_location_id, - }) - }) - .collect::>(); - let clocks = campaign - .clocks - .values() - .map(|clock| { - serde_json::json!({ - "id":clock.id, - "name":clock.label, - "progress":clock.progress, - "threshold":clock.threshold, - "trigger":clock.consequence, - }) - }) - .collect::>(); - serde_json::json!({ - "schema":preview.schema, - "title":preview.title, - "opening":campaign.transcript.first().map(|turn| turn.text.as_str()), - "locations":locations, - "cast":cast, - "institutions":institutions, - "populations":populations, - "clocks":clocks, - "player_role":{ - "name":player.name, - "location_id":player.location_id, - "capabilities":player.capabilities, - "equipment":player.equipment, - "conditions":player.conditions, - "obligations":player.obligations, - }, - "evidence_coverage":preview.evidence_coverage, - "gaps":preview.gaps, - "branch_assumptions":preview.branch_assumptions, - "requires_approval":preview.requires_approval, - }) -} - -fn destination_compilation_preview_projection( - preview: &DestinationCompilationPreview, -) -> serde_json::Value { - match preview { - DestinationCompilationPreview::RegionExpansion(preview) => serde_json::json!({ - "kind":"region_expansion", - "target_location_id":null, - "origin_location_id":preview.expansion.origin_location_id, - "origin_routes":preview.expansion.origin_routes, - "locations":preview.expansion.locations, - "facts":preview.expansion.facts, - "populations":preview.expansion.populations, - "population_profiles":preview.expansion.population_profiles, - "institutions":preview.expansion.institutions, - "institution_profiles":preview.expansion.institution_profiles, - "local_relations":preview.expansion.local_relations, - "migration_relations":preview.expansion.migration_relations, - "civic_system":preview.expansion.civic_system, - "branch_assumptions":preview.branch_assumptions, - "gaps":preview.gaps, - "requires_approval":preview.requires_approval, - }), - DestinationCompilationPreview::LocalityElaboration(preview) => { - serde_json::json!({ - "kind":"locality_elaboration", - "target_location_id":preview.elaboration.target_location_id, - "origin_location_id":preview.elaboration.expansion.origin_location_id, - "origin_routes":preview.elaboration.expansion.origin_routes, - "locations":preview.elaboration.expansion.locations, - "facts":preview.elaboration.expansion.facts, - "populations":preview.elaboration.expansion.populations, - "population_profiles":preview.elaboration.expansion.population_profiles, - "institutions":preview.elaboration.expansion.institutions, - "institution_profiles":preview.elaboration.expansion.institution_profiles, - "local_relations":preview.elaboration.expansion.local_relations, - "migration_relations":preview.elaboration.expansion.migration_relations, - "civic_system":preview.elaboration.expansion.civic_system, - "branch_assumptions":preview.branch_assumptions, - "gaps":preview.gaps, - "requires_approval":preview.requires_approval, - }) - } - } -} - -fn gestalt_fission_preview_projection(preview: &GestaltFissionPreview) -> serde_json::Value { - let children = preview - .children - .iter() - .map(|child| { - serde_json::json!({ - "id":child.id, - "name":child.name, - "home_location_id":child.home_location_id, - "partition_value":preview.child_partition_values.get(&child.id), - }) - }) - .collect::>(); - serde_json::json!({ - "parent_gestalt_id":preview.parent_gestalt_id, - "partition_axis":preview.partition_axis, - "children":children, - "gaps":preview.gaps, - "requires_approval":preview.requires_approval, - }) -} - -fn player_command_projection(result: &CommandResult) -> serde_json::Value { - match result { - CommandResult::Assessed { assessment } => serde_json::json!({ - "kind":"assessed", - "assessment":assessment, - }), - CommandResult::Committed { receipt, .. } => serde_json::json!({ - "kind":"committed", - "revision":receipt.revision, - "receipt":receipt, - }), - CommandResult::ExternalSnapshotCommitted { receipt, .. } => serde_json::json!({ - "kind":"external_snapshot_committed", - "revision":receipt.world_revision, - "receipt":receipt, - }), - CommandResult::ResolutionUpdated { receipt, .. } => serde_json::json!({ - "kind":"resolution_updated", - "receipt":receipt, - }), - CommandResult::Created { .. } => serde_json::json!({ - "kind":"created", - }), - CommandResult::GovernancePending { proposal, .. } => serde_json::json!({ - "kind":"governance_pending", - "proposal":proposal, - }), - CommandResult::TravelGovernancePending { proposal, .. } => serde_json::json!({ - "kind":"travel_governance_pending", - "proposal":proposal, - }), - CommandResult::ResolutionGovernancePending { proposal, .. } => serde_json::json!({ - "kind":"resolution_governance_pending", - "proposal":proposal, - }), - CommandResult::MutationCommitted { receipt, .. } => serde_json::json!({ - "kind":"mutation_committed", - "revision":receipt.world_revision, - "receipt":receipt, - }), - } -} - -fn player_command_projection_with_message( - result: &CommandResult, - message: &str, -) -> serde_json::Value { - let mut projection = player_command_projection(result); - if let Some(object) = projection.as_object_mut() { - object.insert("message".into(), message.into()); - } - projection -} - -fn player_http_command_allowed(command: &WorldCommand, player_actor_id: &str) -> bool { - match command { - WorldCommand::Speak { actor_id, .. } => actor_id == player_actor_id, - WorldCommand::Assess { - intent, proposal, .. - } => intent.actor_id == player_actor_id && proposal.is_none(), - WorldCommand::Attempt { actor_id, .. } if actor_id == player_actor_id => true, - WorldCommand::Attempt { .. } => false, - WorldCommand::Wait { .. } | WorldCommand::SetResolutionBudget { .. } => true, - WorldCommand::CreateCampaign { .. } - | WorldCommand::ApplyExternalSubjectSnapshot { .. } - | WorldCommand::ProposeTimeAdvance { .. } - | WorldCommand::ApproveTimeAdvance { .. } - | WorldCommand::ProposeGroupTravel { .. } - | WorldCommand::ApproveGroupTravel { .. } - | WorldCommand::ProposeResolutionBudget { .. } - | WorldCommand::ApproveResolutionBudget { .. } - | WorldCommand::AdvanceStrategicTick { .. } - | WorldCommand::ExpandRegion { .. } - | WorldCommand::ElaborateLocality { .. } - | WorldCommand::MaterializeGestaltMember { .. } - | WorldCommand::DematerializeGestaltMember { .. } - | WorldCommand::IndividuateGestaltMember { .. } - | WorldCommand::ElaborateGestaltIndividuation { .. } - | WorldCommand::ReconcileGestaltPresence { .. } - | WorldCommand::ResolveReactionWave { .. } - | WorldCommand::ResolveNpcAction { .. } - | WorldCommand::SetProviderParallelism { .. } - | WorldCommand::ReplaceResolutionPins { .. } - | WorldCommand::FissionGestalt { .. } - | WorldCommand::ElaborateGestaltFission { .. } - | WorldCommand::ReconcileFissionCivicBindings { .. } - | WorldCommand::BindClockConsequences { .. } => false, - } -} - -fn player_command_requires_return_catch_up(command: &WorldCommand) -> bool { - matches!( - command, - WorldCommand::Speak { .. } | WorldCommand::Attempt { .. } | WorldCommand::Wait { .. } - ) -} - -fn validate_player_http_command(command: &WorldCommand) -> Result<(), String> { - let bounded = |label: &str, value: &str, max: usize| { - if value.trim().is_empty() || value.chars().count() > max { - Err(format!("{label} must contain 1 to {max} characters")) - } else { - Ok(()) - } - }; - match command { - WorldCommand::Speak { - text, - intended_effect, - persona_response_actor_ids, - .. - } => { - bounded("speech", text, 4_000)?; - if intended_effect.is_some() { - return Err( - "speech and uncertain intended effects use separate player commands".into(), - ); - } - if !persona_response_actor_ids.is_empty() { - return Err("player commands cannot supply Persona response authority IDs".into()); - } - Ok(()) - } - WorldCommand::Assess { intent, .. } => { - bounded("action description", &intent.description, 4_000)?; - bounded("intended effect", &intent.intended_effect, 1_000) - } - WorldCommand::Attempt { - assessment_digest, .. - } => bounded("assessment digest", assessment_digest, 160), - WorldCommand::Wait { minutes, .. } if *minutes == 0 || *minutes > 1_440 => { - Err("wait duration must be between 1 and 1440 minutes".into()) - } - WorldCommand::SetResolutionBudget { - active_cell_budget, .. - } if !(1..=ghostlight_dungeon::resolution::MAX_ACTIVE_CELL_BUDGET) - .contains(active_cell_budget) => - { - Err(format!( - "active Persona-cell budget must be between 1 and {}", - ghostlight_dungeon::resolution::MAX_ACTIVE_CELL_BUDGET - )) - } - _ => Ok(()), - } -} - -fn reaction_stimulus(command: &WorldCommand) -> Option { - match command { - WorldCommand::Speak { actor_id, text, .. } => { - Some(format!("{actor_id} says: {}", text.trim())) - } - _ => None, - } -} - -async fn scheduler_loop(state: AppState) { - let mut pulse = tokio::time::interval(std::time::Duration::from_secs(300)); - pulse.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - pulse.tick().await; - loop { - pulse.tick().await; - if state.live_turns.load(Ordering::SeqCst) > 0 { - continue; - } - for id in state.registry.list().await { - match state.registry.runtime(id).await { - Ok(runtime) => { - let campaign = match load_campaign(&runtime.store) { - Ok(campaign) => campaign, - Err(error) => { - tracing::warn!(%id,%error,"campaign vanished during scheduler pulse"); - continue; - } - }; - if has_current_npc_initiative(&campaign) { - match resolve_npc_initiative(&state, &runtime, &campaign).await { - Ok(true) => {} - Ok(false) => continue, - Err(error) => { - record_rejected_proposal( - &runtime, - "scheduler.recovered_npc_initiative", - error.to_string(), - ); - tracing::warn!(%id,%error,"recovered NPC initiative refused"); - } - } - continue; - } - if let Err(error) = process_due_ticks( - &state, - &runtime, - ghostlight_dungeon::domain::TickSource::Scheduler, - true, - ) - .await - { - tracing::warn!(%id,%error,"strategic scheduler pulse refused"); - } - } - Err(error) => { - tracing::warn!(%id,%error,"campaign runtime vanished during scheduler pulse") - } - } - } - if let Err(error) = refresh_mesh(&state).await { - tracing::warn!(%error, "CultMesh projection refresh failed"); - } - } -} - -async fn refresh_mesh(state: &AppState) -> anyhow::Result { - let mut snapshots = Vec::new(); - for id in state.registry.list().await { - let runtime = state.registry.runtime(id).await?; - let campaign = load_campaign(&runtime.store)?; - snapshots.push(CampaignMeshSnapshot { - membership: runtime - .store - .load::( - "campaign_membership.v1", - &campaign.id.to_string(), - )? - .map(|(_, membership)| membership), - campaign, - evidence: runtime.store.load_all("vault_evidence_receipt.v1")?, - commits: runtime.store.load_all("world_commit_receipt.v1")?, - stages: runtime.store.load_all("persona_stage_receipt.v1")?, - strategic_ticks: runtime.store.load_all("strategic_tick.v1")?, - gestalt_receipts: runtime - .store - .load_all("gestalt_materialization_receipt.v1")?, - rejected: runtime.store.load_all("rejected_proposal_receipt.v1")?, - resolution_plans: runtime.store.load_all("resolution_plan_receipt.v1")?, - cell_appraisals: runtime.store.load_all("cell_appraisal.v1")?, - activity_outcomes: runtime.store.load_all("strategic_activity_outcome.v1")?, - resolution_controls: runtime.store.load_all("resolution_control_receipt.v1")?, - }); - } - let mut session_zero_snapshots = Vec::new(); - for id in state.session_zeros.list().await { - let session_zero = state.session_zeros.snapshot(id).await?; - for member in session_zero.members.values().filter(|member| member.active) { - let choices = campaign_choice_components(snapshots.iter().filter_map(|snapshot| { - snapshot - .membership - .as_ref()? - .member_for_account(&member.account_hash)?; - Some((snapshot.campaign.id, snapshot.campaign.name.clone())) - })); - let mut surface = session_zero_surface(&session_zero, &member.account_hash)?; - append_campaign_choices(&mut surface, choices)?; - session_zero_snapshots.push(SessionZeroMeshSnapshot { - session_zero_id: id, - member_id: member.id.clone(), - surface, - }); - } - } - let publisher = state.mesh.clone(); - let model_status = state.model_status.clone(); - let pressure = state.live_turns.load(Ordering::SeqCst); - tokio::task::spawn_blocking(move || { - publisher.publish_snapshot(&snapshots, &session_zero_snapshots, &model_status, pressure) - }) - .await? -} - -fn schedule_mesh_refresh(state: &AppState) { - let state = state.clone(); - tokio::spawn(async move { - if let Err(error) = refresh_mesh(&state).await { - tracing::warn!(%error, "asynchronous CultMesh refresh failed"); - } - }); -} - -async fn select_campaign_route( - Path(campaign_id): Path, - headers: HeaderMap, - State(state): State, -) -> Response { - let account_hash = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - let owned = match state.registry.runtime(campaign_id).await { - Ok(runtime) => load_campaign(&runtime.store) - .and_then(|campaign| { - campaign_member_for_account(&runtime.store, &campaign, &account_hash) - }) - .is_ok(), - Err(_) => false, - }; - if !owned { - return StatusCode::FORBIDDEN.into_response(); - } - match select_campaign(&state, &account_hash, campaign_id).await { - Ok(()) => StatusCode::NO_CONTENT.into_response(), - Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), - } -} - -async fn begin_contract_review(headers: HeaderMap, State(state): State) -> Response { - let account_hash = match authenticated_session(&headers, &state).await { - Some(value) => value, - None => return StatusCode::UNAUTHORIZED.into_response(), - }; - if let Ok(Some(id)) = state - .session_zeros - .active_contract_review_for_account(&account_hash) - .await - { - return match state - .session_zeros - .snapshot(id) - .await - .and_then(|snapshot| session_zero_surface(&snapshot, &account_hash)) - { - Ok(surface) => Json(surface).into_response(), - Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), - }; - } - let runtime = match session_runtime(&state, &account_hash).await { - Ok(Some(value)) => value, - Ok(None) => return (StatusCode::NOT_FOUND, "session has no campaign").into_response(), - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let campaign = match load_campaign(&runtime.store) { - Ok(value) => value, - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let membership = match runtime - .store - .load::( - "campaign_membership.v1", - &campaign.id.to_string(), - ) { - Ok(Some((_, value))) if value.member_for_account(&account_hash).is_some() => value, - Ok(_) => return StatusCode::FORBIDDEN.into_response(), - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let contract = match runtime - .store - .load::( - "campaign_contract.v1", - &campaign.id.to_string(), - ) { - Ok(Some((_, value))) => value, - Ok(None) => { - return ( - StatusCode::CONFLICT, - "campaign has no Session Zero contract", - ) - .into_response(); - } - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let dm_persona = match runtime - .store - .load_all::("campaign_dm_persona.v1") - { - Ok(values) if values.len() == 1 => values.into_iter().next().unwrap(), - Ok(_) => return (StatusCode::CONFLICT, "campaign DM state is ambiguous").into_response(), - Err(error) => { - return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(); - } - }; - let previous_brief = runtime - .store - .load::( - "approved_campaign_brief.v1", - &campaign.id.to_string(), - ) - .ok() - .flatten() - .map(|(_, value)| value); - let boundaries = runtime - .store - .load::( - "session_zero_publication.v1", - &campaign.id.to_string(), - ) - .ok() - .flatten() - .map(|(_, value)| value.boundaries) - .unwrap_or_default(); - let review = match SessionZeroState::for_contract_review( - &campaign, - &membership, - contract, - dm_persona, - previous_brief.as_ref(), - boundaries, - ) { - Ok(value) => value, - Err(error) => return (StatusCode::CONFLICT, error.to_string()).into_response(), - }; - let id = review.id; - match state.session_zeros.create(review).await { - Ok(_) => match state - .session_zeros - .snapshot(id) - .await - .and_then(|snapshot| session_zero_surface(&snapshot, &account_hash)) - { - Ok(surface) => { - schedule_mesh_refresh(&state); - (StatusCode::CREATED, Json(surface)).into_response() - } - Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), - }, - Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), - } -} - -async fn process_due_ticks( - state: &AppState, - runtime: &CampaignRuntime, - source: ghostlight_dungeon::domain::TickSource, - yield_to_live_turns: bool, -) -> anyhow::Result<()> { - loop { - if yield_to_live_turns && state.live_turns.load(Ordering::SeqCst) > 0 { - return Ok(()); - } - let campaign = match load_campaign(&runtime.store) { - Ok(value) => value, - Err(_) => return Ok(()), - }; - let target = ghostlight_dungeon::scheduler::due_tick_target( - chrono::Utc::now(), - campaign.last_player_activity, - ); - if campaign.away_ticks_processed >= target { - return Ok(()); - } - if advance_one_strategic_tick( - state, - runtime, - campaign, - source.clone(), - yield_to_live_turns, - ) - .await? - .is_none() - { - return Ok(()); - } - } -} - -async fn advance_one_strategic_tick( - state: &AppState, - runtime: &CampaignRuntime, - campaign: Campaign, - source: ghostlight_dungeon::domain::TickSource, - yield_to_live_turns: bool, -) -> anyhow::Result> { - if yield_to_live_turns && state.live_turns.load(Ordering::SeqCst) > 0 { - return Ok(None); - } - let has_simulatable_agency = campaign - .agency_profiles - .values() - .any(|profile| profile.active_leaf && profile.simulation_eligible); - let (model_receipt_hash, resolution_wave) = if has_simulatable_agency { - let Some(model) = &state.model else { - if yield_to_live_turns { - return Ok(None); - } - anyhow::bail!("strategic waiting requires the model provider"); - }; - let permit = Arc::new(SnapshotPermit::new_resolution( - runtime.store.clone(), - campaign.id, - campaign.revision, - campaign.resolution_policy.resolution_epoch, - )); - let (campaign_contract, aggregate_boundaries) = - campaign_model_policy(&runtime.store, campaign.id); - let Some(output) = await_background_work( - state, - yield_to_live_turns, - ghostlight_dungeon::scheduler::propose_resolution_wave_with_policy( - model.clone(), - permit, - &campaign, - campaign_contract.as_ref(), - &aggregate_boundaries, - ), - ) - .await? - else { - return Ok(None); - }; - for stage in &output.stages { - match runtime - .store - .load::( - "persona_stage_receipt.v1", - stage.receipt.storage_key(), - )? { - Some((_, existing)) if existing.same_receipted_content(&stage.receipt) => {} - Some(_) => anyhow::bail!("strategic model receipt hash collision"), - None => { - runtime.store.insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - stage.receipt.storage_key(), - &stage.receipt, - )?; - } - } - } - (Some(output.aggregate_receipt_hash), Some(output.wave)) - } else { - (None, None) - }; - if yield_to_live_turns && state.live_turns.load(Ordering::SeqCst) > 0 { - return Ok(None); - } - let _background_commit = if yield_to_live_turns { - match state.live_commit_gate.clone().try_write_owned() { - Ok(guard) => Some(guard), - Err(_) => return Ok(None), - } - } else { - None - }; - if yield_to_live_turns && state.live_turns.load(Ordering::SeqCst) > 0 { - return Ok(None); - } - let result = runtime - .kernel - .command(WorldCommand::AdvanceStrategicTick { - expected_revision: campaign.revision, - source, - plan: None, - model_receipt_hash, - resolution_wave, - }) - .await - .map_err(anyhow::Error::from)?; - if let Err(error) = refresh_mesh(state).await { - tracing::warn!( - campaign_id = %campaign.id, - revision = campaign.revision.saturating_add(1), - %error, - "post-strategic-commit CultMesh publication failed" - ); - } - Ok(Some(result)) -} - -async fn await_background_work( - state: &AppState, - yield_to_live_turns: bool, - work: impl std::future::Future>, -) -> anyhow::Result> { - if !yield_to_live_turns { - return work.await.map(Some); - } - let live_started = state.live_turn_started.notified(); - tokio::pin!(live_started); - live_started.as_mut().enable(); - if state.live_turns.load(Ordering::SeqCst) > 0 { - return Ok(None); - } - tokio::pin!(work); - tokio::select! { - biased; - _ = &mut live_started => Ok(None), - result = &mut work => result.map(Some), - } -} - -async fn run_live_model_work(state: &AppState, work: impl std::future::Future) -> T { - let _live = LiveTurnGuard::enter(state).await; - work.await -} - -async fn app_session_refresh_loop(state: AppState) { - let mut pulse = tokio::time::interval(std::time::Duration::from_secs(60)); - pulse.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - loop { - pulse.tick().await; - if let Err(error) = refresh_due_app_sessions(&state).await { - tracing::warn!(%error, "scheduled Heimdall session refresh pass failed; unexpired local claims remain authoritative"); - } - } -} - -async fn refresh_due_app_sessions(state: &AppState) -> anyhow::Result<()> { - let candidates = state - .auth - .lock() - .await - .sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(5))?; - for candidate in candidates { - let idempotency_key = refresh_idempotency_key(&candidate.heimdall_session_id); - let completion = match state - .heimdall - .refresh(&candidate.refresh_claim, &idempotency_key) - .await - { - Ok(value) => value, - Err(error) => { - tracing::warn!(%error, session_id=%candidate.heimdall_session_id, "Heimdall refresh transport unavailable"); - continue; - } - }; - if completion.status == "denied" { - state - .auth - .lock() - .await - .revoke_cookie_hash(&candidate.cookie_hash)?; - continue; - } - let claims = match state.heimdall.verify_refresh(&completion).await { - Ok(value) => value, - Err(error) => { - tracing::warn!(%error, session_id=%candidate.heimdall_session_id, "Heimdall refresh receipt failed verification"); - continue; - } - }; - if claims.sid != candidate.heimdall_session_id - || secret_hash(&format!("heimdall-account:{}", claims.account_id)) - != candidate.account_subject_hash - { - tracing::warn!(session_id=%candidate.heimdall_session_id, "Heimdall refresh changed local session custody"); - continue; - } - let session = completion - .session - .as_ref() - .context("Heimdall refresh omitted session summary")?; - let refresh = completion - .refresh - .as_ref() - .context("Heimdall refresh omitted refresh expiry")?; - let refresh_claim = completion - .refresh_token - .as_deref() - .context("Heimdall refresh omitted rotated refresh claim")?; - state.auth.lock().await.apply_refresh( - &candidate.cookie_hash, - RefreshedSession { - expected_access_revision: candidate.access_revision, - access_revision: claims.access_revision, - capabilities: claims.capabilities, - access_expires_at: DateTime::from_timestamp(claims.exp as i64, 0) - .context("Heimdall refresh expiry is invalid")?, - refresh_expires_at: refresh.expires_at.parse()?, - refresh_claim, - }, - )?; - debug_assert_eq!(session.session_id, candidate.heimdall_session_id); - } - Ok(()) -} - -fn refresh_idempotency_key(heimdall_session_id: &str) -> String { - format!("refresh:{heimdall_session_id}:{}", uuid::Uuid::new_v4()) -} - -async fn authenticated_session(headers: &HeaderMap, state: &AppState) -> Option { - let raw_cookie = cookie_value(headers)?; - state - .auth - .lock() - .await - .account_for_cookie(raw_cookie, Utc::now()) -} - -fn cookie_value(headers: &HeaderMap) -> Option<&str> { - headers - .get(header::COOKIE) - .and_then(|v| v.to_str().ok()) - .and_then(|cookies| { - cookies - .split(';') - .map(str::trim) - .find_map(|cookie| cookie.strip_prefix("ghostlight_session=")) - }) -} - -async fn session_runtime( - state: &AppState, - account_hash: &str, -) -> anyhow::Result> { - let campaign_id = state.auth.lock().await.selected_campaign(account_hash); - match campaign_id { - Some(id) => { - let runtime = state.registry.runtime(id).await?; - let campaign = load_campaign(&runtime.store)?; - campaign_member_for_account(&runtime.store, &campaign, account_hash)?; - Ok(Some(runtime)) - } - None => Ok(None), - } -} - -async fn select_campaign( - state: &AppState, - account_hash: &str, - campaign_id: uuid::Uuid, -) -> anyhow::Result<()> { - let runtime = state.registry.runtime(campaign_id).await?; - let campaign = load_campaign(&runtime.store)?; - campaign_member_for_account(&runtime.store, &campaign, account_hash)?; - state - .auth - .lock() - .await - .select_campaign(account_hash, campaign_id) -} - -fn load_campaign(store: &CampaignStore) -> anyhow::Result { - let id = store - .keys("campaign.v1")? - .into_iter() - .next() - .ok_or_else(|| anyhow::anyhow!("campaign missing"))?; - store - .load("campaign.v1", &id)? - .map(|(_, c)| c) - .ok_or_else(|| anyhow::anyhow!("campaign missing")) -} - -fn campaign_model_policy( - store: &CampaignStore, - campaign_id: uuid::Uuid, -) -> ( - Option, - Vec, -) { - let publication = store - .load::( - "session_zero_publication.v1", - &campaign_id.to_string(), - ) - .ok() - .flatten() - .map(|(_, publication)| publication); - let Some(publication) = publication else { - return (None, vec![]); - }; - let mut boundaries = publication.approved_brief.aggregate_boundaries.clone(); - if let Some((_, active)) = store - .load::( - "active_contract_boundary_policy.v1", - &campaign_id.to_string(), - ) - .ok() - .flatten() - && active.review_session_zero_id != publication.session_zero_id - { - boundaries = active.aggregate_boundaries; - } - (Some(publication.contract), boundaries) -} - -fn campaign_vault_id(store: &CampaignStore, campaign_id: uuid::Uuid) -> anyhow::Result { - let (_, contract) = store - .load::( - "campaign_contract.v1", - &campaign_id.to_string(), - )? - .ok_or_else(|| anyhow::anyhow!("campaign contract is missing"))?; - canonical_vault_id(&contract.vault_provider) - .map(str::to_owned) - .ok_or_else(|| anyhow::anyhow!("campaign refers to unavailable lore Vault")) -} - -async fn migrate_legacy_campaign_memberships( - registry: &CampaignRegistry, - auth: &LegacyAuthState, -) -> anyhow::Result<()> { - let mut owners = BTreeMap::>::new(); - for (account_hash, campaign_id) in &auth.session_campaigns { - owners - .entry(*campaign_id) - .or_default() - .insert(account_hash.clone()); - } - for (account_hash, campaign_ids) in &auth.session_campaign_ids { - for campaign_id in campaign_ids { - owners - .entry(*campaign_id) - .or_default() - .insert(account_hash.clone()); - } - } - for campaign_id in registry.list().await { - let runtime = registry.runtime(campaign_id).await?; - if runtime - .store - .load::( - "campaign_membership.v1", - &campaign_id.to_string(), - )? - .is_some() - { - continue; - } - let campaign = load_campaign(&runtime.store)?; - let account_hashes = owners - .get(&campaign_id) - .cloned() - .unwrap_or_default() - .into_iter() - .collect::>(); - let receipt = GovernanceMigrationReceipt { - schema: "ghostlight.governance_migration_receipt.v1".into(), - campaign_id, - status: if account_hashes.len() == 1 { - "migrated".into() - } else { - "quarantined_ambiguous_owner".into() - }, - account_hashes: account_hashes.clone(), - actor_id: campaign.player_actor_id.clone(), - created_at: chrono::Utc::now(), - }; - if account_hashes.len() == 1 { - let member_id = format!("member:{}", uuid::Uuid::new_v4().simple()); - let membership = ghostlight_dungeon::session_zero::CampaignMembership { - schema: "ghostlight.campaign_membership.v1".into(), - campaign_id, - governance_epoch: 0, - host_member_id: member_id.clone(), - members: BTreeMap::from([( - member_id.clone(), - ghostlight_dungeon::session_zero::CampaignMember { - member_id, - account_hash: account_hashes[0].clone(), - display_name: "Player".into(), - actor_id: campaign.player_actor_id.clone(), - is_host: true, - active: true, - cell_allowance: 8, - }, - )]), - extraordinary_permissions: BTreeMap::new(), - }; - runtime.store.insert( - "campaign_membership.v1", - "ghostlight.campaign_membership.v1", - &campaign_id.to_string(), - &membership, - )?; - runtime.store.insert( - "campaign_governance.v1", - "ghostlight.campaign_governance.v1", - &campaign_id.to_string(), - &ghostlight_dungeon::session_zero::CampaignGovernance { - schema: "ghostlight.campaign_governance.v1".into(), - campaign_id, - governance_epoch: 0, - time_advance_policy: "unanimous".into(), - pooled_cell_ceiling: 8, - cooperative_shared_scene_only: true, - pvp_enabled: false, - }, - )?; - } - let _ = runtime.store.insert( - "governance_migration_receipt.v1", - "ghostlight.governance_migration_receipt.v1", - &campaign_id.to_string(), - &receipt, - ); - } - Ok(()) -} - -fn campaign_member_for_account( - store: &CampaignStore, - campaign: &Campaign, - account_hash: &str, -) -> anyhow::Result { - if let Some((_, membership)) = store - .load::( - "campaign_membership.v1", - &campaign.id.to_string(), - )? - { - return membership - .member_for_account(account_hash) - .cloned() - .ok_or_else(|| anyhow::anyhow!("account is not a campaign member")); - } - Err(anyhow::anyhow!( - "campaign membership is missing or quarantined for operator review" - )) -} - -fn migrate_default_campaign(runtime_root: &std::path::Path) -> anyhow::Result<()> { - let legacy_directory = runtime_root.join("campaigns/default"); - let legacy_store_path = legacy_directory.join("campaign.cc"); - if !legacy_store_path.is_file() { - std::fs::create_dir_all(runtime_root.join("campaigns"))?; - return Ok(()); - } - let keys = CampaignStore::open(&legacy_store_path)?.keys("campaign.v1")?; - if keys.is_empty() { - return Ok(()); - } - if keys.len() != 1 { - return Err(anyhow::anyhow!( - "legacy default store contains multiple campaigns" - )); - } - let id = uuid::Uuid::parse_str(&keys[0])?; - let target = runtime_root.join("campaigns").join(id.to_string()); - if target.exists() { - return Err(anyhow::anyhow!( - "legacy campaign migration target already exists" - )); - } - std::fs::rename(legacy_directory, target)?; - Ok(()) -} - -#[derive(Serialize)] -struct ErrorBody { - error: String, -} - -fn player_safe_strategic_failure(error: &anyhow::Error) -> ErrorBody { - let private_error_chain: String = format!("{error:#}").chars().take(4_000).collect(); - tracing::warn!( - error = %private_error_chain, - "private strategic simulation failed without mutation" - ); - ErrorBody { - error: "The strategic world simulation could not produce a valid atomic wave. No world state changed; retry when ready." - .into(), - } -} - -fn player_safe_partial_catch_up_failure( - error: &anyhow::Error, - start_revision: u64, - current_revision: u64, -) -> ErrorBody { - let private_error_chain: String = format!("{error:#}").chars().take(4_000).collect(); - let committed_ticks = current_revision.saturating_sub(start_revision); - tracing::warn!( - error = %private_error_chain, - start_revision, - current_revision, - committed_ticks, - "private return catch-up failed after earlier atomic ticks committed" - ); - ErrorBody { - error: format!( - "The world advanced {committed_ticks} strategic tick(s) while you were away, then the next atomic wave was rejected without changing revision {current_revision}. Refresh campaign state before acting again." - ), - } -} - -fn player_safe_assessment_failure(error: &anyhow::Error) -> ErrorBody { - let private_error_chain: String = format!("{error:#}").chars().take(4_000).collect(); - tracing::warn!( - error = %private_error_chain, - "private action assessment failed without mutation" - ); - ErrorBody { - error: "Ghostlight could not produce a valid stakes assessment after one correction. No world state changed; your draft is preserved so you can retry or revise the attempt." - .into(), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use axum::{body::Body, http::Request}; - use ghostlight_dungeon::domain::{ActorState, BranchOrigin, Location}; - use tower::ServiceExt; - - #[test] - fn empty_campaign_choice_projection_does_not_change_session_zero_surface() { - let mut surface = serde_json::json!({ - "surface":{"root":{"children":[]}}, - "commands":[] - }); - let before = surface.clone(); - - append_campaign_choices(&mut surface, vec![]).unwrap(); - - assert_eq!(surface, before); - } - - #[test] - fn strategic_failure_projection_never_contains_private_model_diagnostics() { - let private = anyhow::anyhow!( - "the hidden convoy chooses a route at dawn; verifier returned private output" - ); - let projected = player_safe_strategic_failure(&private); - - assert_eq!( - projected.error, - "The strategic world simulation could not produce a valid atomic wave. No world state changed; retry when ready." - ); - assert!(!projected.error.contains("convoy")); - assert!(!projected.error.contains("verifier")); - } - - #[test] - fn partial_catch_up_failure_reports_committed_progress_without_private_diagnostics() { - let private = anyhow::anyhow!( - "the hidden convoy emitted two actor_activity effects from a private Persona" - ); - let projected = player_safe_partial_catch_up_failure(&private, 92, 94); - - assert_eq!( - projected.error, - "The world advanced 2 strategic tick(s) while you were away, then the next atomic wave was rejected without changing revision 94. Refresh campaign state before acting again." - ); - assert!(!projected.error.contains("convoy")); - assert!(!projected.error.contains("actor_activity")); - assert!(!projected.error.contains("Persona")); - } - - #[test] - fn assessment_failure_projection_never_contains_private_model_diagnostics() { - let private = anyhow::anyhow!( - "stage action_assessment, instance /strong_effect/clock_advances/secret, schema /minimum: rejected hidden value" - ); - let projected = player_safe_assessment_failure(&private); - - assert_eq!( - projected.error, - "Ghostlight could not produce a valid stakes assessment after one correction. No world state changed; your draft is preserved so you can retry or revise the attempt." - ); - assert!(!projected.error.contains("action_assessment")); - assert!(!projected.error.contains("clock_advances")); - assert!(!projected.error.contains("schema")); - } - - fn seed(name: &str) -> Campaign { - let actor = ActorState { - id: "player".into(), - name: "Player".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }; - Campaign { - schema: "ghostlight.campaign.v1".into(), - id: uuid::Uuid::new_v4(), - name: name.into(), - revision: 0, - branch_origin: BranchOrigin { - canon_cutoff: "test".into(), - evidence_receipt_ids: vec![], - }, - world_time: chrono::Utc::now(), - tick_hours: 6, - player_actor_id: "player".into(), - locations: BTreeMap::from([( - "room".into(), - Location { - id: "room".into(), - name: "Room".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - )]), - actors: BTreeMap::from([("player".into(), actor)]), - institutions: BTreeMap::new(), - clocks: BTreeMap::new(), - facts: BTreeMap::new(), - civic_systems: BTreeMap::new(), - transcript: vec![], - last_player_activity: chrono::Utc::now(), - pending_ticks: 0, - away_ticks_processed: 0, - events: vec![], - news: vec![], - canon_candidates: BTreeMap::new(), - gestalts: BTreeMap::new(), - gestalt_members: BTreeMap::new(), - pending_world_proposals: vec![], - agency_profiles: BTreeMap::new(), - agency_relations: BTreeMap::new(), - gestalt_lineages: BTreeMap::new(), - resolution_policy: Default::default(), - resolution_pins: BTreeMap::new(), - resolution_cover: None, - nemesis_attention_history: Vec::new(), - strategic_tick_count: 0, - } - } - - fn add_aggregate_clock_witness(campaign: &mut Campaign) { - campaign.institutions.insert( - "channel-watch".into(), - ghostlight_dungeon::domain::InstitutionState { - id: "channel-watch".into(), - name: "Channel Watch".into(), - resources: Vec::new(), - goals: Vec::new(), - posture: "observing".into(), - }, - ); - ghostlight_dungeon::resolution::ensure_agency_profiles(campaign); - campaign - .agency_profiles - .get_mut("channel-watch") - .expect("fixture institution has a profile") - .active_leaf = false; - } - - fn empty_app_state(root: &std::path::Path) -> AppState { - let registry = CampaignRegistry::new(root.join("campaigns")).unwrap(); - let wrapping_key = root.join("session-wrapping.key"); - std::fs::write(&wrapping_key, [7_u8; 32]).unwrap(); - let auth = AppSessionOwner::open(root.join("app-sessions.cc"), &wrapping_key).unwrap(); - AppState { - registry, - exports_root: root.join("exports"), - session_zeros: SessionZeroRegistry::new(root.join("session-zero")).unwrap(), - session_zero_director: None, - entitlements: Arc::new(FixtureEntitlementPort), - auth: Arc::new(Mutex::new(auth)), - heimdall: Arc::new(HeimdallClient::fixture()), - model_status: ModelRuntimeStatus { - provider: "fixture".into(), - fast_model: "fixture".into(), - balanced_model: "fixture".into(), - capable_model: "fixture".into(), - readiness: "ready".into(), - }, - compiler: None, - assessor: None, - model: None, - expansion_previews: Arc::new(Mutex::new(BTreeMap::new())), - fission_previews: Arc::new(Mutex::new(BTreeMap::new())), - live_turns: Arc::new(AtomicUsize::new(0)), - live_turn_started: Arc::new(Notify::new()), - live_turn_finished: Arc::new(Notify::new()), - live_commit_gate: Arc::new(RwLock::new(())), - mesh: MeshPublisher::open(root.join("mesh.cc"), None).unwrap(), - } - } - - async fn fixture_session(state: &AppState, account_id: &str) -> (String, String) { - let cookie = state - .auth - .lock() - .await - .create_session(NewSession { - account_id, - heimdall_session_id: "fixture-heimdall-session", - access_revision: 1, - capabilities: vec!["app_access".into()], - access_expires_at: Utc::now() + chrono::Duration::hours(1), - refresh_expires_at: Utc::now() + chrono::Duration::days(7), - refresh_claim: "fixture-refresh", - }) - .unwrap(); - let account_hash = state - .auth - .lock() - .await - .account_for_cookie(&cookie, Utc::now()) - .unwrap(); - (cookie, account_hash) - } - - #[tokio::test] - async fn public_router_exposes_only_the_eve_product_boundary() { - let dir = tempfile::tempdir().unwrap(); - let state = empty_app_state(dir.path()); - let app = app_router(state, dir.path().join("web")); - for retired in [ - "/api/command", - "/api/session-zero", - "/api/auth/heimdall/start", - ] { - let response = app - .clone() - .oneshot(Request::builder().uri(retired).body(Body::empty()).unwrap()) - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::NOT_FOUND); - } - let response = app - .oneshot( - Request::builder() - .uri("/api/eve/surfaces/ghostlight.play") - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::OK); - } - - #[tokio::test] - async fn local_session_cookie_resolves_only_to_heimdall_account_subject_hash() { - let dir = tempfile::tempdir().unwrap(); - let state = empty_app_state(dir.path()); - let (cookie, account_hash) = fixture_session(&state, "acct-1").await; - let mut headers = HeaderMap::new(); - headers.insert( - header::COOKIE, - HeaderValue::from_str(&format!("ghostlight_session={cookie}")).unwrap(), - ); - assert_eq!( - authenticated_session(&headers, &state).await, - Some(account_hash) - ); - } - - #[tokio::test] - async fn native_cultmesh_surface_uses_the_same_heimdall_backed_app_session() { - use base64::{Engine, engine::general_purpose::STANDARD}; - use cultnet_rs::CultNetMessage; - - let dir = tempfile::tempdir().unwrap(); - let state = empty_app_state(dir.path()); - let (session_token, account_hash) = fixture_session(&state, "native-owner").await; - let request = CultNetMessage::OperationRequest { - message_id: "native-surface-1".into(), - service_id: native_cultmesh::NATIVE_SERVICE_ID.into(), - operation: native_cultmesh::NATIVE_SURFACE_GET.into(), - payload_schema: "ghostlight.native_surface_get.v1".into(), - payload_encoding: "messagepack-base64".into(), - payload: STANDARD.encode( - rmp_serde::to_vec_named(&native_cultmesh::NativeSurfaceGetCommand { - schema: "ghostlight.native_surface_get.v1".into(), - session_token, - invite: None, - }) - .unwrap(), - ), - source_runtime_id: Some("native-test".into()), - target_runtime_id: None, - }; - - let response = native_cultmesh::handle_operation(state, request).await; - let CultNetMessage::OperationResponse { - status, - payload_schema, - payload, - .. - } = response - else { - panic!("native boundary returned a non-operation response"); - }; - assert_eq!(status, "accepted"); - assert_eq!(payload_schema, "gamecult.eve.surface.v1"); - let surface: serde_json::Value = - rmp_serde::from_slice(&STANDARD.decode(payload).unwrap()).unwrap(); - assert_eq!(surface["schema"], "gamecult.eve.surface.v1"); - let encoded = serde_json::to_string(&surface).unwrap(); - assert!(!encoded.contains(&account_hash)); - assert!(!encoded.contains("sessionToken")); - } - - #[test] - fn eve_ingress_binds_each_transport_without_changing_command_semantics() { - let invocation = EveCommandInvocation { - schema: "gamecult.eve.command_invocation.v1".into(), - provider_id: EVE_PROVIDER_ID.into(), - surface_id: EVE_SURFACE_ID.into(), - operation: EveOperation { - operation_id: "world.speak".into(), - schema_id: Some("ghostlight.world_speak.v1".into()), - idempotency_key: Some("native-transport-witness".into()), - route_hint: EveRouteHint { - source_version: Some(1), - transport: Some("cultnet-rudp".into()), - }, - }, - payload: serde_json::json!({ - "expected_revision":1, - "text":"Hello from a native client." - }), - issued_at: Utc::now().to_rfc3339(), - client_id: "native-test".into(), - command_boundary: EVE_COMMAND_BOUNDARY.into(), - receipt_schema: EVE_RESULT_SCHEMA.into(), - }; - - assert!(validate_eve_invocation(&invocation, "cultnet-rudp").is_ok()); - assert!(validate_eve_invocation(&invocation, "https-json").is_err()); - } - - #[test] - fn each_refresh_attempt_has_a_distinct_command_identity() { - let first = refresh_idempotency_key("heimdall-session"); - let second = refresh_idempotency_key("heimdall-session"); - - assert_ne!(first, second); - assert!(first.starts_with("refresh:heimdall-session:")); - } - - #[test] - fn persisted_idempotency_results_do_not_store_one_time_capability_urls() { - let result = serde_json::json!({ - "schema":"gamecult.eve.command_result.v1", - "receipt":{"state":"accepted"}, - "transientProjection":{"surface":{"root":{"children":[{"props":{"uri":"/secret/token"}}]}}} - }); - for operation in ["session_zero.invites.create", "campaign.export"] { - let persisted = persistable_eve_result(operation, &result); - assert!(persisted.get("transientProjection").is_none()); - assert_eq!(persisted["receipt"]["state"], "accepted"); - } - assert_eq!(persistable_eve_result("world.assess", &result), result); - } - - #[test] - fn app_session_cookie_survives_browser_relaunch_until_refresh_expiry() { - let now = Utc::now(); - let header = app_session_cookie("opaque-cookie", now + chrono::Duration::days(7), now); - let value = header.to_str().unwrap(); - - assert!(value.contains("Max-Age=604800")); - assert!(value.contains("HttpOnly")); - assert!(value.contains("Secure")); - assert!(value.contains("SameSite=Lax")); - assert!(value.contains("Path=/ghostlight/")); - } - - #[tokio::test] - async fn eve_receipt_uses_an_explicit_nonmutating_progress_message() { - let invocation = EveCommandInvocation { - schema: "gamecult.eve.command_invocation.v1".into(), - provider_id: "ghostlight".into(), - surface_id: EVE_SURFACE_ID.into(), - operation: EveOperation { - operation_id: "session_zero.decision.retry".into(), - schema_id: None, - idempotency_key: Some("retry-message-witness".into()), - route_hint: EveRouteHint { - source_version: Some(7), - transport: None, - }, - }, - payload: serde_json::json!({"bindings":{}}), - issued_at: Utc::now().to_rfc3339(), - client_id: "test-client".into(), - command_boundary: EVE_COMMAND_BOUNDARY.into(), - receipt_schema: EVE_RESULT_SCHEMA.into(), - }; - let response = kernel_response_to_eve( - invocation, - Json(serde_json::json!({ - "status":"counter_retry_started", - "message":"Retry started without changing Session Zero state." - })) - .into_response(), - ) - .await; - let bytes = axum::body::to_bytes(response.into_body(), 1024 * 1024) - .await - .unwrap(); - let result: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); - - assert_eq!( - result["receipt"]["message"], - "Retry started without changing Session Zero state." - ); - assert_eq!(result["receipt"]["state"], "accepted"); - assert_eq!( - result["draftDirective"], - serde_json::json!({"clear":true,"bindingNames":[]}) - ); - } - - #[test] - fn counter_retry_relaunches_from_the_persisted_snapshot_without_state_change() { - let mut snapshot = SessionZeroState::new( - "Retry witness".into(), - "fixture".into(), - "account:host".into(), - "Host".into(), - ) - .unwrap(); - let member_id = snapshot.host_member_id.clone(); - snapshot.decisions.insert( - "decision:countered".into(), - ghostlight_dungeon::session_zero::SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:countered".into(), - owner_member_id: Some(member_id.clone()), - prompt: "Accept this bargain?".into(), - proposed_resolution: "The retired proposal".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: Some("Use the player's exact replacement.".into()), - material: true, - resolved: false, - }, - ); - let before = snapshot.clone(); - - assert_eq!( - pending_counter_retry_target( - &snapshot, - "account:host", - snapshot.revision, - "decision:countered", - ) - .unwrap(), - (format!("private:{member_id}"), Some(member_id)) - ); - assert_eq!(snapshot, before); - assert!( - pending_counter_retry_target( - &snapshot, - "account:intruder", - snapshot.revision, - "decision:countered", - ) - .is_err() - ); - assert!( - pending_counter_retry_target( - &snapshot, - "account:host", - snapshot.revision + 1, - "decision:countered", - ) - .is_err() - ); - } - - #[test] - fn decision_request_uses_an_explicit_action_instead_of_boolean_overloading() { - let decline: SessionZeroDecisionRequest = serde_json::from_value(serde_json::json!({ - "expected_revision": 9, - "decision_id": "decision:opening", - "action": "decline", - "counter": null - })) - .unwrap(); - assert!(decline.action == SessionZeroDecisionRequestAction::Decline); - - let legacy = serde_json::from_value::(serde_json::json!({ - "expected_revision": 9, - "decision_id": "decision:opening", - "accept": false, - "counter": null - })); - assert!(legacy.is_err()); - } - - #[tokio::test] - async fn interactive_model_work_cancels_background_inference_and_excludes_its_commit_gate() { - let dir = tempfile::tempdir().unwrap(); - let state = empty_app_state(dir.path()); - state - .mesh - .publish_snapshot(&[], &[], &state.model_status, 0) - .unwrap(); - let trigger_state = state.clone(); - let (entered_tx, entered_rx) = tokio::sync::oneshot::channel(); - let (release_tx, release_rx) = tokio::sync::oneshot::channel(); - let trigger = tokio::spawn(async move { - run_live_model_work(&trigger_state, async move { - let _ = entered_tx.send(()); - let _ = release_rx.await; - }) - .await; - }); - - let result = tokio::time::timeout( - std::time::Duration::from_millis(100), - await_background_work(&state, true, std::future::pending::>()), - ) - .await - .expect("background work did not yield") - .unwrap(); - assert!(result.is_none()); - entered_rx.await.unwrap(); - assert_eq!(state.live_turns.load(Ordering::SeqCst), 1); - assert_eq!( - state.mesh.health().unwrap()["scheduler"]["live_turn_pressure"], - 1 - ); - assert!(state.live_commit_gate.clone().try_write_owned().is_err()); - - let _ = release_tx.send(()); - trigger.await.unwrap(); - assert_eq!(state.live_turns.load(Ordering::SeqCst), 0); - assert_eq!( - state.mesh.health().unwrap()["scheduler"]["live_turn_pressure"], - 0 - ); - assert!(state.live_commit_gate.clone().try_write_owned().is_ok()); - } - - #[tokio::test] - async fn live_turn_completion_announces_only_after_releasing_its_commit_guard() { - let dir = tempfile::tempdir().unwrap(); - let state = empty_app_state(dir.path()); - let live = LiveTurnGuard::enter(&state).await; - let finished = state.live_turn_finished.notified(); - tokio::pin!(finished); - finished.as_mut().enable(); - - assert!(state.live_commit_gate.clone().try_write_owned().is_err()); - drop(live); - - tokio::time::timeout(std::time::Duration::from_millis(100), &mut finished) - .await - .expect("idle boundary was not announced"); - assert_eq!(state.live_turns.load(Ordering::SeqCst), 0); - assert!(state.live_commit_gate.clone().try_write_owned().is_ok()); - } - - #[tokio::test] - async fn queued_live_work_announces_pressure_before_waiting_for_a_background_commit() { - let dir = tempfile::tempdir().unwrap(); - let state = empty_app_state(dir.path()); - let background_commit = state.live_commit_gate.clone().write_owned().await; - let live_started = state.live_turn_started.notified(); - tokio::pin!(live_started); - live_started.as_mut().enable(); - - let live_state = state.clone(); - let (entered_tx, mut entered_rx) = tokio::sync::oneshot::channel(); - let live = tokio::spawn(async move { - run_live_model_work(&live_state, async move { - let _ = entered_tx.send(()); - }) - .await; - }); - - tokio::time::timeout(std::time::Duration::from_millis(100), &mut live_started) - .await - .expect("queued live work did not announce pressure"); - assert_eq!(state.live_turns.load(Ordering::SeqCst), 1); - assert!(entered_rx.try_recv().is_err()); - assert!( - await_background_work(&state, true, async { Ok::<_, anyhow::Error>(()) }) - .await - .unwrap() - .is_none() - ); - - drop(background_commit); - live.await.unwrap(); - assert_eq!(state.live_turns.load(Ordering::SeqCst), 0); - } - - #[tokio::test] - async fn cancelling_live_work_queued_at_the_commit_gate_releases_its_pressure() { - let dir = tempfile::tempdir().unwrap(); - let state = empty_app_state(dir.path()); - let _background_commit = state.live_commit_gate.clone().write_owned().await; - let live_started = state.live_turn_started.notified(); - tokio::pin!(live_started); - live_started.as_mut().enable(); - - let live_state = state.clone(); - let live = tokio::spawn(async move { - run_live_model_work(&live_state, std::future::pending::<()>()).await; - }); - tokio::time::timeout(std::time::Duration::from_millis(100), &mut live_started) - .await - .expect("queued live work did not announce pressure"); - assert_eq!(state.live_turns.load(Ordering::SeqCst), 1); - - live.abort(); - assert!(live.await.unwrap_err().is_cancelled()); - assert_eq!(state.live_turns.load(Ordering::SeqCst), 0); - } - - #[tokio::test] - async fn due_ticks_without_simulatable_agency_advance_deterministically_without_a_model() { - let dir = tempfile::tempdir().unwrap(); - let state = empty_app_state(dir.path()); - let mut campaign = seed("Quiet world"); - add_aggregate_clock_witness(&mut campaign); - let original_player = campaign.actors["player"].clone(); - let original_time = campaign.world_time; - campaign.last_player_activity = chrono::Utc::now() - chrono::Duration::minutes(90); - campaign.clocks.insert( - "tide".into(), - ghostlight_dungeon::domain::WorldClock { - id: "tide".into(), - label: "Tide turns".into(), - progress: 0, - threshold: 4, - consequence: "the channel narrows".into(), - consequence_scope: ghostlight_dungeon::domain::WorldEventScope { - institution_ids: vec!["channel-watch".into()], - location_ids: vec!["room".into()], - ..Default::default() - }, - }, - ); - let runtime = state - .registry - .create_unadmitted_fixture(campaign.clone(), vec![], vec![]) - .await - .unwrap(); - process_due_ticks( - &state, - &runtime, - ghostlight_dungeon::domain::TickSource::Scheduler, - true, - ) - .await - .unwrap(); - - let advanced = load_campaign(&runtime.store).unwrap(); - assert_eq!(advanced.away_ticks_processed, 1); - assert_eq!(advanced.strategic_tick_count, 1); - assert_eq!(advanced.clocks["tide"].progress, 1); - assert_eq!( - advanced.world_time, - original_time + chrono::Duration::hours(6) - ); - assert_eq!(advanced.actors["player"], original_player); - let operator = state.mesh.operator_surface(campaign.id).unwrap(); - let operator_title = operator["surface"]["root"]["children"][0]["props"]["title"] - .as_str() - .unwrap(); - assert!( - operator_title.starts_with(&format!("Revision {} ·", advanced.revision)), - "strategic commits must publish their own derived operator projection" - ); - } - - #[tokio::test] - async fn player_strategic_wait_uses_the_same_tick_commit_and_resets_away_accounting() { - let dir = tempfile::tempdir().unwrap(); - let state = empty_app_state(dir.path()); - let mut campaign = seed("Player wait world"); - add_aggregate_clock_witness(&mut campaign); - let original_time = campaign.world_time; - campaign.last_player_activity = chrono::Utc::now() - chrono::Duration::hours(4); - campaign.away_ticks_processed = 3; - campaign.pending_ticks = 2; - campaign.clocks.insert( - "pressure".into(), - ghostlight_dungeon::domain::WorldClock { - id: "pressure".into(), - label: "Pressure rises".into(), - progress: 0, - threshold: 4, - consequence: "the settlement must choose".into(), - consequence_scope: ghostlight_dungeon::domain::WorldEventScope { - institution_ids: vec!["channel-watch".into()], - location_ids: vec!["room".into()], - ..Default::default() - }, - }, - ); - let runtime = state - .registry - .create_unadmitted_fixture(campaign.clone(), vec![], vec![]) - .await - .unwrap(); - - let result = advance_one_strategic_tick( - &state, - &runtime, - campaign, - ghostlight_dungeon::domain::TickSource::PlayerWait, - false, - ) - .await - .unwrap(); - assert!(result.is_some()); - - let advanced = load_campaign(&runtime.store).unwrap(); - assert_eq!( - advanced.world_time, - original_time + chrono::Duration::hours(i64::from(advanced.tick_hours)) - ); - assert_eq!(advanced.clocks["pressure"].progress, 1); - assert_eq!(advanced.strategic_tick_count, 1); - assert_eq!(advanced.away_ticks_processed, 0); - assert_eq!(advanced.pending_ticks, 0); - assert!(advanced.last_player_activity > chrono::Utc::now() - chrono::Duration::minutes(1)); - } - - #[tokio::test] - async fn campaign_selection_is_derived_from_exact_membership() { - let dir = tempfile::tempdir().unwrap(); - let state = empty_app_state(dir.path()); - let (_cookie, account_hash) = fixture_session(&state, "owner").await; - let campaign = seed("Membership-bound"); - let runtime = state - .registry - .create_unadmitted_fixture(campaign.clone(), vec![], vec![]) - .await - .unwrap(); - runtime - .store - .insert( - "campaign_membership.v1", - "ghostlight.campaign_membership.v1", - &campaign.id.to_string(), - &ghostlight_dungeon::session_zero::CampaignMembership { - schema: "ghostlight.campaign_membership.v1".into(), - campaign_id: campaign.id, - governance_epoch: 0, - host_member_id: "member:owner".into(), - members: BTreeMap::from([( - "member:owner".into(), - ghostlight_dungeon::session_zero::CampaignMember { - member_id: "member:owner".into(), - account_hash: account_hash.clone(), - display_name: "Owner".into(), - actor_id: "player".into(), - is_host: true, - active: true, - cell_allowance: 8, - }, - )]), - extraordinary_permissions: BTreeMap::new(), - }, - ) - .unwrap(); - let session_zero = SessionZeroState::new( - "Still negotiating".into(), - "fixture".into(), - account_hash.clone(), - "Owner".into(), - ) - .unwrap(); - let projected = - session_zero_surface_with_campaign_choices(&state, &session_zero, &account_hash) - .await - .unwrap(); - let encoded = serde_json::to_string(&projected).unwrap(); - assert!(encoded.contains("Your existing campaigns")); - assert!(encoded.contains("Continue Membership-bound")); - assert!(encoded.contains(&campaign.id.to_string())); - assert!(encoded.contains("campaign.select")); - select_campaign(&state, &account_hash, campaign.id) - .await - .unwrap(); - assert_eq!( - load_campaign( - &session_runtime(&state, &account_hash) - .await - .unwrap() - .unwrap() - .store - ) - .unwrap() - .id, - campaign.id - ); - assert!( - select_campaign(&state, "sha256:not-a-member", campaign.id) - .await - .is_err() - ); - } - - #[tokio::test] - async fn campaign_export_is_an_exact_membership_bound_single_use_snapshot() { - let dir = tempfile::tempdir().unwrap(); - let state = empty_app_state(dir.path()); - let (owner_cookie, account_hash) = fixture_session(&state, "export-owner").await; - let (intruder_cookie, _) = fixture_session(&state, "export-intruder").await; - let campaign = seed("Export witness"); - let runtime = state - .registry - .create_unadmitted_fixture(campaign.clone(), vec![], vec![]) - .await - .unwrap(); - let expected_export = load_campaign(&runtime.store).unwrap(); - runtime - .store - .insert( - "campaign_membership.v1", - "ghostlight.campaign_membership.v1", - &campaign.id.to_string(), - &ghostlight_dungeon::session_zero::CampaignMembership { - schema: "ghostlight.campaign_membership.v1".into(), - campaign_id: campaign.id, - governance_epoch: 0, - host_member_id: "member:owner".into(), - members: BTreeMap::from([( - "member:owner".into(), - ghostlight_dungeon::session_zero::CampaignMember { - member_id: "member:owner".into(), - account_hash: account_hash.clone(), - display_name: "Owner".into(), - actor_id: "player".into(), - is_host: true, - active: true, - cell_allowance: 8, - }, - )]), - extraordinary_permissions: BTreeMap::new(), - }, - ) - .unwrap(); - select_campaign(&state, &account_hash, campaign.id) - .await - .unwrap(); - let app = app_router(state.clone(), dir.path().join("web")); - let invocation = serde_json::json!({ - "schema":"gamecult.eve.command_invocation.v1", - "providerId":EVE_PROVIDER_ID, - "surfaceId":EVE_SURFACE_ID, - "operation":{ - "operationId":"campaign.export", - "schemaId":"ghostlight.campaign_export_request.v1", - "idempotencyKey":"export-command-1", - "routeHint":{ - "sourceVersion":campaign_interface_version(&expected_export), - "transport":"https-json" - } - }, - "payload":{}, - "issuedAt":Utc::now().to_rfc3339(), - "clientId":"export-test", - "commandBoundary":EVE_COMMAND_BOUNDARY, - "receiptSchema":EVE_RESULT_SCHEMA - }); - let command_response = app - .clone() - .oneshot( - Request::builder() - .method("POST") - .uri("/api/eve/commands") - .header("content-type", "application/json") - .header(header::COOKIE, format!("ghostlight_session={owner_cookie}")) - .body(Body::from(serde_json::to_vec(&invocation).unwrap())) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(command_response.status(), StatusCode::OK); - let command_bytes = axum::body::to_bytes(command_response.into_body(), 1024 * 1024) - .await - .unwrap(); - let result: serde_json::Value = serde_json::from_slice(&command_bytes).unwrap(); - assert_eq!(result["receipt"]["state"], "accepted"); - let download = &result["transientProjection"]["surface"]["root"]["children"][1]; - assert_eq!(download["kind"], "resource.download"); - let uri = download["props"]["uri"].as_str().unwrap(); - let internal_uri = uri - .strip_prefix("/ghostlight") - .expect("public resource URI must stay below the Ghostlight mount"); - let token = uri.rsplit('/').next().unwrap(); - assert!( - !state - .auth - .lock() - .await - .persisted_bytes_contain(token) - .unwrap() - ); - - let intruder = app - .clone() - .oneshot( - Request::builder() - .uri(internal_uri) - .header( - header::COOKIE, - format!("ghostlight_session={intruder_cookie}"), - ) - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(intruder.status(), StatusCode::NOT_FOUND); - - let download_response = app - .clone() - .oneshot( - Request::builder() - .uri(internal_uri) - .header(header::COOKIE, format!("ghostlight_session={owner_cookie}")) - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(download_response.status(), StatusCode::OK); - assert_eq!( - download_response.headers()[header::CONTENT_TYPE], - "application/vnd.gamecult.cultcache" - ); - let exported = axum::body::to_bytes(download_response.into_body(), 32 * 1024 * 1024) - .await - .unwrap(); - let downloaded_path = dir.path().join("downloaded.cc"); - std::fs::write(&downloaded_path, &exported).unwrap(); - let exported_store = CampaignStore::open(downloaded_path).unwrap(); - let exported_campaign = exported_store - .load::("campaign.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(exported_campaign, expected_export); - - let replay = app - .oneshot( - Request::builder() - .uri(internal_uri) - .header(header::COOKIE, format!("ghostlight_session={owner_cookie}")) - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(replay.status(), StatusCode::NOT_FOUND); - } - - #[test] - fn authority_fields_are_rejected_recursively_at_eve_ingress() { - assert!(contains_authority_field( - &serde_json::json!({"bindings":{"actor_id":"npc"}}) - )); - assert!(contains_authority_field( - &serde_json::json!({"nested":[{"memberId":"member:other"}]}) - )); - assert!(!contains_authority_field( - &serde_json::json!({"target":"member:other","text":"hello"}) - )); - } - - #[test] - fn player_http_boundary_cannot_invoke_internal_world_commands_or_npcs() { - assert!(player_http_command_allowed( - &WorldCommand::Wait { - expected_revision: 4, - minutes: 10, - }, - "player", - )); - assert!(player_http_command_allowed( - &WorldCommand::Speak { - expected_revision: 4, - actor_id: "player".into(), - text: "Hello.".into(), - intended_effect: None, - persona_response_actor_ids: BTreeSet::new(), - }, - "player", - )); - assert!(!player_http_command_allowed( - &WorldCommand::Speak { - expected_revision: 4, - actor_id: "npc".into(), - text: "I have been puppeted.".into(), - intended_effect: None, - persona_response_actor_ids: BTreeSet::new(), - }, - "player", - )); - assert!(!player_http_command_allowed( - &WorldCommand::AdvanceStrategicTick { - expected_revision: 4, - source: ghostlight_dungeon::domain::TickSource::Scheduler, - plan: None, - model_receipt_hash: None, - resolution_wave: None, - }, - "player", - )); - assert!(!player_http_command_allowed( - &WorldCommand::ReconcileGestaltPresence { - expected_revision: 4, - reason: "browser says so".into(), - plan: Default::default(), - }, - "player", - )); - assert!(player_http_command_allowed( - &WorldCommand::SetResolutionBudget { - expected_revision: 4, - expected_resolution_epoch: 2, - active_cell_budget: 8, - }, - "player", - )); - assert!(!player_http_command_allowed( - &WorldCommand::ReplaceResolutionPins { - expected_revision: 4, - expected_resolution_epoch: 2, - pins: vec![], - }, - "player", - )); - } - - #[test] - fn only_fictional_player_commands_require_return_catch_up() { - assert!(player_command_requires_return_catch_up( - &WorldCommand::Speak { - expected_revision: 4, - actor_id: "player".into(), - text: "Hello.".into(), - intended_effect: None, - persona_response_actor_ids: BTreeSet::new(), - } - )); - assert!(player_command_requires_return_catch_up( - &WorldCommand::Attempt { - actor_id: "player".into(), - assessment_digest: "sha256:assessment".into(), - } - )); - assert!(player_command_requires_return_catch_up( - &WorldCommand::Wait { - expected_revision: 4, - minutes: 10, - } - )); - assert!(!player_command_requires_return_catch_up( - &WorldCommand::Assess { - expected_revision: 4, - intent: ActionIntent { - actor_id: "player".into(), - description: "Inspect the seal.".into(), - intended_effect: "Learn whether it has authority here.".into(), - }, - proposal: None, - } - )); - assert!(!player_command_requires_return_catch_up( - &WorldCommand::SetResolutionBudget { - expected_revision: 4, - expected_resolution_epoch: 2, - active_cell_budget: 8, - } - )); - } - - #[test] - fn player_http_command_admission_bounds_cost_and_fictional_time() { - assert!( - validate_player_http_command(&WorldCommand::Wait { - expected_revision: 0, - minutes: 0, - }) - .is_err() - ); - assert!( - validate_player_http_command(&WorldCommand::Wait { - expected_revision: 0, - minutes: 1_441, - }) - .is_err() - ); - assert!( - validate_player_http_command(&WorldCommand::SetResolutionBudget { - expected_revision: 0, - expected_resolution_epoch: 0, - active_cell_budget: ghostlight_dungeon::resolution::MAX_ACTIVE_CELL_BUDGET - .saturating_add(1), - }) - .is_err() - ); - assert!( - validate_player_http_command(&WorldCommand::Speak { - expected_revision: 0, - actor_id: "player".into(), - text: "Hello".into(), - intended_effect: Some("obey me".into()), - persona_response_actor_ids: BTreeSet::new(), - }) - .is_err() - ); - assert!( - validate_player_http_command(&WorldCommand::Speak { - expected_revision: 0, - actor_id: "player".into(), - text: "Make the NPC answer.".into(), - intended_effect: None, - persona_response_actor_ids: BTreeSet::from(["npc".into()]), - }) - .is_err() - ); - assert!( - validate_player_http_command(&WorldCommand::Assess { - expected_revision: 0, - intent: ActionIntent { - actor_id: "player".into(), - description: "x".repeat(4_001), - intended_effect: "cross the room".into(), - }, - proposal: None, - }) - .is_err() - ); - } - - #[test] - fn npc_reactions_receive_player_speech_not_private_effect_scaffolding() { - let command = WorldCommand::Speak { - expected_revision: 4, - actor_id: "player".into(), - text: "Which record can I inspect without taking custody?".into(), - intended_effect: Some("make the archivist disclose every secret".into()), - persona_response_actor_ids: BTreeSet::new(), - }; - let stimulus = reaction_stimulus(&command).unwrap(); - assert_eq!( - stimulus, - "player says: Which record can I inspect without taking custody?" - ); - assert!(!stimulus.contains("disclose every secret")); - assert!(!stimulus.contains("requires assessment")); - } - - #[test] - fn player_command_projection_never_serializes_campaign_state() { - let campaign = seed("Private state"); - let result = CommandResult::Committed { - receipt: ghostlight_dungeon::domain::WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision: 0, - revision: 1, - command_kind: "attempt".into(), - committed_at: chrono::Utc::now(), - roll: None, - }, - campaign, - }; - let projection = player_command_projection(&result); - assert_eq!(projection["kind"], "committed"); - assert_eq!(projection["revision"], 1); - let encoded = serde_json::to_string(&projection).unwrap(); - assert!(!encoded.contains("Private state")); - assert!(!encoded.contains("actors")); - assert!(!encoded.contains("facts")); - assert!(!encoded.contains("narration")); - - let created = player_command_projection(&CommandResult::Created { - campaign: seed("Hidden seed"), - }); - assert_eq!(created, serde_json::json!({"kind":"created"})); - } - - #[test] - fn post_commit_failure_remains_an_accepted_committed_projection() { - let campaign = seed("Private state"); - let result = CommandResult::Committed { - receipt: ghostlight_dungeon::domain::WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision: 4, - revision: 5, - command_kind: "speak".into(), - committed_at: chrono::Utc::now(), - roll: None, - }, - campaign, - }; - - let projection = player_command_projection_with_message( - &result, - "The player action committed, but reaction appraisal stopped.", - ); - - assert_eq!(projection["kind"], "committed"); - assert_eq!(projection["revision"], 5); - assert!( - projection["message"] - .as_str() - .unwrap() - .contains("committed") - ); - assert!( - !serde_json::to_string(&projection) - .unwrap() - .contains("Private state") - ); - } - - #[test] - fn assessment_command_result_is_a_complete_eve_surface() { - let projection = transient_result_projection( - "world.assess", - &serde_json::json!({ - "assessment": { - "digest": "sha256:assessment", - "admissible": false, - "missing_permission": "No admitted authority reaches the garrison command.", - "dc": 30, - "modifier_total": -10, - "effect_ceiling": "No effect", - "success_stake": "No impossible effect occurs.", - "mixed_stake": "No impossible effect occurs.", - "failure_stake": "The overreach is refused.", - "bargains": ["Acquire an authority that actually reaches the garrison."] - } - }), - 4_000_000_000_000, - ) - .unwrap(); - - assert_eq!(projection["schema"], "gamecult.eve.surface.v1"); - assert_eq!(projection["version"], 4_000_000_000_000_u64); - assert!(projection["surface"]["styles"].is_object()); - assert!(projection["surface"]["root"]["children"].is_array()); - let summary = projection["surface"]["root"]["children"][0]["props"]["value"] - .as_str() - .unwrap(); - assert!(summary.contains("No roll occurs")); - assert!(summary.contains("No admitted authority reaches the garrison command")); - assert!(summary.contains("Ways to make a narrower attempt possible")); - assert!(!summary.contains("DC 30")); - } - - #[test] - fn stale_attempt_projects_the_fresh_assessment_and_revision() { - let projection = transient_result_projection( - "world.attempt", - &serde_json::json!({ - "kind":"assessed", - "assessment": { - "revision": 9, - "digest": "sha256:fresh-assessment", - "admissible": true, - "dc": 15, - "modifier_total": 2, - "modifiers": [ - { - "label":"The audit seal matches the lock", - "value":2, - "references":["equipment:audit-seal","location:archive"] - } - ], - "effect_ceiling": "Supervised access only", - "success_stake": "The ledger is opened.", - "mixed_stake": "The ledger is opened under scrutiny.", - "failure_stake": "Access is refused.", - "bargains": [] - } - }), - 8_000_000_000_123, - ) - .unwrap(); - - assert_eq!(projection["version"], 9_000_000_000_123_u64); - let roll = &projection["surface"]["root"]["children"][1]; - assert_eq!(roll["kind"], "control.button"); - assert_eq!(roll["props"]["command"], "world.attempt"); - assert_eq!( - roll["props"]["action"]["assessment_digest"], - "sha256:fresh-assessment" - ); - let summary = projection["surface"]["root"]["children"][0]["props"]["value"] - .as_str() - .unwrap(); - assert!(summary.contains("+2 The audit seal matches the lock")); - assert!(summary.contains("equipment:audit-seal, location:archive")); - } - - #[test] - fn committed_attempt_projects_the_exact_roll_receipt() { - let projection = transient_result_projection( - "world.attempt", - &serde_json::json!({ - "kind":"committed", - "revision": 6, - "receipt": { - "revision": 3, - "roll": { - "assessment_digest":"sha256:assessment", - "d20":12, - "modifier_total":3, - "total":15, - "dc":15, - "outcome":"success" - } - } - }), - 2_000_000_000_000, - ) - .unwrap(); - - assert_eq!(projection["version"], 3_000_000_000_000_u64); - assert_eq!( - projection["surface"]["root"]["children"][0]["props"]["value"], - "d20 12 +3 = 15 against DC 15 — success." - ); - } - - #[test] - fn compiler_preview_projection_exposes_approval_shape_not_private_state() { - let mut campaign = seed("Approval preview"); - let player = campaign.actors.get_mut("player").unwrap(); - player.goals = vec!["private goal".into()]; - player.memories = vec!["private memory".into()]; - player - .relationships - .insert("hidden".into(), "distrust".into()); - campaign.facts.insert( - "branch-secret".into(), - ghostlight_dungeon::domain::WorldFact { - id: "branch-secret".into(), - statement: "The apparent ally caused the disaster.".into(), - scope: ghostlight_dungeon::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["room".into()]), - }, - ); - let preview = WorldCompilePreview { - schema: "ghostlight.world_compile_preview.v1".into(), - title: "Approval preview".into(), - campaign, - evidence_receipts: vec![], - evidence_coverage: vec![], - gaps: vec!["a visible gap".into()], - branch_assumptions: vec!["a visible assumption".into()], - requires_approval: true, - }; - - let projection = world_compile_preview_projection(&preview); - let encoded = serde_json::to_string(&projection).unwrap(); - assert!(encoded.contains("player_role")); - assert!(encoded.contains("locations")); - for private_key in [ - "\"campaign\":", - "\"evidence_receipts\":", - "\"goals\":", - "\"memories\":", - "\"relationships\":", - "\"model_receipts\":", - "\"branch_facts\":", - "branch-secret", - "The apparent ally caused the disaster.", - ] { - assert!(!encoded.contains(private_key), "leaked {private_key}"); - } - } + runtime::run().await } diff --git a/crates/ghostlight-dungeon/src/mesh.rs b/crates/ghostlight-dungeon/src/mesh.rs index 6639515..7bc1067 100644 --- a/crates/ghostlight-dungeon/src/mesh.rs +++ b/crates/ghostlight-dungeon/src/mesh.rs @@ -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, - pub evidence: Vec, - pub commits: Vec, - pub stages: Vec, - pub strategic_ticks: Vec, - pub gestalt_receipts: Vec, - pub rejected: Vec, - pub resolution_plans: Vec, - pub cell_appraisals: Vec, - pub activity_outcomes: Vec, - pub resolution_controls: Vec, -} - -#[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>, remote: Option, identity: MeshRuntimeIdentity, @@ -146,14 +93,11 @@ struct RemoteReplication { target: SocketAddr, runtime_id: String, pending: Arc<(Mutex>>, Condvar)>, + alive: Arc, } impl MeshPublisher { - pub fn open(store_path: impl AsRef, rudp_target: Option) -> Result { - Self::open_with_identity(store_path, rudp_target, MeshRuntimeIdentity::default()) - } - - pub fn open_with_identity( + pub(crate) fn open( store_path: impl AsRef, rudp_target: Option, 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 { + pub(crate) fn publish(&self, snapshot: Option<&WorldSnapshot>) -> Result { + 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 { - self.node - .lock() - .map_err(|_| anyhow::anyhow!("mesh lock poisoned"))? - .get_required::(HEALTH_KEY) - .map(|record| record.value) - } - - pub fn publish_live_turn_pressure(&self, live_turn_pressure: usize) -> Result { - let mut node = self - .node - .lock() - .map_err(|_| anyhow::anyhow!("mesh lock poisoned"))?; - let mut health = node.get_required::(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 { + pub(crate) fn health(&self) -> Result { + 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::(&format!( - "eve:operator:ghostlight.campaign.{campaign_id}" - )) + .try_lock() + .map_err(|_| anyhow::anyhow!("mesh projection is busy or its lock is poisoned"))? + .get_required::(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 { let pending = Arc::new(( Mutex::new(None::>), 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); + 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::("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::("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::(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::(ADVERTISEMENT_KEY) + .is_ok() ); + assert!(node.get_required::(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); } } diff --git a/crates/ghostlight-dungeon/src/model.rs b/crates/ghostlight-dungeon/src/model.rs deleted file mode 100644 index 5ae9557..0000000 --- a/crates/ghostlight-dungeon/src/model.rs +++ /dev/null @@ -1,1788 +0,0 @@ -use anyhow::{Result, anyhow}; -use async_trait::async_trait; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::time::Instant; -use zeroize::Zeroizing; - -pub const MODEL_FAST: &str = "ghostlight.fast.v1"; -pub const MODEL_BALANCED: &str = "ghostlight.balanced.v1"; -pub const MODEL_CAPABLE: &str = "ghostlight.capable.v1"; - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "camelCase")] -pub struct ModelRuntimeStatus { - pub provider: String, - pub fast_model: String, - pub balanced_model: String, - pub capable_model: String, - pub readiness: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct ModelStageRequest { - pub stage: String, - pub model: String, - pub snapshot_binding: String, - pub lived_stream: String, - pub output_schema: Option, - pub source_receipt_ids: Vec, - pub temperature: Option, - pub max_output_tokens: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(tag = "role", rename_all = "snake_case", deny_unknown_fields)] -pub enum ModelInputItem { - UserText { text: String }, - AssistantText { text: String }, -} - -impl ModelInputItem { - pub fn user(text: impl Into) -> Self { - Self::UserText { text: text.into() } - } - - pub fn assistant(text: impl Into) -> Self { - Self::AssistantText { text: text.into() } - } - - fn text(&self) -> &str { - match self { - Self::UserText { text } | Self::AssistantText { text } => text, - } - } -} - -pub fn render_model_input(items: &[ModelInputItem]) -> String { - items - .iter() - .map(|item| match item { - ModelInputItem::UserText { text } => format!("USER:\n{text}"), - ModelInputItem::AssistantText { text } => format!("ASSISTANT:\n{text}"), - }) - .collect::>() - .join("\n\n") -} - -fn model_input_chars(items: &[ModelInputItem]) -> usize { - items.iter().map(|item| item.text().chars().count()).sum() -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ModelStageReceipt { - pub schema: String, - #[serde(default)] - pub receipt_hash: String, - pub provider: String, - pub model: String, - pub stage: String, - pub snapshot_binding: String, - pub request_hash: String, - pub output_hash: String, - pub source_receipt_ids: Vec, - pub latency_ms: u64, - pub validation_result: String, - #[serde(default)] - pub local_validation_error: Option, - #[serde(default)] - pub input_chars: usize, - #[serde(default)] - pub output_chars: usize, - #[serde(default)] - pub provider_attempts: Vec, -} - -#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ModelTokenUsage { - pub prompt_tokens: u64, - pub completion_tokens: u64, - pub total_tokens: u64, - pub prompt_cache_hit_tokens: u64, - pub prompt_cache_miss_tokens: u64, - pub reasoning_tokens: u64, -} - -#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ModelProviderAttemptReceipt { - pub provider_request_id: Option, - pub system_fingerprint: Option, - pub finish_reason: Option, - pub latency_ms: u64, - pub token_usage: Option, - #[serde(default)] - pub transport_features: Vec, - #[serde(default)] - pub local_validation_result: String, - #[serde(default)] - pub local_validation_error: Option, -} - -impl ModelStageReceipt { - pub fn storage_key(&self) -> &str { - if self.receipt_hash.is_empty() { - &self.output_hash - } else { - &self.receipt_hash - } - } - - /// Bind a structurally validated model output to a narrower local semantic - /// object without rerunning inference. The request and output hashes remain - /// the exact provider evidence; the content-addressed receipt changes to - /// cover the locally admitted binding. - pub fn rebind_snapshot(&mut self, snapshot_binding: String) { - self.snapshot_binding = snapshot_binding; - self.receipt_hash = format!( - "sha256:{:x}", - Sha256::digest( - format!( - "{}|{}|{}|{}|{}|{}", - self.provider, - self.model, - self.stage, - self.snapshot_binding, - self.request_hash, - self.output_hash - ) - .as_bytes() - ) - ); - } - - pub fn same_receipted_content(&self, other: &Self) -> bool { - self.storage_key() == other.storage_key() - && self.schema == other.schema - && self.provider == other.provider - && self.model == other.model - && self.stage == other.stage - && self.snapshot_binding == other.snapshot_binding - && self.request_hash == other.request_hash - && self.output_hash == other.output_hash - && self.source_receipt_ids == other.source_receipt_ids - && self.validation_result == other.validation_result - && self.local_validation_error == other.local_validation_error - && self.input_chars == other.input_chars - && self.output_chars == other.output_chars - } -} - -pub(crate) fn mark_model_receipt_semantic_invalid( - receipt: &mut ModelStageReceipt, - finding: &impl std::fmt::Display, -) { - receipt.validation_result = "semantic_invalid".into(); - receipt.local_validation_error = Some(finding.to_string().chars().take(1_000).collect()); -} - -#[derive(Clone, Debug, PartialEq)] -pub struct ModelStageOutput { - pub narrative: String, - pub structured: Option, - pub receipt: ModelStageReceipt, -} - -#[derive(Clone, Debug, Default, PartialEq)] -pub struct ModelProviderOutput { - pub content: String, - pub resolved_model: Option, - pub provider_request_id: Option, - pub system_fingerprint: Option, - pub finish_reason: Option, - pub token_usage: Option, - pub transport_features: Vec, -} - -#[async_trait] -pub trait ModelPort: Send + Sync { - async fn run(&self, request: &ModelStageRequest) -> Result; - async fn run_observed(&self, request: &ModelStageRequest) -> Result { - Ok(ModelProviderOutput { - content: self.run(request).await?, - ..Default::default() - }) - } - async fn run_observed_conversation( - &self, - request: &ModelStageRequest, - input: &[ModelInputItem], - ) -> Result { - let mut projected = request.clone(); - projected.lived_stream = render_model_input(input); - self.run_observed(&projected).await - } - fn provider(&self) -> &'static str; - fn attempt_timeout(&self, _request: &ModelStageRequest) -> std::time::Duration { - std::time::Duration::from_secs(45) - } -} - -pub async fn run_validated_stage( - port: &dyn ModelPort, - request: &ModelStageRequest, -) -> Result { - run_validated_stage_inner(port, request, port.attempt_timeout(request), None).await -} - -pub async fn run_validated_conversation_stage( - port: &dyn ModelPort, - request: &ModelStageRequest, - input: &[ModelInputItem], -) -> Result { - run_validated_stage_inner( - port, - request, - port.attempt_timeout(request), - Some(input.to_vec()), - ) - .await -} - -pub async fn run_validated_stage_with_timeout( - port: &dyn ModelPort, - request: &ModelStageRequest, - timeout: std::time::Duration, -) -> Result { - run_validated_stage_inner(port, request, timeout, None).await -} - -async fn run_validated_stage_inner( - port: &dyn ModelPort, - request: &ModelStageRequest, - timeout: std::time::Duration, - mut conversation: Option>, -) -> Result { - let validator = request - .output_schema - .as_ref() - .map(jsonschema::validator_for) - .transpose() - .map_err(|error| { - anyhow!( - "model stage {} has an invalid local output schema: {error}", - request.stage - ) - })?; - let mut attempt_request = request.clone(); - let stage_started = Instant::now(); - let mut provider_attempts = Vec::new(); - for attempt in 0..2 { - let (provider_output, provider_latency_ms) = { - let mut transport_attempt = 0; - loop { - let started = Instant::now(); - let (failure_kind, diagnostic) = match tokio::time::timeout(timeout, async { - match conversation.as_deref() { - Some(input) => { - port.run_observed_conversation(&attempt_request, input) - .await - } - None => port.run_observed(&attempt_request).await, - } - }) - .await - { - Ok(Ok(output)) => break (output, started.elapsed().as_millis() as u64), - Ok(Err(error)) => ("provider_error", bounded_validation_error(&error)), - Err(_) => ( - "timeout", - format!( - "model stage {} timed out after {} seconds with {} input characters", - request.stage, - timeout.as_secs(), - conversation.as_deref().map_or_else( - || attempt_request.lived_stream.chars().count(), - model_input_chars, - ) - ), - ), - }; - provider_attempts.push(ModelProviderAttemptReceipt { - provider_request_id: None, - system_fingerprint: None, - finish_reason: Some(failure_kind.into()), - latency_ms: started.elapsed().as_millis() as u64, - token_usage: None, - transport_features: Vec::new(), - local_validation_result: failure_kind.into(), - local_validation_error: Some(diagnostic.clone()), - }); - if transport_attempt == 0 { - transport_attempt += 1; - continue; - } - return Err(anyhow!( - "model stage {} transport failed on both permitted attempts against the same snapshot; latest failure ({failure_kind}): {diagnostic}", - request.stage - )); - } - }; - let ModelProviderOutput { - content: output, - resolved_model, - provider_request_id, - system_fingerprint, - finish_reason, - token_usage, - transport_features, - } = provider_output; - provider_attempts.push(ModelProviderAttemptReceipt { - provider_request_id, - system_fingerprint, - finish_reason, - latency_ms: provider_latency_ms, - token_usage, - transport_features, - local_validation_result: "pending".into(), - local_validation_error: None, - }); - if output.trim().is_empty() { - provider_attempts - .last_mut() - .expect("attempt was just recorded") - .local_validation_result = "empty".into(); - provider_attempts - .last_mut() - .expect("attempt was just recorded") - .local_validation_error = Some("provider returned an empty response".into()); - if attempt == 0 { - append_validation_retry( - &mut attempt_request, - &mut conversation, - &output, - "LOCAL VALIDATOR: The previous response was empty. Return one complete response against the same snapshot and output contract.".into(), - ); - continue; - } - return Err(anyhow!("model returned empty output twice")); - } - let structured = match &validator { - Some(_) => match serde_json::from_str(&output) { - Ok(value) => { - let validation = validator.as_ref().expect("structured validator"); - if let Err(error) = validation.validate(&value) { - let diagnostic = schema_validation_diagnostic( - &request.stage, - &error, - &value, - request - .output_schema - .as_ref() - .expect("validated structured output has a schema"), - ); - provider_attempts - .last_mut() - .expect("attempt was just recorded") - .local_validation_result = "schema_invalid".into(); - provider_attempts - .last_mut() - .expect("attempt was just recorded") - .local_validation_error = Some(bounded_validation_error(&diagnostic)); - if attempt == 0 { - append_validation_retry( - &mut attempt_request, - &mut conversation, - &output, - format!( - "LOCAL VALIDATOR REJECTED THE PREVIOUS JSON: {diagnostic}\nReturn one corrected complete JSON object against the same snapshot and schema." - ), - ); - continue; - } - return Err(anyhow!( - "model returned schema-invalid JSON twice: {diagnostic}" - )); - } - Some(value) - } - Err(error) if attempt == 0 => { - provider_attempts - .last_mut() - .expect("attempt was just recorded") - .local_validation_result = "malformed_json".into(); - provider_attempts - .last_mut() - .expect("attempt was just recorded") - .local_validation_error = Some(bounded_validation_error(&error)); - append_validation_retry( - &mut attempt_request, - &mut conversation, - &output, - format!( - "LOCAL VALIDATOR COULD NOT PARSE THE PREVIOUS RESPONSE AS JSON: {error}\nReturn one corrected complete JSON object against the same snapshot and schema." - ), - ); - continue; - } - Err(error) => { - provider_attempts - .last_mut() - .expect("attempt was just recorded") - .local_validation_result = "malformed_json".into(); - provider_attempts - .last_mut() - .expect("attempt was just recorded") - .local_validation_error = Some(bounded_validation_error(&error)); - return Err(anyhow!("model returned malformed JSON twice: {error}")); - } - }, - None => None, - }; - provider_attempts - .last_mut() - .expect("attempt was just recorded") - .local_validation_result = "valid".into(); - let receipt_model = resolved_model.unwrap_or_else(|| attempt_request.model.clone()); - let mut receipted_request = attempt_request.clone(); - receipted_request.model.clone_from(&receipt_model); - if let Some(input) = conversation.as_deref() { - receipted_request.lived_stream = render_model_input(input); - } - let request_bytes = serde_json::to_vec(&receipted_request)?; - let provider = port.provider().to_owned(); - let request_hash = format!("sha256:{:x}", Sha256::digest(&request_bytes)); - let output_hash = format!("sha256:{:x}", Sha256::digest(output.as_bytes())); - let receipt_hash = format!( - "sha256:{:x}", - Sha256::digest( - format!( - "{}|{}|{}|{}|{}|{}", - provider, - receipt_model, - request.stage, - request.snapshot_binding, - request_hash, - output_hash - ) - .as_bytes() - ) - ); - return Ok(ModelStageOutput { - narrative: output.clone(), - structured, - receipt: ModelStageReceipt { - schema: "ghostlight.persona_stage_receipt.v1".into(), - receipt_hash, - provider, - model: receipt_model, - stage: request.stage.clone(), - snapshot_binding: request.snapshot_binding.clone(), - request_hash, - output_hash, - source_receipt_ids: request.source_receipt_ids.clone(), - latency_ms: stage_started.elapsed().as_millis() as u64, - validation_result: "valid".into(), - local_validation_error: None, - input_chars: conversation.as_deref().map_or_else( - || attempt_request.lived_stream.chars().count(), - model_input_chars, - ), - output_chars: output.chars().count(), - provider_attempts, - }, - }); - } - unreachable!() -} - -fn append_validation_retry( - request: &mut ModelStageRequest, - conversation: &mut Option>, - rejected_output: &str, - diagnostic: String, -) { - if let Some(input) = conversation.as_mut() { - if !rejected_output.trim().is_empty() { - input.push(ModelInputItem::assistant(rejected_output)); - } - input.push(ModelInputItem::user(diagnostic)); - } else { - request.lived_stream.push_str("\n\n"); - request.lived_stream.push_str(&diagnostic); - } -} - -fn bounded_validation_error(error: &impl std::fmt::Display) -> String { - error.to_string().chars().take(1_000).collect() -} - -fn schema_validation_diagnostic( - stage: &str, - error: &jsonschema::ValidationError<'_>, - rejected: &serde_json::Value, - output_schema: &serde_json::Value, -) -> String { - let mut diagnostic = format!( - "stage {stage}, instance {}, schema {}: {error}", - error.instance_path(), - error.schema_path() - ); - let instance_path = error.instance_path().to_string(); - let rejected_context = action_rejected_context(rejected, &instance_path).or_else(|| { - nearest_rejected_object(rejected, &instance_path).map(|(path, value)| (path, value.clone())) - }); - if let Some((path, value)) = rejected_context - && let Ok(serialized) = serde_json::to_string(&value) - { - let bounded: String = serialized.chars().take(2_000).collect(); - diagnostic.push_str(&format!( - "; rejected containing value at {}: {bounded}", - if path.is_empty() { "/" } else { &path } - )); - } - if let Some(detail) = matching_action_schema_diagnostic(output_schema, rejected, &instance_path) - { - diagnostic.push_str(&format!("; exact attributed action failure: {detail}")); - } - diagnostic -} - -fn matching_action_schema_diagnostic( - output_schema: &serde_json::Value, - rejected: &serde_json::Value, - instance_path: &str, -) -> Option { - let mut segments = instance_path.split('/').skip(1); - if segments.next()? != "actions" { - return None; - } - let action_index = segments.next()?.parse::().ok()?; - let action_path = format!("/actions/{action_index}"); - let action = rejected.pointer(&action_path)?; - let subject_id = action.get("subject_id")?.as_str()?; - let alternative = output_schema - .pointer("/properties/actions/items/anyOf")? - .as_array()? - .iter() - .find(|candidate| { - candidate - .pointer("/properties/subject_id/const") - .and_then(serde_json::Value::as_str) - == Some(subject_id) - })?; - - let mut isolated = serde_json::Map::new(); - if let Some(dialect) = output_schema.get("$schema") { - isolated.insert("$schema".into(), dialect.clone()); - } - if let Some(definitions) = output_schema.get("$defs") { - isolated.insert("$defs".into(), definitions.clone()); - } - isolated.insert("allOf".into(), serde_json::json!([alternative])); - let isolated = serde_json::Value::Object(isolated); - let validator = jsonschema::validator_for(&isolated).ok()?; - let nested_error = validator.validate(action).err()?; - Some(format!( - "subject {subject_id}, instance {action_path}{}, schema {}: {nested_error}", - nested_error.instance_path(), - nested_error.schema_path() - )) -} - -fn action_rejected_context( - rejected: &serde_json::Value, - instance_path: &str, -) -> Option<(String, serde_json::Value)> { - let mut segments = instance_path.split('/').skip(1); - if segments.next()? != "actions" { - return None; - } - let action_index = segments.next()?.parse::().ok()?; - let action_path = format!("/actions/{action_index}"); - let action = rejected.pointer(&action_path)?.as_object()?; - let (_, rejected_value) = nearest_rejected_object(rejected, instance_path)?; - Some(( - action_path, - serde_json::json!({ - "subject_id":action.get("subject_id"), - "intent":action.get("intent"), - "intended_effect":action.get("intended_effect"), - "rejected_value":rejected_value, - }), - )) -} - -fn nearest_rejected_object<'a>( - rejected: &'a serde_json::Value, - instance_path: &str, -) -> Option<(String, &'a serde_json::Value)> { - let mut path = instance_path.to_owned(); - loop { - if let Some(value) = rejected.pointer(&path) - && value.is_object() - { - return Some((path, value)); - } - if path.is_empty() { - return None; - } - match path.rfind('/') { - Some(0) => path.clear(), - Some(index) => path.truncate(index), - None => return None, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::{ - Mutex, - atomic::{AtomicUsize, Ordering}, - }; - - fn receipt_fixture() -> ModelStageReceipt { - ModelStageReceipt { - schema: "ghostlight.persona_stage_receipt.v1".into(), - receipt_hash: "sha256:receipt".into(), - provider: "fixture".into(), - model: "fixture-model".into(), - stage: "fixture-stage".into(), - snapshot_binding: "campaign:one:revision:4".into(), - request_hash: "sha256:request".into(), - output_hash: "sha256:output".into(), - source_receipt_ids: vec!["receipt:source".into()], - latency_ms: 17, - validation_result: "valid".into(), - local_validation_error: None, - input_chars: 120, - output_chars: 42, - provider_attempts: vec![ModelProviderAttemptReceipt { - latency_ms: 17, - ..Default::default() - }], - } - } - - #[test] - fn content_addressed_receipts_ignore_only_observational_attempt_telemetry() { - let original = receipt_fixture(); - let mut repeated = original.clone(); - repeated.latency_ms = 91; - repeated.provider_attempts = vec![ModelProviderAttemptReceipt { - provider_request_id: Some("retry-request".into()), - latency_ms: 91, - ..Default::default() - }]; - assert!(original.same_receipted_content(&repeated)); - - let mut changed_output = repeated.clone(); - changed_output.output_hash = "sha256:different".into(); - assert!(!original.same_receipted_content(&changed_output)); - - let mut changed_semantics = repeated; - changed_semantics.validation_result = "semantic_invalid".into(); - assert!(!original.same_receipted_content(&changed_semantics)); - } - - struct InvalidThenValid { - calls: AtomicUsize, - } - - struct NeverReturns; - struct ShortDeadlineNeverReturns; - struct AlwaysSchemaInvalid; - struct CorrectionAware { - calls: AtomicUsize, - } - struct TransportFailureThenValid { - calls: AtomicUsize, - } - struct TimeoutThenValid { - calls: AtomicUsize, - requests: Mutex>, - } - struct MixedTransportFailures { - calls: AtomicUsize, - timeout_first: bool, - } - struct PhysicallyRoutedModel; - - #[async_trait] - impl ModelPort for NeverReturns { - async fn run(&self, _: &ModelStageRequest) -> Result { - std::future::pending().await - } - - fn provider(&self) -> &'static str { - "fixture" - } - } - - #[async_trait] - impl ModelPort for ShortDeadlineNeverReturns { - async fn run(&self, _: &ModelStageRequest) -> Result { - std::future::pending().await - } - - fn provider(&self) -> &'static str { - "slow-fixture" - } - - fn attempt_timeout(&self, _: &ModelStageRequest) -> std::time::Duration { - std::time::Duration::from_millis(5) - } - } - - #[async_trait] - impl ModelPort for AlwaysSchemaInvalid { - async fn run(&self, _: &ModelStageRequest) -> Result { - Ok(r#"{"answer":[]}"#.into()) - } - - fn provider(&self) -> &'static str { - "invalid-fixture" - } - } - - #[async_trait] - impl ModelPort for InvalidThenValid { - async fn run(&self, _: &ModelStageRequest) -> Result { - Ok(if self.calls.fetch_add(1, Ordering::SeqCst) == 0 { - r#"{"answer":7}"#.into() - } else { - r#"{"answer":"ready"}"#.into() - }) - } - - fn provider(&self) -> &'static str { - "fixture" - } - } - - #[async_trait] - impl ModelPort for CorrectionAware { - async fn run(&self, request: &ModelStageRequest) -> Result { - assert_eq!(request.snapshot_binding, "campaign:one:revision:4"); - self.calls.fetch_add(1, Ordering::SeqCst); - Ok(if request.lived_stream.contains("LOCAL VALIDATOR") { - assert!( - request - .lived_stream - .contains("rejected containing value at /: {\"wrong\":\"shape\"}") - ); - r#"{"answer":"corrected"}"#.into() - } else { - r#"{"wrong":"shape"}"#.into() - }) - } - - fn provider(&self) -> &'static str { - "fixture" - } - } - - #[async_trait] - impl ModelPort for TransportFailureThenValid { - async fn run(&self, _: &ModelStageRequest) -> Result { - if self.calls.fetch_add(1, Ordering::SeqCst) == 0 { - Err(anyhow!("connection reset by fixture peer")) - } else { - Ok(r#"{"answer":"ready"}"#.into()) - } - } - - fn provider(&self) -> &'static str { - "transient-fixture" - } - } - - #[async_trait] - impl ModelPort for TimeoutThenValid { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.requests.lock().unwrap().push(request.clone()); - if self.calls.fetch_add(1, Ordering::SeqCst) == 0 { - std::future::pending().await - } else { - Ok(r#"{"answer":"ready"}"#.into()) - } - } - - fn provider(&self) -> &'static str { - "transient-timeout-fixture" - } - } - - #[async_trait] - impl ModelPort for MixedTransportFailures { - async fn run(&self, _: &ModelStageRequest) -> Result { - let first_attempt = self.calls.fetch_add(1, Ordering::SeqCst) == 0; - if first_attempt == self.timeout_first { - std::future::pending().await - } else { - Err(anyhow!("connection reset by fixture peer")) - } - } - - fn provider(&self) -> &'static str { - "mixed-transport-fixture" - } - } - - #[async_trait] - impl ModelPort for PhysicallyRoutedModel { - async fn run(&self, _: &ModelStageRequest) -> Result { - unreachable!("run_observed owns this fixture") - } - - async fn run_observed(&self, _: &ModelStageRequest) -> Result { - Ok(ModelProviderOutput { - content: "ready".into(), - resolved_model: Some("stealth/ox-alpha".into()), - ..Default::default() - }) - } - - fn provider(&self) -> &'static str { - "openrouter" - } - } - - #[tokio::test] - async fn schema_invalid_json_gets_one_same_snapshot_retry() { - let port = InvalidThenValid { - calls: AtomicUsize::new(0), - }; - let request = ModelStageRequest { - stage: "typed-stage".into(), - model: "fixture".into(), - snapshot_binding: "campaign:one:revision:4".into(), - lived_stream: "fixture".into(), - output_schema: Some(serde_json::json!({ - "$schema":"https://json-schema.org/draft/2020-12/schema", - "type":"object", - "required":["answer"], - "properties":{"answer":{"type":"string"}} - })), - source_receipt_ids: vec![], - temperature: None, - max_output_tokens: None, - }; - let output = run_validated_stage(&port, &request).await.unwrap(); - assert_eq!(port.calls.load(Ordering::SeqCst), 2); - assert_eq!(output.structured.unwrap()["answer"], "ready"); - assert_eq!(output.receipt.provider_attempts.len(), 2); - assert_eq!(output.receipt.snapshot_binding, request.snapshot_binding); - } - - #[tokio::test] - async fn structured_retry_carries_local_failure_without_rebinding_snapshot() { - let port = CorrectionAware { - calls: AtomicUsize::new(0), - }; - let request = ModelStageRequest { - stage: "typed-stage".into(), - model: "fixture".into(), - snapshot_binding: "campaign:one:revision:4".into(), - lived_stream: "fixture".into(), - output_schema: Some(serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["answer"], - "properties":{"answer":{"type":"string"}} - })), - source_receipt_ids: vec![], - temperature: None, - max_output_tokens: None, - }; - let output = run_validated_stage(&port, &request).await.unwrap(); - assert_eq!(port.calls.load(Ordering::SeqCst), 2); - assert_eq!(output.structured.unwrap()["answer"], "corrected"); - assert_eq!(output.receipt.snapshot_binding, request.snapshot_binding); - } - - #[tokio::test] - async fn transient_provider_failure_retries_the_exact_request() { - let port = TransportFailureThenValid { - calls: AtomicUsize::new(0), - }; - let request = ModelStageRequest { - stage: "typed-stage".into(), - model: "fixture".into(), - snapshot_binding: "campaign:one:revision:4".into(), - lived_stream: "fixture".into(), - output_schema: Some(serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["answer"], - "properties":{"answer":{"type":"string"}} - })), - source_receipt_ids: vec![], - temperature: None, - max_output_tokens: None, - }; - let output = run_validated_stage(&port, &request).await.unwrap(); - assert_eq!(port.calls.load(Ordering::SeqCst), 2); - assert_eq!(output.structured.unwrap()["answer"], "ready"); - assert_eq!(output.receipt.snapshot_binding, request.snapshot_binding); - assert_eq!(output.receipt.provider_attempts.len(), 2); - assert_eq!( - output.receipt.provider_attempts[0].local_validation_result, - "provider_error" - ); - assert!( - output.receipt.provider_attempts[0] - .local_validation_error - .as_deref() - .unwrap() - .contains("connection reset") - ); - assert_eq!( - output.receipt.provider_attempts[1].local_validation_result, - "valid" - ); - } - - #[tokio::test] - async fn transient_timeout_retries_the_exact_request_and_receipts_both_attempts() { - let port = TimeoutThenValid { - calls: AtomicUsize::new(0), - requests: Mutex::new(Vec::new()), - }; - let request = ModelStageRequest { - stage: "typed-stage".into(), - model: "fixture".into(), - snapshot_binding: "campaign:one:revision:4".into(), - lived_stream: "fixture".into(), - output_schema: Some(serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["answer"], - "properties":{"answer":{"type":"string"}} - })), - source_receipt_ids: vec![], - temperature: None, - max_output_tokens: None, - }; - - let output = - run_validated_stage_with_timeout(&port, &request, std::time::Duration::from_millis(5)) - .await - .unwrap(); - - assert_eq!(port.calls.load(Ordering::SeqCst), 2); - let requests = port.requests.lock().unwrap(); - assert_eq!( - serde_json::to_value(&requests[0]).unwrap(), - serde_json::to_value(&requests[1]).unwrap() - ); - assert_eq!(output.structured.unwrap()["answer"], "ready"); - assert_eq!(output.receipt.snapshot_binding, request.snapshot_binding); - assert_eq!(output.receipt.provider_attempts.len(), 2); - assert_eq!( - output.receipt.provider_attempts[0].local_validation_result, - "timeout" - ); - assert_eq!( - output.receipt.provider_attempts[1].local_validation_result, - "valid" - ); - } - - #[tokio::test] - async fn mixed_transport_failures_report_the_latest_kind_without_rewriting_history() { - let request = ModelStageRequest { - stage: "typed-stage".into(), - model: "fixture".into(), - snapshot_binding: "campaign:one:revision:4".into(), - lived_stream: "fixture".into(), - output_schema: None, - source_receipt_ids: vec![], - temperature: None, - max_output_tokens: None, - }; - for (timeout_first, latest_kind) in [(false, "timeout"), (true, "provider_error")] { - let port = MixedTransportFailures { - calls: AtomicUsize::new(0), - timeout_first, - }; - let error = run_validated_stage_with_timeout( - &port, - &request, - std::time::Duration::from_millis(5), - ) - .await - .unwrap_err() - .to_string(); - - assert_eq!(port.calls.load(Ordering::SeqCst), 2); - assert!(error.contains("transport failed on both permitted attempts")); - assert!(error.contains(&format!("latest failure ({latest_kind})"))); - assert!(!error.contains("failed twice")); - assert!(!error.contains("timed out twice")); - } - } - - #[tokio::test] - async fn repeated_schema_failure_names_stage_and_exact_instance_path() { - let request = ModelStageRequest { - stage: "outcome-fixture".into(), - model: "fixture".into(), - snapshot_binding: "campaign:one:revision:4".into(), - lived_stream: "fixture".into(), - output_schema: Some(serde_json::json!({ - "type":"object", - "required":["answer"], - "properties":{"answer":{"type":"array","minItems":1}} - })), - source_receipt_ids: vec![], - temperature: None, - max_output_tokens: None, - }; - let error = run_validated_stage(&AlwaysSchemaInvalid, &request) - .await - .unwrap_err() - .to_string(); - - assert!(error.contains("stage outcome-fixture")); - assert!(error.contains("instance /answer")); - assert!(error.contains("minItems")); - assert!(error.contains("rejected containing value at /")); - assert!(error.contains("{\"answer\":[]}")); - } - - #[test] - fn schema_diagnostic_preserves_action_ownership_without_unrelated_output() { - let schema = serde_json::json!({ - "type":"object", - "properties":{ - "actions":{ - "type":"array", - "items":{ - "type":"object", - "properties":{ - "effect":{ - "type":"object", - "properties":{ - "activity":{"type":"string"}, - "target_subject_ids":{"type":"array","minItems":1} - } - } - } - } - } - } - }); - let rejected = serde_json::json!({ - "actions":[{ - "subject_id":"member:reed", - "effect":{"activity":"coordinate","target_subject_ids":[]} - }], - "unrelated":"must not be repeated to the model" - }); - let validator = jsonschema::validator_for(&schema).unwrap(); - let error = validator.validate(&rejected).unwrap_err(); - - let diagnostic = - schema_validation_diagnostic("cell_interpreter", &error, &rejected, &schema); - - assert!(diagnostic.contains("instance /actions/0/effect/target_subject_ids")); - assert!(diagnostic.contains("rejected containing value at /actions/0")); - assert!(diagnostic.contains("\"activity\":\"coordinate\"")); - assert!(diagnostic.contains("member:reed")); - assert!(!diagnostic.contains("must not be repeated")); - } - - #[test] - fn schema_diagnostic_descends_into_matching_attributed_action() { - let schema = serde_json::json!({ - "type":"object", - "properties":{ - "actions":{ - "type":"array", - "items":{ - "anyOf":[ - { - "type":"object", - "required":["subject_id","public_channels"], - "properties":{ - "subject_id":{"const":"actor:one"}, - "public_channels":{ - "type":"array", - "items":{"enum":["exact-channel"]} - } - } - }, - { - "type":"object", - "required":["subject_id","public_channels"], - "properties":{ - "subject_id":{"const":"actor:two"}, - "public_channels":{"type":"array","maxItems":0} - } - } - ] - } - } - } - }); - let rejected = serde_json::json!({ - "actions":[{ - "subject_id":"actor:one", - "public_channels":["invented-channel"] - }] - }); - let validator = jsonschema::validator_for(&schema).unwrap(); - let error = validator.validate(&rejected).unwrap_err(); - - let diagnostic = - schema_validation_diagnostic("cell_interpreter", &error, &rejected, &schema); - - assert!(diagnostic.contains("exact attributed action failure")); - assert!(diagnostic.contains("subject actor:one")); - assert!(diagnostic.contains("/actions/0/public_channels/0")); - assert!(diagnostic.contains("invented-channel")); - assert!(diagnostic.contains("exact-channel")); - } - - #[tokio::test] - async fn provider_timeout_returns_no_stage_output() { - let request = ModelStageRequest { - stage: "timeout-stage".into(), - model: "fixture".into(), - snapshot_binding: "campaign:one:revision:4".into(), - lived_stream: "fixture".into(), - output_schema: None, - source_receipt_ids: vec![], - temperature: None, - max_output_tokens: None, - }; - let error = run_validated_stage_with_timeout( - &NeverReturns, - &request, - std::time::Duration::from_millis(5), - ) - .await - .unwrap_err(); - assert!(error.to_string().contains("timed out")); - } - - #[tokio::test] - async fn validated_stage_uses_the_transport_owned_attempt_deadline() { - let request = ModelStageRequest { - stage: "transport-timeout-stage".into(), - model: "fixture".into(), - snapshot_binding: "campaign:one:revision:4".into(), - lived_stream: "fixture".into(), - output_schema: None, - source_receipt_ids: vec![], - temperature: None, - max_output_tokens: None, - }; - let error = run_validated_stage(&ShortDeadlineNeverReturns, &request) - .await - .unwrap_err(); - assert!(error.to_string().contains("timed out")); - } - - #[tokio::test] - async fn receipt_hashes_the_physical_provider_model_not_the_logical_class() { - let request = ModelStageRequest { - stage: "startup_probe".into(), - model: MODEL_FAST.into(), - snapshot_binding: "service-startup".into(), - lived_stream: "ready?".into(), - output_schema: None, - source_receipt_ids: vec![], - temperature: Some(0.0), - max_output_tokens: Some(16), - }; - let output = run_validated_stage(&PhysicallyRoutedModel, &request) - .await - .unwrap(); - assert_eq!(output.receipt.provider, "openrouter"); - assert_eq!(output.receipt.model, "stealth/ox-alpha"); - let mut physical_request = request; - physical_request.model = "stealth/ox-alpha".into(); - assert_eq!( - output.receipt.request_hash, - format!( - "sha256:{:x}", - Sha256::digest(serde_json::to_vec(&physical_request).unwrap()) - ) - ); - } - - #[test] - fn deepseek_response_preserves_usage_metadata_without_reasoning_content() { - let output = decode_deepseek_response(&serde_json::json!({ - "id":"request-7", - "model":"deepseek-v4-flash", - "system_fingerprint":"fp-live", - "choices":[{ - "finish_reason":"stop", - "message":{ - "content":"ready", - "reasoning_content":"must never enter the receipt" - } - }], - "usage":{ - "prompt_tokens":120, - "completion_tokens":30, - "total_tokens":150, - "prompt_cache_hit_tokens":80, - "prompt_cache_miss_tokens":40, - "completion_tokens_details":{"reasoning_tokens":0} - } - })) - .unwrap(); - assert_eq!(output.content, "ready"); - assert_eq!(output.resolved_model.as_deref(), Some("deepseek-v4-flash")); - assert_eq!(output.provider_request_id.as_deref(), Some("request-7")); - assert_eq!(output.finish_reason.as_deref(), Some("stop")); - assert_eq!(output.token_usage.as_ref().unwrap().total_tokens, 150); - let receipt_shape = serde_json::to_value(ModelProviderAttemptReceipt { - provider_request_id: output.provider_request_id, - system_fingerprint: output.system_fingerprint, - finish_reason: output.finish_reason, - latency_ms: 1, - token_usage: output.token_usage, - transport_features: output.transport_features, - local_validation_result: "valid".into(), - local_validation_error: None, - }) - .unwrap(); - assert!( - !serde_json::to_string(&receipt_shape) - .unwrap() - .contains("reasoning_content") - ); - } - - #[test] - fn deepseek_structured_requests_are_deterministic_but_narrative_requests_are_not_forced() { - let mut request = ModelStageRequest { - stage: "interpreter".into(), - model: "deepseek-v4-flash".into(), - snapshot_binding: "campaign:one:revision:4".into(), - lived_stream: "fixture".into(), - output_schema: Some(serde_json::json!({"type":"object"})), - source_receipt_ids: vec![], - temperature: None, - max_output_tokens: Some(321), - }; - let structured = deepseek_request_body(&request); - assert_eq!(structured["temperature"].as_f64(), Some(0.0)); - assert_eq!(structured["response_format"]["type"], "json_object"); - assert_eq!(structured["max_tokens"], 321); - - request.output_schema = None; - let narrative = deepseek_request_body(&request); - assert!(narrative.get("temperature").is_none()); - assert!(narrative.get("response_format").is_none()); - } - - #[test] - fn openrouter_requests_use_the_selected_physical_model_and_hide_reasoning() { - let request = ModelStageRequest { - stage: "interpreter".into(), - model: MODEL_FAST.into(), - snapshot_binding: "campaign:one:revision:4".into(), - lived_stream: "fixture".into(), - output_schema: Some(serde_json::json!({"type":"object"})), - source_receipt_ids: vec![], - temperature: None, - max_output_tokens: Some(321), - }; - let body = openrouter_request_body(&request, "stealth/ox-alpha"); - assert_eq!(body["model"], "stealth/ox-alpha"); - assert_eq!(body["reasoning"]["effort"], "low"); - assert_eq!(body["reasoning"]["exclude"], true); - assert_eq!(body["response_format"]["type"], "json_object"); - assert_eq!(body["plugins"][0]["id"], "response-healing"); - assert_eq!(body["temperature"].as_f64(), Some(0.0)); - assert!(body.get("thinking").is_none()); - let port = OpenRouterPort::new("test-key".into(), "stealth/ox-alpha", "stealth/ox-alpha"); - assert_eq!( - port.attempt_timeout(&request), - std::time::Duration::from_secs(120) - ); - - let mut narrative = request.clone(); - narrative.output_schema = None; - assert!( - openrouter_request_body(&narrative, "stealth/ox-alpha") - .get("plugins") - .is_none() - ); - - let mut capable = request; - capable.model = MODEL_CAPABLE.into(); - assert_eq!( - openrouter_request_body(&capable, "stealth/ox-alpha")["reasoning"]["effort"], - "medium" - ); - - let mut balanced = capable; - balanced.model = MODEL_BALANCED.into(); - assert_eq!( - openrouter_request_body(&balanced, "stealth/ox-alpha")["reasoning"]["effort"], - "medium" - ); - assert_eq!( - resolve_model(&balanced, "fixture-fast", "fixture-capable"), - "fixture-capable" - ); - } - - #[test] - fn openrouter_response_preserves_cache_usage_without_reasoning_content() { - let output = decode_openai_chat_response( - &serde_json::json!({ - "id":"generation-9", - "model":"stealth/ox-alpha", - "choices":[{ - "finish_reason":"stop", - "message":{"content":"ready", "reasoning":"private"} - }], - "usage":{ - "prompt_tokens":120, - "completion_tokens":30, - "total_tokens":150, - "prompt_tokens_details":{"cached_tokens":80}, - "completion_tokens_details":{"reasoning_tokens":0} - } - }), - "OpenRouter", - ) - .unwrap(); - assert_eq!(output.resolved_model.as_deref(), Some("stealth/ox-alpha")); - let usage = output.token_usage.as_ref().unwrap(); - assert_eq!(usage.prompt_cache_hit_tokens, 80); - assert_eq!(usage.prompt_cache_miss_tokens, 40); - assert!(!format!("{output:?}").contains("private")); - } - - #[tokio::test] - async fn openrouter_retries_transient_admission_without_changing_the_request() { - let calls = std::sync::Arc::new(AtomicUsize::new(0)); - let server_calls = calls.clone(); - let app = axum::Router::new().route( - "/", - axum::routing::post(move || { - let calls = server_calls.clone(); - async move { - if calls.fetch_add(1, Ordering::SeqCst) == 0 { - axum::response::Response::builder() - .status(axum::http::StatusCode::TOO_MANY_REQUESTS) - .header(reqwest::header::RETRY_AFTER, "0") - .body(axum::body::Body::from("busy")) - .unwrap() - } else { - axum::response::IntoResponse::into_response(axum::Json(serde_json::json!({ - "id":"generation-after-retry", - "model":"stealth/ox-alpha", - "choices":[{ - "finish_reason":"stop", - "message":{"content":"ready"} - }] - }))) - } - } - }), - ); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); - let mut port = - OpenRouterPort::new("test-key".into(), "stealth/ox-alpha", "stealth/ox-alpha"); - port.endpoint = format!("http://{address}/"); - let request = ModelStageRequest { - stage: "interpreter".into(), - model: MODEL_FAST.into(), - snapshot_binding: "campaign:one:revision:4".into(), - lived_stream: "same snapshot".into(), - output_schema: None, - source_receipt_ids: vec![], - temperature: None, - max_output_tokens: Some(32), - }; - - let output = port.run_with_observation(&request).await.unwrap(); - - assert_eq!(calls.load(Ordering::SeqCst), 2); - assert_eq!(output.content, "ready"); - assert!( - output - .transport_features - .contains(&"openrouter.transient-retries:1".to_owned()) - ); - server.abort(); - } -} - -#[derive(Clone)] -pub struct FixtureModel; -#[async_trait] -impl ModelPort for FixtureModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - Ok(if request.stage == "speech_address_resolver" { - r#"{"persona_response_actor_ids":[]}"#.into() - } else if request.output_schema.is_some() { - r#"{"private_delta":{"memories_add":[],"conditions_add":[],"conditions_remove":[],"goals_add":[],"relationship_updates":{}},"speech":null,"reaction_priority":0,"world_actions":[]}"#.into() - } else { - request.lived_stream.to_string() - }) - } - fn provider(&self) -> &'static str { - "fixture" - } -} - -pub struct DeepSeekPort { - client: reqwest::Client, - api_key: Zeroizing, - endpoint: String, - fast_model: String, - capable_model: String, -} -impl DeepSeekPort { - pub fn new(api_key: String) -> Self { - Self::with_models(api_key, "deepseek-v4-flash", "deepseek-v4-pro") - } - - pub fn with_models( - api_key: String, - fast_model: impl Into, - capable_model: impl Into, - ) -> Self { - Self { - client: reqwest::Client::builder() - .connect_timeout(std::time::Duration::from_secs(10)) - .build() - .expect("static DeepSeek client configuration is valid"), - api_key: Zeroizing::new(api_key), - endpoint: "https://api.deepseek.com/chat/completions".into(), - fast_model: fast_model.into(), - capable_model: capable_model.into(), - } - } - - #[cfg(windows)] - pub fn from_machine_dpapi(path: impl AsRef) -> Result { - Ok(Self::new(crate::windows_secret::unprotect_machine_utf8( - path, - )?)) - } - - pub fn from_utf8_secret_file(path: impl AsRef) -> Result { - let bytes = Zeroizing::new(std::fs::read(path.as_ref())?); - let secret = std::str::from_utf8(bytes.as_slice())?.trim().to_owned(); - if secret.is_empty() { - anyhow::bail!("DeepSeek credential file is empty"); - } - Ok(Self::new(secret)) - } - - pub fn from_runtime_secret(path: impl AsRef) -> Result { - Self::from_runtime_secret_with_models(path, "deepseek-v4-flash", "deepseek-v4-pro") - } - - pub fn from_runtime_secret_with_models( - path: impl AsRef, - fast_model: impl Into, - capable_model: impl Into, - ) -> Result { - #[cfg(windows)] - if path - .as_ref() - .extension() - .is_some_and(|value| value == "dpapi") - { - return Ok(Self::with_models( - crate::windows_secret::unprotect_machine_utf8(path)?, - fast_model, - capable_model, - )); - } - let bytes = Zeroizing::new(std::fs::read(path.as_ref())?); - let secret = std::str::from_utf8(bytes.as_slice())?.trim().to_owned(); - if secret.is_empty() { - anyhow::bail!("DeepSeek credential file is empty"); - } - Ok(Self::with_models(secret, fast_model, capable_model)) - } - - async fn run_with_observation( - &self, - request: &ModelStageRequest, - ) -> Result { - let resolved_model = resolve_model(request, &self.fast_model, &self.capable_model); - let mut routed_request = request.clone(); - routed_request.model.clone_from(&resolved_model); - let body = deepseek_request_body(&routed_request); - let value: serde_json::Value = self - .client - .post(&self.endpoint) - .bearer_auth(self.api_key.as_str()) - .json(&body) - .send() - .await? - .error_for_status()? - .json() - .await?; - let mut output = decode_deepseek_response(&value)?; - output.resolved_model = Some(resolved_model); - Ok(output) - } -} - -fn deepseek_request_body(request: &ModelStageRequest) -> serde_json::Value { - let mut body = serde_json::json!({ - "model": request.model, - "messages": [{"role": "user", "content": request.lived_stream}], - "stream": false, - "thinking": {"type": "disabled"} - }); - if request.output_schema.is_some() { - body["response_format"] = serde_json::json!({"type":"json_object"}); - body["temperature"] = serde_json::json!(request.temperature.unwrap_or(0.0)); - } else if let Some(temperature) = request.temperature { - body["temperature"] = serde_json::json!(temperature); - } - if let Some(max_tokens) = request.max_output_tokens { - body["max_tokens"] = serde_json::json!(max_tokens); - } - body -} -#[async_trait] -impl ModelPort for DeepSeekPort { - async fn run(&self, request: &ModelStageRequest) -> Result { - Ok(self.run_with_observation(request).await?.content) - } - async fn run_observed(&self, request: &ModelStageRequest) -> Result { - self.run_with_observation(request).await - } - fn provider(&self) -> &'static str { - "deepseek" - } -} - -fn decode_deepseek_response(value: &serde_json::Value) -> Result { - decode_openai_chat_response(value, "DeepSeek") -} - -pub struct OpenRouterPort { - client: reqwest::Client, - api_key: Zeroizing, - endpoint: String, - fast_model: String, - capable_model: String, -} - -impl OpenRouterPort { - pub fn new( - api_key: String, - fast_model: impl Into, - capable_model: impl Into, - ) -> Self { - Self { - client: reqwest::Client::builder() - .connect_timeout(std::time::Duration::from_secs(10)) - .build() - .expect("static OpenRouter client configuration is valid"), - api_key: Zeroizing::new(api_key), - endpoint: "https://openrouter.ai/api/v1/chat/completions".into(), - fast_model: fast_model.into(), - capable_model: capable_model.into(), - } - } - - pub fn from_utf8_secret_file( - path: impl AsRef, - fast_model: impl Into, - capable_model: impl Into, - ) -> Result { - let bytes = Zeroizing::new(std::fs::read(path.as_ref())?); - let secret = std::str::from_utf8(bytes.as_slice())?.trim().to_owned(); - if secret.is_empty() { - anyhow::bail!("OpenRouter credential file is empty"); - } - Ok(Self::new(secret, fast_model, capable_model)) - } - - pub fn from_runtime_secret( - path: impl AsRef, - fast_model: impl Into, - capable_model: impl Into, - ) -> Result { - #[cfg(windows)] - if path - .as_ref() - .extension() - .is_some_and(|value| value == "dpapi") - { - return Ok(Self::new( - crate::windows_secret::unprotect_machine_utf8(path)?, - fast_model, - capable_model, - )); - } - Self::from_utf8_secret_file(path, fast_model, capable_model) - } - - async fn run_with_observation( - &self, - request: &ModelStageRequest, - ) -> Result { - let resolved_model = resolve_model(request, &self.fast_model, &self.capable_model); - let body = openrouter_request_body(request, &resolved_model); - let mut transient_retries = 0usize; - let value: serde_json::Value = loop { - let response = self - .client - .post(&self.endpoint) - .bearer_auth(self.api_key.as_str()) - .header("HTTP-Referer", "https://ghostlight.gamecult.org") - .header("X-Title", "Ghostlight Dungeon") - .json(&body) - .send() - .await?; - if openrouter_transient_status(response.status()) && transient_retries < 3 { - let delay = openrouter_retry_delay(&response, transient_retries); - transient_retries += 1; - tokio::time::sleep(delay).await; - continue; - } - break response.error_for_status()?.json().await?; - }; - let mut output = decode_openai_chat_response(&value, "OpenRouter")?; - output.resolved_model = Some(resolved_model); - if transient_retries > 0 { - output - .transport_features - .push(format!("openrouter.transient-retries:{transient_retries}")); - } - if request.output_schema.is_some() { - output - .transport_features - .push("openrouter.response-healing".into()); - } - Ok(output) - } -} - -fn openrouter_transient_status(status: reqwest::StatusCode) -> bool { - matches!( - status, - reqwest::StatusCode::TOO_MANY_REQUESTS - | reqwest::StatusCode::BAD_GATEWAY - | reqwest::StatusCode::SERVICE_UNAVAILABLE - | reqwest::StatusCode::GATEWAY_TIMEOUT - ) -} - -fn openrouter_retry_delay(response: &reqwest::Response, retry: usize) -> std::time::Duration { - let advertised_seconds = response - .headers() - .get(reqwest::header::RETRY_AFTER) - .and_then(|value| value.to_str().ok()) - .and_then(|value| value.parse::().ok()); - std::time::Duration::from_secs( - advertised_seconds - .unwrap_or([5, 15, 30][retry.min(2)]) - .min(30), - ) -} - -fn openrouter_request_body(request: &ModelStageRequest, resolved_model: &str) -> serde_json::Value { - let mut body = serde_json::json!({ - "model": resolved_model, - "messages": [{"role": "user", "content": request.lived_stream}], - "stream": false, - "reasoning": { - "effort": if matches!(request.model.as_str(), MODEL_BALANCED | MODEL_CAPABLE) { "medium" } else { "low" }, - "exclude": true - } - }); - if request.output_schema.is_some() { - body["response_format"] = serde_json::json!({"type":"json_object"}); - body["plugins"] = serde_json::json!([{"id":"response-healing"}]); - body["temperature"] = serde_json::json!(request.temperature.unwrap_or(0.0)); - } else if let Some(temperature) = request.temperature { - body["temperature"] = serde_json::json!(temperature); - } - if let Some(max_tokens) = request.max_output_tokens { - body["max_tokens"] = serde_json::json!(max_tokens); - } - body -} - -#[async_trait] -impl ModelPort for OpenRouterPort { - async fn run(&self, request: &ModelStageRequest) -> Result { - Ok(self.run_with_observation(request).await?.content) - } - - async fn run_observed(&self, request: &ModelStageRequest) -> Result { - self.run_with_observation(request).await - } - - fn provider(&self) -> &'static str { - "openrouter" - } - - fn attempt_timeout(&self, _request: &ModelStageRequest) -> std::time::Duration { - std::time::Duration::from_secs(120) - } -} - -fn resolve_model(request: &ModelStageRequest, fast_model: &str, capable_model: &str) -> String { - match request.model.as_str() { - MODEL_FAST => fast_model.to_owned(), - MODEL_BALANCED => capable_model.to_owned(), - MODEL_CAPABLE => capable_model.to_owned(), - explicit => explicit.to_owned(), - } -} - -fn decode_openai_chat_response( - value: &serde_json::Value, - provider_name: &str, -) -> Result { - let content = value - .pointer("/choices/0/message/content") - .and_then(|v| v.as_str()) - .map(str::to_owned) - .ok_or_else(|| anyhow!("{provider_name} response contained no assistant content"))?; - let token_usage = value - .get("usage") - .filter(|usage| !usage.is_null()) - .map(|usage| ModelTokenUsage { - prompt_tokens: usage["prompt_tokens"].as_u64().unwrap_or_default(), - completion_tokens: usage["completion_tokens"].as_u64().unwrap_or_default(), - total_tokens: usage["total_tokens"].as_u64().unwrap_or_default(), - prompt_cache_hit_tokens: usage["prompt_cache_hit_tokens"] - .as_u64() - .or_else(|| usage["prompt_tokens_details"]["cached_tokens"].as_u64()) - .unwrap_or_default(), - prompt_cache_miss_tokens: usage["prompt_cache_miss_tokens"].as_u64().unwrap_or_else( - || { - usage["prompt_tokens"] - .as_u64() - .unwrap_or_default() - .saturating_sub( - usage["prompt_tokens_details"]["cached_tokens"] - .as_u64() - .unwrap_or_default(), - ) - }, - ), - reasoning_tokens: usage["completion_tokens_details"]["reasoning_tokens"] - .as_u64() - .unwrap_or_default(), - }); - Ok(ModelProviderOutput { - content, - resolved_model: value["model"].as_str().map(str::to_owned), - provider_request_id: value["id"].as_str().map(str::to_owned), - system_fingerprint: value["system_fingerprint"].as_str().map(str::to_owned), - finish_reason: value["choices"][0]["finish_reason"] - .as_str() - .map(str::to_owned), - token_usage, - transport_features: vec![], - }) -} diff --git a/crates/ghostlight-dungeon/src/model_connector.rs b/crates/ghostlight-dungeon/src/model_connector.rs deleted file mode 100644 index 180d268..0000000 --- a/crates/ghostlight-dungeon/src/model_connector.rs +++ /dev/null @@ -1,1084 +0,0 @@ -use std::collections::BTreeSet; -use std::net::SocketAddr; -use std::path::Path; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use anyhow::{Context, Result, bail}; -use async_trait::async_trait; -use codex_connector::{ - CodexConnectorClient, CodexInputItem, CodexProviderRequest, CodexToolChoice, - CodexTransportDisposition, CodexTransportEventPayload, CodexTransportInvocation, - CodexTransportOutcome, -}; -use sha2::{Digest, Sha256}; -use tokio::sync::Semaphore; -use zeroize::Zeroizing; - -use crate::model::{ - MODEL_BALANCED, MODEL_CAPABLE, MODEL_FAST, ModelInputItem, ModelPort, ModelProviderOutput, - ModelStageRequest, ModelTokenUsage, -}; - -const MAX_FRAME_BYTES: usize = 1_052_672; -const REQUEST_EXPIRY: Duration = Duration::from_secs(150); -const FAST_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(120); -const BALANCED_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(180); -const CAPABLE_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(300); -const WORLD_COMPILE_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(600); -const DESTINATION_COMPILE_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(600); -const BALANCED_DESTINATION_COMPILE_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(300); - -#[derive(Clone)] -pub struct CodexConnectorModelPort { - client: CodexConnectorClient, - request_gate: std::sync::Arc, - caller_runtime_id: String, - fast_model: String, - balanced_model: String, - capable_model: String, -} - -impl CodexConnectorModelPort { - pub fn new( - endpoint: SocketAddr, - connection_key: String, - caller_runtime_id: impl Into, - fast_model: impl Into, - balanced_model: impl Into, - capable_model: impl Into, - max_concurrent_requests: usize, - ) -> Result { - let caller_runtime_id = caller_runtime_id.into(); - if caller_runtime_id.trim().is_empty() || caller_runtime_id.trim() != caller_runtime_id { - bail!("CodexConnector caller runtime must be a non-empty exact identity") - } - if !(1..=128).contains(&max_concurrent_requests) { - bail!("CodexConnector caller concurrency must be between 1 and 128") - } - let client = CodexConnectorClient::new(endpoint, connection_key, MAX_FRAME_BYTES, None)?; - Ok(Self { - client, - request_gate: std::sync::Arc::new(Semaphore::new(max_concurrent_requests)), - caller_runtime_id, - fast_model: fast_model.into(), - balanced_model: balanced_model.into(), - capable_model: capable_model.into(), - }) - } - - pub fn from_runtime_secret( - endpoint: SocketAddr, - path: impl AsRef, - caller_runtime_id: impl Into, - fast_model: impl Into, - balanced_model: impl Into, - capable_model: impl Into, - max_concurrent_requests: usize, - ) -> Result { - let bytes = Zeroizing::new(std::fs::read(path.as_ref())?); - let raw = std::str::from_utf8(bytes.as_slice())?; - let connection_key = raw.trim_end_matches(['\r', '\n']); - if connection_key.is_empty() || connection_key.len() != raw.trim().len() { - bail!("CodexConnector key file is empty or contains surrounding whitespace") - } - Self::new( - endpoint, - connection_key.to_owned(), - caller_runtime_id, - fast_model, - balanced_model, - capable_model, - max_concurrent_requests, - ) - } - - fn invoke(&self, request: &ModelStageRequest) -> Result { - self.invoke_with_input(request, None) - } - - fn invoke_with_input( - &self, - request: &ModelStageRequest, - conversation: Option<&[ModelInputItem]>, - ) -> Result { - let request_id = format!("ghostlight-model-{}", uuid::Uuid::new_v4()); - let resolved_model = match request.model.as_str() { - MODEL_FAST => self.fast_model.clone(), - MODEL_BALANCED => self.balanced_model.clone(), - MODEL_CAPABLE => self.capable_model.clone(), - explicit => explicit.to_string(), - }; - let mut provider_request = CodexProviderRequest::new( - request_id.clone(), - request_id, - resolved_model, - "Execute the supplied Ghostlight model stage. Treat it as projected context, obey its output contract, and return only the requested public answer.", - ); - provider_request.input = conversation.map_or_else( - || { - vec![CodexInputItem::UserText { - text: request.lived_stream.clone(), - }] - }, - |input| { - input - .iter() - .map(|item| match item { - ModelInputItem::UserText { text } => { - CodexInputItem::UserText { text: text.clone() } - } - ModelInputItem::AssistantText { text } => { - CodexInputItem::AssistantText { text: text.clone() } - } - }) - .collect() - }, - ); - provider_request.reasoning_effort = Some( - if matches!(request.model.as_str(), MODEL_BALANCED | MODEL_CAPABLE) { - "medium" - } else { - "low" - } - .to_string(), - ); - provider_request.tools = Vec::new(); - provider_request.tool_choice = CodexToolChoice::Auto; - provider_request.parallel_tool_calls = false; - if let Some(schema) = request.output_schema.as_ref() { - let mut schema = schema.clone(); - project_strict_responses_schema(&mut schema)?; - provider_request.output_format_name = Some(output_format_name(&request.stage)); - provider_request.output_schema_json = Some(serde_json::to_string(&schema)?); - } - provider_request.max_output_tokens = request.max_output_tokens; - provider_request.prompt_cache_key = Some(prompt_cache_key(request)?); - - let native_request_sha256 = Sha256::digest(match conversation { - Some(input) => rmp_serde::to_vec_named(&(request, input))?, - None => rmp_serde::to_vec(request)?, - }) - .into(); - let invocation = CodexTransportInvocation::new( - self.caller_runtime_id.clone(), - unix_ms()?.saturating_add(REQUEST_EXPIRY.as_millis() as u64), - native_request_sha256, - provider_request, - )?; - observed_output(self.client.execute(&invocation)?) - } -} - -#[async_trait] -impl ModelPort for CodexConnectorModelPort { - async fn run(&self, request: &ModelStageRequest) -> Result { - Ok(self.run_observed(request).await?.content) - } - - async fn run_observed(&self, request: &ModelStageRequest) -> Result { - let permit = self - .request_gate - .clone() - .acquire_owned() - .await - .map_err(|_| anyhow::anyhow!("CodexConnector request gate closed"))?; - let port = self.clone(); - let request = request.clone(); - tokio::task::spawn_blocking(move || { - let _permit = permit; - port.invoke(&request) - }) - .await? - } - - async fn run_observed_conversation( - &self, - request: &ModelStageRequest, - input: &[ModelInputItem], - ) -> Result { - let permit = self - .request_gate - .clone() - .acquire_owned() - .await - .map_err(|_| anyhow::anyhow!("CodexConnector request gate closed"))?; - let port = self.clone(); - let request = request.clone(); - let input = input.to_vec(); - tokio::task::spawn_blocking(move || { - let _permit = permit; - port.invoke_with_input(&request, Some(&input)) - }) - .await? - } - - fn provider(&self) -> &'static str { - "codex-connector" - } - - fn attempt_timeout(&self, request: &ModelStageRequest) -> Duration { - match (request.stage.as_str(), request.model.as_str()) { - ("world_compile", MODEL_CAPABLE) => WORLD_COMPILE_ATTEMPT_TIMEOUT, - ("destination_compile", MODEL_CAPABLE) => DESTINATION_COMPILE_ATTEMPT_TIMEOUT, - ("destination_compile", MODEL_BALANCED) => BALANCED_DESTINATION_COMPILE_ATTEMPT_TIMEOUT, - (_, MODEL_BALANCED) => BALANCED_ATTEMPT_TIMEOUT, - (_, MODEL_CAPABLE) => CAPABLE_ATTEMPT_TIMEOUT, - _ => FAST_ATTEMPT_TIMEOUT, - } - } -} - -fn observed_output(result: codex_connector::CodexTransportResult) -> Result { - let (events, receipt) = match result.disposition { - CodexTransportDisposition::Refused(reason) => { - bail!("CodexConnector refused request: {reason:?}") - } - CodexTransportDisposition::Transported { events, receipt } => (events, receipt), - }; - let mut content = String::new(); - for event in events { - match event.payload { - CodexTransportEventPayload::TextDelta { text } => content.push_str(&text), - CodexTransportEventPayload::ToolCall { .. } => { - bail!("CodexConnector exposed an inadmissible tool call") - } - } - } - let (provider_response_id, prompt_tokens, completion_tokens, reasoning_tokens, cache_hits) = - match receipt.outcome { - CodexTransportOutcome::Completed { - provider_response_id, - input_tokens, - output_tokens, - reasoning_output_tokens, - cached_input_tokens, - } => ( - provider_response_id, - input_tokens.unwrap_or_default(), - output_tokens.unwrap_or_default(), - reasoning_output_tokens.unwrap_or_default(), - cached_input_tokens.unwrap_or_default(), - ), - CodexTransportOutcome::Failed { - failure_kind, - message, - } => bail!("Codex provider failed ({failure_kind}): {message}"), - }; - Ok(ModelProviderOutput { - content, - resolved_model: Some(receipt.model), - provider_request_id: provider_response_id, - system_fingerprint: None, - finish_reason: Some("completed".to_string()), - token_usage: Some(ModelTokenUsage { - prompt_tokens, - completion_tokens, - total_tokens: prompt_tokens.saturating_add(completion_tokens), - prompt_cache_hit_tokens: cache_hits, - prompt_cache_miss_tokens: prompt_tokens.saturating_sub(cache_hits), - reasoning_tokens, - }), - transport_features: vec![ - "cultnet.direct-pipe".to_string(), - "gamecult.codex.transport.v2".to_string(), - receipt.transport, - ], - }) -} - -fn output_format_name(stage: &str) -> String { - let name = stage - .chars() - .map(|character| { - if character.is_ascii_alphanumeric() || matches!(character, '_' | '-') { - character - } else { - '_' - } - }) - .take(64) - .collect::(); - if name.is_empty() { - "ghostlight_output".to_string() - } else { - name - } -} - -fn prompt_cache_key(request: &ModelStageRequest) -> Result { - let schema = request - .output_schema - .as_ref() - .map(serde_json::to_vec) - .transpose()? - .unwrap_or_default(); - let digest = Sha256::digest( - [ - request.stage.as_bytes(), - &[0], - request.model.as_bytes(), - &[0], - &schema, - ] - .concat(), - ); - Ok(format!("ghostlight:{digest:x}")) -} - -fn unix_ms() -> Result { - Ok(SystemTime::now() - .duration_since(UNIX_EPOCH) - .context("system clock predates Unix epoch")? - .as_millis() - .try_into() - .context("system clock does not fit u64 milliseconds")?) -} - -pub(crate) fn project_strict_responses_schema(schema: &mut serde_json::Value) -> Result<()> { - lower_schema_for_responses_format(schema); - require_closed_responses_objects(schema, "$")?; - if schema.get("type").and_then(serde_json::Value::as_str) != Some("object") { - bail!("Responses output schema root must have type object") - } - if !responses_schema_is_strict(schema) { - bail!("projected Responses output schema is not strict") - } - Ok(()) -} - -fn responses_schema_is_strict(schema: &serde_json::Value) -> bool { - match schema { - serde_json::Value::Object(map) => { - if map.contains_key("$ref") && map.len() != 1 { - return false; - } - if map.get("const").is_some_and(|value| { - matches!( - value, - serde_json::Value::Array(_) | serde_json::Value::Object(_) - ) - }) { - return false; - } - if (map.contains_key("const") || map.contains_key("enum")) && !map.contains_key("type") - { - return false; - } - if map.get("type").and_then(serde_json::Value::as_str) == Some("array") - && !map.contains_key("items") - { - return false; - } - if schema_map_describes_object(map) { - if map.get("additionalProperties") != Some(&serde_json::Value::Bool(false)) { - return false; - } - let Some(properties) = map.get("properties").and_then(serde_json::Value::as_object) - else { - return false; - }; - let Some(required) = map.get("required").and_then(serde_json::Value::as_array) - else { - return false; - }; - if properties - .keys() - .any(|key| !required.iter().any(|item| item.as_str() == Some(key))) - { - return false; - } - } - map.values().all(responses_schema_is_strict) - } - serde_json::Value::Array(values) => values.iter().all(responses_schema_is_strict), - _ => true, - } -} - -fn require_closed_responses_objects(schema: &mut serde_json::Value, path: &str) -> Result<()> { - match schema { - serde_json::Value::Object(map) => { - if map.contains_key("$ref") && map.len() != 1 { - bail!("Responses schema {path} places sibling keywords beside $ref") - } - let describes_object = schema_map_describes_object(map); - if describes_object { - map.insert("type".to_string(), serde_json::json!("object")); - let properties = map - .get("properties") - .and_then(serde_json::Value::as_object) - .cloned() - .unwrap_or_default(); - let canonical_required = map - .get("required") - .and_then(serde_json::Value::as_array) - .cloned() - .unwrap_or_default(); - for required in &canonical_required { - let required = required.as_str().ok_or_else(|| { - anyhow::anyhow!("Responses schema {path} has a non-string required key") - })?; - if !properties.contains_key(required) { - bail!("Responses schema {path} requires undeclared property {required:?}") - } - } - let canonical_required = canonical_required - .into_iter() - .filter_map(|value| value.as_str().map(ToString::to_string)) - .collect::>(); - let mut projected = serde_json::Map::new(); - for (name, mut property) in properties { - require_closed_responses_objects( - &mut property, - &format!("{path}.properties.{name}"), - )?; - if !canonical_required.contains(&name) { - property = nullable_responses_property(property); - } - projected.insert(name, property); - } - let required = projected - .keys() - .cloned() - .map(serde_json::Value::String) - .collect(); - map.insert("properties".to_string(), projected.into()); - map.insert("required".to_string(), serde_json::Value::Array(required)); - map.insert("additionalProperties".to_string(), serde_json::json!(false)); - } - for (name, value) in map.iter_mut() { - if name != "properties" || !describes_object { - require_closed_responses_objects(value, &format!("{path}.{name}"))?; - } - } - Ok(()) - } - serde_json::Value::Array(values) => { - for (index, value) in values.iter_mut().enumerate() { - require_closed_responses_objects(value, &format!("{path}[{index}]"))?; - } - Ok(()) - } - _ => Ok(()), - } -} - -fn schema_map_describes_object(map: &serde_json::Map) -> bool { - map.get("type").and_then(serde_json::Value::as_str) == Some("object") - || [ - "properties", - "required", - "additionalProperties", - "patternProperties", - "propertyNames", - "minProperties", - "maxProperties", - ] - .iter() - .any(|keyword| map.contains_key(*keyword)) -} - -fn parent_relative_object_alternatives(value: &serde_json::Value) -> bool { - value.as_array().is_some_and(|alternatives| { - !alternatives.is_empty() - && alternatives.iter().all(|alternative| { - alternative.as_object().is_some_and(|map| { - !map.contains_key("type") - && !map.contains_key("$ref") - && map - .keys() - .any(|key| matches!(key.as_str(), "properties" | "required")) - && map.keys().all(|key| { - matches!( - key.as_str(), - "properties" | "required" | "title" | "description" | "$comment" - ) - }) - }) - }) - }) -} - -fn inferred_json_type(value: &serde_json::Value) -> &'static str { - match value { - serde_json::Value::Null => "null", - serde_json::Value::Bool(_) => "boolean", - serde_json::Value::Number(number) if number.is_i64() || number.is_u64() => "integer", - serde_json::Value::Number(_) => "number", - serde_json::Value::String(_) => "string", - serde_json::Value::Array(_) => "array", - serde_json::Value::Object(_) => "object", - } -} - -fn infer_responses_literal_type(map: &mut serde_json::Map) { - if map.contains_key("type") { - return; - } - let mut types = BTreeSet::new(); - if let Some(value) = map.get("const") { - types.insert(inferred_json_type(value)); - } else if let Some(values) = map.get("enum").and_then(serde_json::Value::as_array) { - for value in values { - types.insert(inferred_json_type(value)); - } - } - match types.len() { - 0 => {} - 1 => { - map.insert( - "type".to_string(), - serde_json::json!(types.into_iter().next().expect("one literal type")), - ); - } - _ => { - map.insert( - "type".to_string(), - types.into_iter().collect::>().into(), - ); - } - } -} - -fn compound_const_array_item_schema(values: &[serde_json::Value]) -> serde_json::Value { - if values.is_empty() { - // maxItems: 0 makes this item type unreachable, but the Responses - // schema dialect still expects arrays to declare an item shape. - return serde_json::json!({"type":"string"}); - } - if values.iter().all(serde_json::Value::is_string) { - let values = values - .iter() - .filter_map(serde_json::Value::as_str) - .map(ToString::to_string) - .collect::>() - .into_iter() - .collect::>(); - return if values.len() == 1 { - serde_json::json!({"type":"string", "const":values[0]}) - } else { - serde_json::json!({"type":"string", "enum":values}) - }; - } - - let mut alternatives = Vec::new(); - let mut seen = BTreeSet::new(); - for value in values { - let mut alternative = serde_json::json!({"const":value}); - lower_schema_for_responses_format(&mut alternative); - let digest = serde_json::to_string(&alternative).expect("JSON schema serializes"); - if seen.insert(digest) { - alternatives.push(alternative); - } - } - if alternatives.len() == 1 { - alternatives.pop().expect("one alternative") - } else { - serde_json::json!({"anyOf":alternatives}) - } -} - -fn lower_compound_const(map: &mut serde_json::Map) { - let Some(value) = map.get("const").cloned() else { - return; - }; - match value { - serde_json::Value::Array(values) => { - map.remove("const"); - map.insert("type".to_string(), serde_json::json!("array")); - map.insert("minItems".to_string(), serde_json::json!(values.len())); - map.insert("maxItems".to_string(), serde_json::json!(values.len())); - map.insert( - "items".to_string(), - compound_const_array_item_schema(&values), - ); - } - serde_json::Value::Object(values) => { - map.remove("const"); - map.insert("type".to_string(), serde_json::json!("object")); - map.insert( - "required".to_string(), - serde_json::Value::Array( - values - .keys() - .cloned() - .map(serde_json::Value::String) - .collect(), - ), - ); - map.insert( - "properties".to_string(), - values - .into_iter() - .map(|(name, value)| (name, serde_json::json!({"const":value}))) - .collect::>() - .into(), - ); - map.insert("additionalProperties".to_string(), serde_json::json!(false)); - } - _ => {} - } -} - -fn nullable_responses_property(property: serde_json::Value) -> serde_json::Value { - if property - .get("anyOf") - .and_then(serde_json::Value::as_array) - .is_some_and(|variants| { - variants.iter().any(|variant| { - variant.get("type").and_then(serde_json::Value::as_str) == Some("null") - }) - }) - { - property - } else { - serde_json::json!({"anyOf":[property,{"type":"null"}]}) - } -} - -const RESPONSES_UNSUPPORTED_SCHEMA_KEYWORDS: &[&str] = &[ - "allOf", - "not", - "dependentRequired", - "dependentSchemas", - "if", - "then", - "else", - "patternProperties", - "propertyNames", - "minProperties", - "maxProperties", - "unevaluatedProperties", - "uniqueItems", - "contains", - "minContains", - "maxContains", - "prefixItems", - "unevaluatedItems", - "default", - "examples", - "readOnly", - "writeOnly", - "$schema", - "$id", - "$anchor", - "$dynamicAnchor", - "$dynamicRef", - "$vocabulary", -]; - -fn lower_schema_for_responses_format(schema: &mut serde_json::Value) { - let serde_json::Value::Object(map) = schema else { - return; - }; - lower_compound_const(map); - infer_responses_literal_type(map); - if map.get("format").and_then(serde_json::Value::as_str) == Some("uuid") { - map.remove("format"); - map.entry("pattern".to_string()).or_insert_with(|| { - serde_json::json!( - "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" - ) - }); - } - for unsupported in RESPONSES_UNSUPPORTED_SCHEMA_KEYWORDS { - map.remove(*unsupported); - } - if let Some(one_of) = map.remove("oneOf") { - map.insert("anyOf".to_string(), one_of); - } - if map - .get("anyOf") - .is_some_and(parent_relative_object_alternatives) - { - map.remove("anyOf"); - } - for collection in ["properties", "$defs", "definitions"] { - if let Some(serde_json::Value::Object(children)) = map.get_mut(collection) { - for child in children.values_mut() { - lower_schema_for_responses_format(child); - } - } - } - if let Some(items) = map.get_mut("items") { - match items { - serde_json::Value::Array(items) => { - for item in items { - lower_schema_for_responses_format(item); - } - } - item => lower_schema_for_responses_format(item), - } - } - if let Some(serde_json::Value::Array(alternatives)) = map.get_mut("anyOf") { - for alternative in alternatives { - lower_schema_for_responses_format(alternative); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::io::{Read, Write}; - use std::net::TcpListener; - - use codex_connector::{ - CodexTransportEvent, CodexTransportKey, CodexTransportReceipt, decrypt_invocation, - encrypt_result, - }; - - #[tokio::test] - async fn connector_port_preserves_append_only_roles_in_the_provider_request() -> Result<()> { - let listener = TcpListener::bind("127.0.0.1:0")?; - let endpoint = listener.local_addr()?; - let server = std::thread::spawn(move || -> Result { - let (mut stream, _) = listener.accept()?; - let mut length = [0_u8; 4]; - stream.read_exact(&mut length)?; - let mut payload = vec![0_u8; u32::from_be_bytes(length) as usize]; - stream.read_exact(&mut payload)?; - let envelope = rmp_serde::from_slice(&payload)?; - let key = CodexTransportKey::from_connection_secret("connector-test-key")?; - let invocation = decrypt_invocation(&envelope, &key)?; - let receipt = CodexTransportReceipt { - schema_id: codex_connector::RECEIPT_SCHEMA_ID.to_string(), - request_id: invocation.request_id().to_string(), - caller_runtime_id: invocation.caller_runtime_id.clone(), - native_request_sha256: invocation.native_request_sha256, - provider_request_sha256: invocation.provider_request_sha256, - model: invocation.request.model.clone(), - transport: "codex-connector-test".to_string(), - outcome: CodexTransportOutcome::Completed { - provider_response_id: Some("response-1".to_string()), - input_tokens: Some(100), - output_tokens: Some(10), - reasoning_output_tokens: Some(3), - cached_input_tokens: Some(80), - }, - }; - let result = codex_connector::CodexTransportResult::transported( - &invocation, - vec![CodexTransportEvent { - sequence: 0, - payload: CodexTransportEventPayload::TextDelta { - text: "{\"answer\":\"ready\"}".to_string(), - }, - }], - receipt, - ); - let response = rmp_serde::to_vec(&encrypt_result(&result, &key)?)?; - stream.write_all(&(response.len() as u32).to_be_bytes())?; - stream.write_all(&response)?; - Ok(invocation) - }); - - let port = CodexConnectorModelPort::new( - endpoint, - "connector-test-key".to_string(), - "ghostlight-dungeon-yggdrasil", - "gpt-5.6-luna", - "gpt-5.6-terra", - "gpt-5.6-luna", - 1, - )?; - assert_eq!(port.request_gate.available_permits(), 1); - let request = ModelStageRequest { - stage: "test_interpreter".to_string(), - model: MODEL_BALANCED.to_string(), - snapshot_binding: "revision:7".to_string(), - lived_stream: "Return the typed answer.".to_string(), - output_schema: Some(serde_json::json!({ - "type":"object", - "required":["answer"], - "properties":{"answer":{"type":"string"}}, - "additionalProperties":false - })), - source_receipt_ids: Vec::new(), - temperature: Some(0.0), - max_output_tokens: Some(512), - }; - let input = vec![ - ModelInputItem::user("Choose one action."), - ModelInputItem::assistant("{\"answer\":\"draft\"}"), - ModelInputItem::user("The tool rejected that draft; repair it."), - ]; - let output = port.run_observed_conversation(&request, &input).await?; - let invocation = server.join().expect("server thread")?; - assert_eq!(invocation.request.model, "gpt-5.6-terra"); - assert_eq!(invocation.request.max_output_tokens, Some(512)); - assert_eq!( - invocation.request.output_format_name.as_deref(), - Some("test_interpreter") - ); - assert!(matches!( - invocation.request.input.as_slice(), - [ - CodexInputItem::UserText { text: first }, - CodexInputItem::AssistantText { text: second }, - CodexInputItem::UserText { text: third }, - ] if first == "Choose one action." - && second == "{\"answer\":\"draft\"}" - && third == "The tool rejected that draft; repair it." - )); - assert_eq!(output.content, "{\"answer\":\"ready\"}"); - assert_eq!( - output.token_usage.expect("usage").prompt_cache_hit_tokens, - 80 - ); - Ok(()) - } - - #[test] - fn strict_schema_projection_closes_objects_and_makes_optional_fields_nullable() -> Result<()> { - let mut schema = serde_json::json!({ - "type":"object", - "required":["answer"], - "properties":{ - "answer":{"type":"string"}, - "note":{"type":"string","default":""}, - "kind":{"enum":["one","two"]} - } - }); - project_strict_responses_schema(&mut schema)?; - assert_eq!(schema["additionalProperties"], false); - assert_eq!( - schema["required"], - serde_json::json!(["answer", "kind", "note"]) - ); - let kind_variants = schema["properties"]["kind"]["anyOf"] - .as_array() - .context("optional enum was not projected as nullable")?; - assert!( - kind_variants - .iter() - .any(|variant| variant["type"] == "string") - ); - assert!( - kind_variants - .iter() - .any(|variant| variant["type"] == "null") - ); - assert!(schema["properties"]["note"]["anyOf"].is_array()); - assert!(responses_schema_is_strict(&schema)); - Ok(()) - } - - #[test] - fn strict_schema_projection_lowers_compound_literals_only_on_the_provider_clone() -> Result<()> - { - fn contains_compound_const(value: &serde_json::Value) -> bool { - match value { - serde_json::Value::Object(map) => { - map.get("const").is_some_and(|value| { - matches!( - value, - serde_json::Value::Array(_) | serde_json::Value::Object(_) - ) - }) || map.values().any(contains_compound_const) - } - serde_json::Value::Array(values) => values.iter().any(contains_compound_const), - _ => false, - } - } - - let native = serde_json::json!({ - "type":"object", - "required":["empty", "ids", "manifest"], - "properties":{ - "empty":{"type":"array", "const":[]}, - "ids":{"type":"array", "const":["council:a", "council:b"]}, - "manifest":{ - "type":"object", - "const":{ - "governing_ids":["council:a", "council:b"], - "schema":"fixture.v1" - } - } - }, - "additionalProperties":false - }); - let mut projected = native.clone(); - - project_strict_responses_schema(&mut projected)?; - - assert!(contains_compound_const(&native)); - assert!(!contains_compound_const(&projected)); - assert_eq!(projected["properties"]["empty"]["minItems"], 0); - assert_eq!(projected["properties"]["empty"]["maxItems"], 0); - assert_eq!(projected["properties"]["empty"]["items"]["type"], "string"); - assert_eq!(projected["properties"]["ids"]["minItems"], 2); - assert_eq!(projected["properties"]["ids"]["maxItems"], 2); - assert_eq!( - projected["properties"]["ids"]["items"]["enum"], - serde_json::json!(["council:a", "council:b"]) - ); - assert_eq!( - projected["properties"]["manifest"]["additionalProperties"], - false - ); - assert!(responses_schema_is_strict(&projected)); - - let reordered = serde_json::json!({ - "empty":[], - "ids":["council:a", "council:a"], - "manifest":{ - "governing_ids":["council:b", "council:a"], - "schema":"fixture.v1" - } - }); - assert!(jsonschema::validator_for(&projected)?.is_valid(&reordered)); - assert!(!jsonschema::validator_for(&native)?.is_valid(&reordered)); - Ok(()) - } - - #[test] - fn strict_schema_projection_rejects_ref_siblings_before_provider_submission() { - let mut schema = serde_json::json!({ - "$ref":"#/$defs/Answer", - "description":"provider-incompatible sibling" - }); - let error = project_strict_responses_schema(&mut schema) - .unwrap_err() - .to_string(); - assert!(error.contains("sibling keywords beside $ref")); - } - - #[test] - fn strict_schema_projection_rejects_root_unions_before_provider_submission() { - let mut schema = serde_json::json!({ - "oneOf":[ - { - "type":"object", - "required":["kind"], - "properties":{"kind":{"type":"string","const":"one"}}, - "additionalProperties":false - }, - { - "type":"object", - "required":["kind"], - "properties":{"kind":{"type":"string","const":"two"}}, - "additionalProperties":false - } - ] - }); - - let error = project_strict_responses_schema(&mut schema) - .unwrap_err() - .to_string(); - - assert!(error.contains("root must have type object")); - } - - #[test] - fn strict_schema_projection_rejects_arrays_without_an_item_contract() { - let mut schema = serde_json::json!({ - "type":"object", - "required":["findings"], - "properties":{ - "findings":{"type":"array", "maxItems":0} - }, - "additionalProperties":false - }); - - let error = project_strict_responses_schema(&mut schema) - .unwrap_err() - .to_string(); - - assert!(error.contains("not strict")); - } - - #[test] - fn large_compile_stages_get_bounded_specific_deadlines() -> Result<()> { - let port = CodexConnectorModelPort::new( - "127.0.0.1:4103".parse()?, - "bounded-test-key".to_string(), - "ghostlight-test", - "gpt-5.6-luna", - "gpt-5.6-terra", - "gpt-5.6-sol", - 1, - )?; - let mut request = ModelStageRequest { - stage: "world_compile".to_string(), - model: MODEL_CAPABLE.to_string(), - snapshot_binding: "revision:0".to_string(), - lived_stream: "fixture".to_string(), - output_schema: None, - source_receipt_ids: Vec::new(), - temperature: None, - max_output_tokens: None, - }; - assert_eq!( - port.attempt_timeout(&request), - WORLD_COMPILE_ATTEMPT_TIMEOUT - ); - - request.model = MODEL_BALANCED.to_string(); - assert_eq!(port.attempt_timeout(&request), BALANCED_ATTEMPT_TIMEOUT); - - request.model = MODEL_FAST.to_string(); - assert_eq!(port.attempt_timeout(&request), FAST_ATTEMPT_TIMEOUT); - - request.stage = "agency_compile".to_string(); - request.model = MODEL_CAPABLE.to_string(); - assert_eq!(port.attempt_timeout(&request), CAPABLE_ATTEMPT_TIMEOUT); - - request.stage = "destination_compile".to_string(); - assert_eq!( - port.attempt_timeout(&request), - DESTINATION_COMPILE_ATTEMPT_TIMEOUT - ); - - request.model = MODEL_BALANCED.to_string(); - assert_eq!( - port.attempt_timeout(&request), - BALANCED_DESTINATION_COMPILE_ATTEMPT_TIMEOUT - ); - - request.model = MODEL_FAST.to_string(); - assert_eq!(port.attempt_timeout(&request), FAST_ATTEMPT_TIMEOUT); - - request.stage = "destination_civic_reconciliation".to_string(); - request.model = MODEL_BALANCED.to_string(); - assert_eq!(port.attempt_timeout(&request), BALANCED_ATTEMPT_TIMEOUT); - - request.stage = "cell_interpreter".to_string(); - request.model = MODEL_FAST.to_string(); - assert_eq!(port.attempt_timeout(&request), FAST_ATTEMPT_TIMEOUT); - Ok(()) - } - - #[test] - fn cache_key_tracks_stable_stage_contract_not_dynamic_world_context() -> Result<()> { - let request = ModelStageRequest { - stage: "cell_interpreter".to_string(), - model: MODEL_CAPABLE.to_string(), - snapshot_binding: "revision:7".to_string(), - lived_stream: "A changing world slice.".to_string(), - output_schema: Some(serde_json::json!({ - "type":"object", - "properties":{"action":{"type":"string"}} - })), - source_receipt_ids: vec!["receipt:one".to_string()], - temperature: Some(0.3), - max_output_tokens: Some(512), - }; - let mut changed_context = request.clone(); - changed_context.snapshot_binding = "revision:8".to_string(); - changed_context.lived_stream = "A different world slice.".to_string(); - assert_eq!( - prompt_cache_key(&request)?, - prompt_cache_key(&changed_context)? - ); - changed_context.output_schema = Some(serde_json::json!({ - "type":"object", - "properties":{"different_action":{"type":"string"}} - })); - assert_ne!( - prompt_cache_key(&request)?, - prompt_cache_key(&changed_context)? - ); - Ok(()) - } -} diff --git a/crates/ghostlight-dungeon/src/model_runtime.rs b/crates/ghostlight-dungeon/src/model_runtime.rs deleted file mode 100644 index 6c55183..0000000 --- a/crates/ghostlight-dungeon/src/model_runtime.rs +++ /dev/null @@ -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) -> Result { - 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::() - .context("GHOSTLIGHT_CODEX_CONNECTOR_MAX_CONCURRENT_REQUESTS must be an integer")?, - }) - } - - pub fn status(&self, readiness: impl Into) -> 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>> { - if !self.credential_path.is_file() { - return Ok(None); - } - let provider: Arc = 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)) - } -} diff --git a/crates/ghostlight-dungeon/src/native_cultmesh.rs b/crates/ghostlight-dungeon/src/native_cultmesh.rs deleted file mode 100644 index 2161c75..0000000 --- a/crates/ghostlight-dungeon/src/native_cultmesh.rs +++ /dev/null @@ -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, -} - -#[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, - pub refresh_expires_at: Option, -} - -#[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::(); - 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 { - 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 { - 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 { - 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(request: &CultNetMessage) -> Result { - 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 { - operation_response(request, "accepted", payload_schema, payload, Vec::new()) -} - -fn failure_response(request: &CultNetMessage, code: &str, message: &str) -> Result { - 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, -) -> Result { - 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::(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)); - } -} diff --git a/crates/ghostlight-dungeon/src/newspaper.rs b/crates/ghostlight-dungeon/src/newspaper.rs deleted file mode 100644 index f11b6ea..0000000 --- a/crates/ghostlight-dungeon/src/newspaper.rs +++ /dev/null @@ -1,6120 +0,0 @@ -use crate::{ - agent::{ - ModelAgentProgress, ModelAgentSpec, ModelAgentTool, ModelAgentToolContext, - ModelAgentToolOutcome, - }, - domain::{ - Campaign, Event, MAX_PUBLIC_EVENT_SUMMARY_CHARS, NewsIssue, PublicEventAssertionStatus, - }, - model::{ - MODEL_BALANCED, MODEL_CAPABLE, ModelPort, ModelStageReceipt, ModelStageRequest, - run_validated_stage, - }, - persistence::CampaignStore, -}; -use anyhow::{Result, anyhow}; -use async_trait::async_trait; -use chrono::{DateTime, Utc}; -use schemars::{JsonSchema, schema_for}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::{ - collections::{BTreeMap, BTreeSet}, - error::Error as StdError, - fmt, -}; - -const MAX_FRONT_PAGE_ARTICLES: usize = 6; -const MAX_PUBLIC_RECORD_QUERY_RESULTS: usize = 24; -const MAX_NARRATIVE_SELECTION_STEPS: usize = 12; -const NEWSROOM_CONTRACT_VERSION: &str = "character-newsroom.v16"; -const EDITION_LABEL: &str = "Current Edition"; -const ALLOWED_SECTIONS: [&str; 6] = [ - "Front Page", - "Realm Affairs", - "Courts & Councils", - "Guilds & Trade", - "Dispatches", - "Comment", -]; - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldNewspaperStaffMember { - pub id: String, - pub name: String, - #[schemars(length(min = 1, max = 500))] - pub character: String, - #[schemars(length(min = 1, max = 6))] - pub biases: Vec, - #[schemars(length(min = 1, max = 6))] - pub preferences: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldNewspaperJournalist { - pub staff: WorldNewspaperStaffMember, - #[schemars(length(min = 1, max = 60))] - pub byline: String, - #[schemars(length(min = 1, max = 160))] - pub beat: String, - #[schemars(length(min = 1, max = 500))] - pub voice: String, - #[schemars(length(min = 1, max = 4))] - pub source_instincts: Vec, - #[schemars(length(min = 1, max = 3))] - pub blind_spots: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldNewspaperNewsroom { - pub assignment_editor: WorldNewspaperStaffMember, - #[schemars(length(min = 1, max = 6))] - pub journalists: Vec, - pub copy_editor: WorldNewspaperStaffMember, - pub night_editor: WorldNewspaperStaffMember, -} - -pub fn canopy_ledger_newsroom() -> WorldNewspaperNewsroom { - WorldNewspaperNewsroom { - assignment_editor: WorldNewspaperStaffMember { - id: "veyra-kest".into(), - name: "Veyra Kest".into(), - character: "A veteran city editor who treats official vagueness as a confession delivered without the useful nouns.".into(), - biases: vec![ - "Institutional euphemism usually protects whoever already has a seal and a chair.".into(), - "A public consequence outranks an announced intention.".into(), - ], - preferences: vec![ - "Conflict with named opposing actors and visible stakes.".into(), - "Continuing stories whose new turn changes what readers should fear or demand.".into(), - ], - }, - journalists: vec![ - WorldNewspaperJournalist { - staff: WorldNewspaperStaffMember { - id: "aven-tarl".into(), - name: "Aven Tarl".into(), - character: "A court reporter with immaculate cuffs, a long memory for humiliation, and no respect for inherited dignity once it becomes funny.".into(), - biases: vec!["Power is most legible when it is embarrassed in public.".into()], - preferences: vec!["Court scandal, succession, hypocrisy, and status reversals.".into()], - }, - byline: "Aven Tarl".into(), - beat: "Courts, councils, succession, and the social machinery of rank.".into(), - voice: "Dry, exact, and delighted by status reversal. Aven quotes ceremonial language just long enough for the facts to make it ridiculous, then ends on the person whose dignity paid for the spectacle.".into(), - source_instincts: vec![ - "Clerks, chamber servants, discarded advisers, and rivals who know which title was omitted.".into(), - "Orders, seating plans, sealed filings, and tiny breaches of protocol that expose a larger panic.".into(), - ], - blind_spots: vec![ - "May treat sincere grief as theatre when it occurs inside a powerful household.".into(), - ], - }, - WorldNewspaperJournalist { - staff: WorldNewspaperStaffMember { - id: "mera-quill".into(), - name: "Mera Quill".into(), - character: "A street correspondent who listens first to witnesses, children, mourners, and whoever must clean the room after policy leaves it.".into(), - biases: vec!["Procedure is often the name authority gives to somebody else's pain.".into()], - preferences: vec!["Bodies, witnesses, private cost, public anger, and grotesque physical evidence.".into()], - }, - byline: "Mera Quill".into(), - beat: "Streets, households, witnesses, mourning, and the bodily residue of public decisions.".into(), - voice: "Intimate, sensory, and morally impatient. Mera stays near the witness, names who cleans the blood or carries the water, and lets one concrete indignity indict an institution without asking permission.".into(), - source_instincts: vec![ - "Witnesses, children, mourners, cleaners, displaced households, and people officials call incidental.".into(), - "Objects left at a scene, rituals interrupted, injuries, smells, queues, and public anger.".into(), - ], - blind_spots: vec![ - "Distrusts abstraction so deeply that necessary coordination can look like evasion before it has failed.".into(), - ], - }, - WorldNewspaperJournalist { - staff: WorldNewspaperStaffMember { - id: "ossan-reed".into(), - name: "Ossan Reed".into(), - character: "A former works clerk who can smell a failing pump, a cooked ledger, and management's preferred order for blaming the shift.".into(), - biases: vec!["Infrastructure failures are political decisions with tools attached.".into()], - preferences: vec!["Labor, shortages, hazardous works, guild conflict, and material consequences.".into()], - }, - byline: "Ossan Reed".into(), - beat: "Works, labor, maintenance, shortages, guild practice, and infrastructure failure.".into(), - voice: "Mechanically specific, causal, and salted with shift-floor gallows humor. Ossan follows pressure, tools, schedules, and chains of command until somebody's supposedly technical decision acquires a name.".into(), - source_instincts: vec![ - "Shift workers, repair crews, stores clerks, safety stewards, and the logbook management forgot was public.".into(), - "Failure sequences, material inventories, bypasses, shutdown orders, and who was placed nearest the hazard.".into(), - ], - blind_spots: vec![ - "Often assumes a management incentive explains a failure before allowing enough room for ordinary incompetence.".into(), - ], - }, - WorldNewspaperJournalist { - staff: WorldNewspaperStaffMember { - id: "lysa-fen".into(), - name: "Lysa Fen".into(), - character: "A border correspondent who reads every truce as a maneuver and every maneuver as somebody else's future funeral.".into(), - biases: vec!["Security claims deserve to be read from the exposed side of the boundary.".into()], - preferences: vec!["Borders, armed orders, treaties, migrations, and rival countermoves.".into()], - }, - byline: "Lysa Fen".into(), - beat: "Borders, armed orders, treaties, crossings, migration, and contested jurisdiction.".into(), - voice: "Clipped, tactical, and suspicious of the passive voice. Lysa reconstructs who moved, who waited, and who had the cleaner escape route, then tells readers which reassuring phrase is likely to become a casualty list.".into(), - source_instincts: vec![ - "Couriers, deserters, checkpoint families, quartermasters, scouts, and treaty interpreters.".into(), - "Route changes, refused orders, missing watches, supply movement, and rival countermoves.".into(), - ], - blind_spots: vec![ - "Finds maneuvers so readily that she can underweight panic, accident, and institutional confusion.".into(), - ], - }, - WorldNewspaperJournalist { - staff: WorldNewspaperStaffMember { - id: "corin-vey".into(), - name: "Corin Vey".into(), - character: "A trade columnist who believes every noble abstraction eventually arrives as a toll, an empty stall, or a favor owed.".into(), - biases: vec!["Markets reveal alliances that proclamations try to hide.".into()], - preferences: vec!["Trade, tolls, communes, debt, patronage, and who profits from disorder.".into()], - }, - byline: "Corin Vey".into(), - beat: "Trade, tolls, debt, patronage, provisioning, and the household price of policy.".into(), - voice: "Wry, ledger-minded, and relentlessly distributive. Corin follows a noble abstraction until it becomes a fee, an empty stall, a privileged queue, or a favor somebody will collect later.".into(), - source_instincts: vec![ - "Toll clerks, traders, household cooperatives, carriers, lenders, and market gossips who remember yesterday's price.".into(), - "Ledgers, petitions, route costs, shortages, exemptions, and suspiciously well-provisioned allies.".into(), - ], - blind_spots: vec![ - "Can force experiences that are not transactions into a market frame because the ledger usually rewards the habit.".into(), - ], - }, - ], - copy_editor: WorldNewspaperStaffMember { - id: "dalen-marr".into(), - name: "Dalen Marr".into(), - character: "A copy editor with a jeweller's patience for exact language and a personal grudge against causation smuggled through a comma.".into(), - biases: vec!["Certainty is expensive and reporters spend it too freely.".into()], - preferences: vec!["Complete factual query lists, exact quoted passages, and no proposed prose.".into()], - }, - night_editor: WorldNewspaperStaffMember { - id: "meret-sorn".into(), - name: "Meret Sorn".into(), - character: "A deadline editor who can remove a libelous hinge without sanding the blade off the sentence around it.".into(), - biases: vec!["A late correction is survivable; a page that says nothing is not worth printing.".into()], - preferences: vec!["The smallest repair that clears every lodged objection and preserves the reporter's case.".into()], - }, - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct WorldNewspaperIssue { - pub schema: String, - pub id: String, - pub title: String, - pub edition_label: String, - pub at: DateTime, - pub source_world_revision: u64, - pub lead_article_id: Option, - pub editorial_agenda: Option, - pub articles: Vec, - pub editorial_receipt_ids: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct WorldNewspaperArticle { - pub id: String, - pub section: String, - pub headline: String, - pub deck: String, - pub byline: String, - pub dateline: Option, - pub paragraphs: Vec, - pub sources: Vec, -} - -impl WorldNewspaperArticle { - pub fn source_news_ids(&self) -> Vec { - self.sources - .iter() - .flat_map(|source| source.source_news_ids.iter().cloned()) - .collect::>() - .into_iter() - .collect() - } - - pub fn event_ids(&self) -> Vec { - self.sources - .iter() - .flat_map(|source| source.facts.iter()) - .flat_map(|fact| fact.event_ids.iter().cloned()) - .collect::>() - .into_iter() - .collect() - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct WorldNewspaperSourceCitation { - pub citation: String, - pub source_news_ids: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub source_times: Vec>, - pub source_channels: Vec, - pub source_reliability: Vec, - pub facts: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct WorldNewspaperSourceFact { - pub event_ids: Vec, - pub account: String, - pub assertion_status: WorldNewspaperAssertionStatus, - pub named_people: Vec, - pub institutions: Vec, - pub populations: Vec, - pub places: Vec, -} - -pub type WorldNewspaperAssertionStatus = PublicEventAssertionStatus; - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct WorldNewspaperNamedPerson { - pub name: String, - /// Empty until the canonical subject state owns an explicit attribute. - pub supported_identity_attributes: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct WorldNewspaperGroundingFinding { - pub article_index: u16, - pub category: WorldNewspaperGroundingCategory, - pub claim_or_phrase: String, - pub reason: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum WorldNewspaperGroundingCategory { - UnsupportedFact, - UnearnedAttribution, - ProceduralLeakage, - MechanicalCopy, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct WorldNewspaperComposition { - pub schema: String, - pub issue: WorldNewspaperIssue, - pub copy_desk: WorldNewspaperCopyDeskReport, - pub press_close: WorldNewspaperPressClose, - pub model_receipts: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldNewspaperCopyDeskReport { - #[schemars(length(min = 1, max = 500))] - pub assessment: String, - #[schemars(length(max = 24))] - pub queries: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct WorldNewspaperPressClose { - pub schema: String, - pub source_checkpoint_id: String, - pub copy_desk_receipt_id: String, - pub night_editor_receipt_id: String, - pub night_editor_action_applied: bool, - pub addressed_query_indices: Vec, - pub changed_article_indices: Vec, - pub source_page_digest: String, - pub printed_page_digest: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum WorldNewspaperCloseOrigin { - InitialCopyDesk, - LegacyV7Checkpoint, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[serde(deny_unknown_fields)] -struct WorldNewspaperCloseCheckpoint { - schema: String, - id: String, - publication_task_binding: String, - editorial_binding: String, - origin: WorldNewspaperCloseOrigin, - source_checkpoint_id: Option, - editorial_agenda: WorldNewspaperEditorialAgenda, - draft: EditorialPageDraft, - copy_desk: WorldNewspaperCopyDeskReport, - model_receipt_ids: Vec, - receipt_chain_digest: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[serde(tag = "stage", rename_all = "snake_case", deny_unknown_fields)] -enum WorldNewspaperProductionContent { - EditorialAgenda { - editorial_agenda: WorldNewspaperEditorialAgenda, - }, - FiledArticle { - agenda_checkpoint_id: String, - article_index: u16, - assignment_digest: String, - journalist_id: String, - article: EditorialArticleDraft, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[serde(deny_unknown_fields)] -struct WorldNewspaperProductionCheckpoint { - schema: String, - id: String, - publication_task_binding: String, - editorial_binding: String, - content: WorldNewspaperProductionContent, - model_receipt_ids: Vec, - receipt_chain_digest: String, - content_digest: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[serde(deny_unknown_fields)] -struct PersistedWorldNewspaperComposition { - schema: String, - publication_task_binding: String, - editorial_binding: String, - source_checkpoint_id: Option, - composition: WorldNewspaperComposition, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct WorldNewspaperCompositionFailure { - pub message: String, - pub model_receipts: Vec, -} - -impl fmt::Display for WorldNewspaperCompositionFailure { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str(&self.message) - } -} - -impl StdError for WorldNewspaperCompositionFailure {} - -#[derive(Clone, Debug, Serialize, PartialEq, Eq)] -struct PublicRecordProjection { - record_id: String, - at: DateTime, - channel: String, - headline: String, - reliability: String, - facts: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldNewspaperEditorialAgenda { - #[serde(default)] - pub issue_shape: WorldNewspaperIssueShape, - #[serde(default)] - #[schemars(length(max = 500))] - pub issue_shape_rationale: String, - #[schemars(length(min = 1, max = 500))] - pub dominant_throughline: String, - #[schemars(length(min = 1, max = 500))] - pub reader_stake: String, - #[schemars(length(min = 1, max = 6))] - pub story_pitches: Vec, -} - -#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum WorldNewspaperIssueShape { - SpecialIssue, - #[default] - GeneralIssue, -} - -#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum WorldNewspaperNarrativeFunction { - LeadChronology, - Consequence, - Accountability, - Opposition, - CounterNarrative, - #[default] - IndependentBeat, -} - -#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum WorldNewspaperContextRole { - OwnsIssueChronology, - AssumesIssueChronology, - #[default] - SelfContained, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldNewspaperStoryPitch { - pub lead: bool, - #[serde(default)] - pub section: String, - #[serde(default)] - pub journalist_id: String, - #[serde(default)] - pub narrative_function: WorldNewspaperNarrativeFunction, - #[serde(default)] - pub context_role: WorldNewspaperContextRole, - #[serde(default)] - #[schemars(length(max = 500))] - pub assignment_reason: String, - #[schemars(length(min = 1))] - pub citations: Vec, - #[serde(default)] - pub focus_citation: String, - #[schemars(length(min = 1, max = 500))] - #[serde(alias = "angle")] - pub narrative_claim: String, - #[schemars(length(min = 1, max = 500))] - pub tension: String, - #[schemars(length(min = 1, max = 500))] - pub public_question: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub conflict_axis: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct WorldNewspaperConflictAxis { - #[schemars(length(min = 1, max = 160))] - pub first_party: String, - #[schemars(length(min = 1, max = 160))] - pub first_party_citation: String, - #[schemars(length(min = 1, max = 500))] - pub first_party_move: String, - #[schemars(length(min = 1, max = 160))] - pub opposing_party: String, - #[schemars(length(min = 1, max = 160))] - pub opposing_party_citation: String, - #[schemars(length(min = 1, max = 500))] - pub opposing_party_move: String, - #[schemars(length(min = 1, max = 500))] - pub conflict: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(deny_unknown_fields)] -struct NarrativeSelectionAction { - command: NarrativeSelectionCommand, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(tag = "tool", rename_all = "snake_case", deny_unknown_fields)] -enum NarrativeSelectionCommand { - QueryPublicRecords { - #[schemars(length(max = 6))] - terms: Vec, - match_terms: PublicRecordTermMatch, - #[schemars(length(max = 6))] - entity_names: Vec, - #[schemars(length(max = 5))] - assertion_statuses: Vec, - #[schemars(length(max = 6))] - channels: Vec, - order: PublicRecordOrder, - cursor: Option, - #[schemars(range(min = 1, max = 24))] - limit: u8, - }, - FetchPublicRecords { - #[schemars(length(min = 1, max = 24))] - record_ids: Vec, - }, - ProposeAgenda { - issue_shape: WorldNewspaperIssueShape, - #[schemars(length(min = 1, max = 500))] - issue_shape_rationale: String, - #[schemars(length(min = 1, max = 500))] - dominant_throughline: String, - #[schemars(length(min = 1, max = 500))] - reader_stake: String, - #[schemars(length(min = 1, max = 6))] - story_pitches: Vec, - }, - CommitAgenda { - #[schemars(length(min = 71, max = 71))] - candidate_digest: String, - }, -} - -#[derive( - Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, -)] -#[serde(rename_all = "snake_case")] -enum PublicRecordTermMatch { - Any, - All, -} - -#[derive( - Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, -)] -#[serde(rename_all = "snake_case")] -enum PublicRecordOrder { - Newest, - Oldest, -} - -#[derive(Clone, Debug, Serialize, PartialEq, Eq, PartialOrd, Ord)] -struct PublicRecordQuery { - terms: Vec, - match_terms: PublicRecordTermMatch, - entity_names: Vec, - assertion_statuses: Vec, - channels: Vec, - order: PublicRecordOrder, - cursor: Option, - limit: u8, -} - -#[derive(Clone, Debug, Serialize, PartialEq, Eq)] -#[serde(tag = "kind", rename_all = "snake_case")] -enum NarrativeSelectionFinding { - AgendaRejected { - reason: String, - }, - QueryRejected { - reason: String, - }, - QueryResult { - records: Vec, - next_cursor: Option, - }, - AgendaProposed { - candidate_digest: String, - issue_shape: WorldNewspaperIssueShape, - issue_shape_rationale: String, - front_page: EditorialPitchProof, - below_fold: Vec, - review_questions: Vec, - }, -} - -#[derive(Clone, Debug, Serialize, PartialEq, Eq)] -struct EditorialPitchProof { - page_position: String, - journalist_id: String, - narrative_function: WorldNewspaperNarrativeFunction, - context_role: WorldNewspaperContextRole, - assignment_reason: String, - narrative_claim: String, - tension: String, - public_question: String, - focus_record: PublicRecordProjection, - supporting_records: Vec, -} - -#[derive(Clone, Debug, Serialize, PartialEq, Eq)] -struct EditorialSupportingRecord { - record_id: String, - at: DateTime, - headline: String, -} - -#[derive(Clone, Debug, Serialize, PartialEq, Eq)] -struct EditorialRecordIndexEntry { - record_id: String, - at: DateTime, - channel: String, - headline: String, - named_entities: Vec, -} - -#[derive(Clone, Debug, Serialize, PartialEq, Eq)] -struct EditorialPeriodDirectoryEntry { - at: DateTime, - completed_change_headlines: Vec, - completed_change_count: usize, - other_record_count: usize, -} - -#[derive(Clone, Debug, Serialize)] -struct AssignmentJournalistProfile<'a> { - id: &'a str, - name: &'a str, - byline: &'a str, - beat: &'a str, - biases: &'a [String], - preferences: &'a [String], - voice_signature: &'a str, - source_instincts: &'a [String], - blind_spots: &'a [String], -} - -fn assignment_journalist_profile( - journalist: &WorldNewspaperJournalist, -) -> AssignmentJournalistProfile<'_> { - AssignmentJournalistProfile { - id: &journalist.staff.id, - name: &journalist.staff.name, - byline: &journalist.byline, - beat: &journalist.beat, - biases: &journalist.staff.biases, - preferences: &journalist.staff.preferences, - voice_signature: &journalist.voice, - source_instincts: &journalist.source_instincts, - blind_spots: &journalist.blind_spots, - } -} - -#[derive(Clone, Debug, Serialize, PartialEq, Eq)] -struct NarrativeSelectionContextSnapshot { - inspected_record_count: usize, - completed_query_count: usize, - inspected_records: Vec, - pending_agenda_token: Option, -} - -struct NarrativeSelectionWorkbench<'a> { - records: &'a [PublicRecordProjection], - newsroom: &'a WorldNewspaperNewsroom, - max_articles: usize, - visible_record_ids: BTreeSet, - completed_queries: BTreeSet, - pending_agenda: Option<(String, WorldNewspaperEditorialAgenda)>, -} - -impl NarrativeSelectionWorkbench<'_> { - fn query(&mut self, mut query: PublicRecordQuery) -> Result { - normalize_query_terms(&mut query.terms, "query term")?; - normalize_query_terms(&mut query.entity_names, "query entity")?; - query.channels.sort(); - query.channels.dedup(); - query.assertion_statuses.sort(); - query.assertion_statuses.dedup(); - if !(1..=MAX_PUBLIC_RECORD_QUERY_RESULTS).contains(&usize::from(query.limit)) { - return Err(anyhow!( - "public-record query limit is outside the bounded response" - )); - } - if query - .channels - .iter() - .any(|channel| !self.records.iter().any(|record| &record.channel == channel)) - { - return Err(anyhow!("public-record query names an unknown channel")); - } - if query - .cursor - .as_ref() - .is_some_and(|cursor| !self.visible_record_ids.contains(cursor)) - { - return Err(anyhow!( - "public-record query cursor was not previously inspected" - )); - } - if !self.completed_queries.insert(query.clone()) { - return Err(anyhow!( - "public-record query exactly repeats an earlier query" - )); - } - - let ordered = match query.order { - PublicRecordOrder::Newest => self.records.iter().collect::>(), - PublicRecordOrder::Oldest => self.records.iter().rev().collect::>(), - }; - let start = query.cursor.as_ref().map_or(0, |cursor| { - ordered - .iter() - .position(|record| &record.record_id == cursor) - .map_or(ordered.len(), |index| index.saturating_add(1)) - }); - let matching = ordered - .into_iter() - .skip(start) - .filter(|record| public_record_matches(record, &query)) - .collect::>(); - let limit = usize::from(query.limit); - let records = matching - .iter() - .take(limit) - .map(|record| (*record).clone()) - .collect::>(); - self.visible_record_ids - .extend(records.iter().map(|record| record.record_id.clone())); - self.pending_agenda = None; - let next_cursor = (matching.len() > records.len()) - .then(|| records.last().map(|record| record.record_id.clone())) - .flatten(); - Ok(NarrativeSelectionFinding::QueryResult { - records, - next_cursor, - }) - } - - fn fetch_records(&mut self, mut record_ids: Vec) -> Result { - for record_id in &mut record_ids { - *record_id = record_id.trim().to_owned(); - if record_id.is_empty() - || record_id.chars().count() > 240 - || record_id.chars().any(char::is_control) - { - return Err(anyhow!("public record ID is malformed")); - } - } - record_ids.sort(); - record_ids.dedup(); - if record_ids.is_empty() || record_ids.len() > MAX_PUBLIC_RECORD_QUERY_RESULTS { - return Err(anyhow!( - "exact public-record fetch is outside the bounded response" - )); - } - let known = self - .records - .iter() - .map(|record| (record.record_id.as_str(), record)) - .collect::>(); - let records = record_ids - .iter() - .map(|record_id| { - known - .get(record_id.as_str()) - .map(|record| (*record).clone()) - .ok_or_else(|| { - anyhow!("exact public-record fetch names unknown record {record_id}") - }) - }) - .collect::>>()?; - self.visible_record_ids - .extend(records.iter().map(|record| record.record_id.clone())); - self.pending_agenda = None; - Ok(NarrativeSelectionFinding::QueryResult { - records, - next_cursor: None, - }) - } - - fn context(&self) -> NarrativeSelectionContextSnapshot { - let inspected_records = self - .records - .iter() - .filter(|record| self.visible_record_ids.contains(&record.record_id)) - .map(|record| { - let named_entities = record - .facts - .iter() - .flat_map(|fact| { - fact.named_people - .iter() - .map(|person| person.name.clone()) - .chain(fact.institutions.iter().cloned()) - .chain(fact.populations.iter().cloned()) - .chain(fact.places.iter().cloned()) - }) - .collect::>() - .into_iter() - .collect(); - EditorialRecordIndexEntry { - record_id: record.record_id.clone(), - at: record.at, - channel: record.channel.clone(), - headline: record.headline.clone(), - named_entities, - } - }) - .collect(); - NarrativeSelectionContextSnapshot { - inspected_record_count: self.visible_record_ids.len(), - completed_query_count: self.completed_queries.len(), - inspected_records, - pending_agenda_token: self - .pending_agenda - .as_ref() - .map(|(digest, _)| digest.clone()), - } - } - - fn propose_agenda( - &mut self, - agenda: WorldNewspaperEditorialAgenda, - ) -> Result { - let uninspected_record = agenda - .story_pitches - .iter() - .flat_map(|pitch| &pitch.citations) - .find(|record_id| !self.visible_record_ids.contains(*record_id)); - if let Some(record_id) = uninspected_record { - return Err(anyhow!( - "agenda cites public record {record_id} without querying it" - )); - } - validate_editorial_agenda(self.records, self.newsroom, &agenda, self.max_articles)?; - let candidate_digest = editorial_agenda_candidate_digest(&agenda)?; - let mut pitches = agenda - .story_pitches - .iter() - .enumerate() - .map(|(index, pitch)| self.pitch_proof(index, pitch)) - .collect::>>()?; - let front_page = pitches.remove(0); - self.pending_agenda = Some((candidate_digest.clone(), agenda)); - let pending = self - .pending_agenda - .as_ref() - .map(|(_, agenda)| agenda) - .ok_or_else(|| anyhow!("agenda proposal was not retained"))?; - Ok(NarrativeSelectionFinding::AgendaProposed { - candidate_digest, - issue_shape: pending.issue_shape, - issue_shape_rationale: pending.issue_shape_rationale.clone(), - front_page, - below_fold: pitches, - review_questions: vec![ - "Compare the lead focus fact with every below-fold focus fact. Would a reader reasonably call another story more vivid, consequential, scandalous, or urgent? If so, propose a revised agenda rather than committing this one." - .into(), - "Does each continuing story foreground the incident and then identify what changed, or has routine handling displaced the thing readers actually care about?" - .into(), - "Do the pitches expose people or institutions in conflict and make public or material stakes legible, or do they mainly explain what records do not prove? Query for missing opposition, countermoves, reaction, or lived cost when the ledger may contain them." - .into(), - "If this is a special issue, does only the lead own the shared chronology while every other story performs a distinct consequence, accountability, opposition, or counter-narrative function? If this is a general issue, did an exciting record improperly swallow independent beats?" - .into(), - "Would each reporter plausibly pursue this assignment because of the named beat, biases, source instincts, and blind spots, or are the bylines interchangeable?" - .into(), - ], - }) - } - - fn pitch_proof( - &self, - index: usize, - pitch: &WorldNewspaperStoryPitch, - ) -> Result { - let focus_record = self - .records - .iter() - .find(|record| record.record_id == pitch.focus_citation) - .cloned() - .ok_or_else(|| anyhow!("agenda focus record is absent from the public ledger"))?; - let supporting_records = pitch - .citations - .iter() - .filter(|record_id| **record_id != pitch.focus_citation) - .map(|record_id| { - let record = self - .records - .iter() - .find(|record| &record.record_id == record_id) - .ok_or_else(|| { - anyhow!("agenda supporting record is absent from the public ledger") - })?; - Ok(EditorialSupportingRecord { - record_id: record.record_id.clone(), - at: record.at, - headline: record.headline.clone(), - }) - }) - .collect::>>()?; - Ok(EditorialPitchProof { - page_position: if index == 0 { - "front_page_lead".into() - } else { - format!("inside_article_{}", index + 1) - }, - journalist_id: pitch.journalist_id.clone(), - narrative_function: pitch.narrative_function, - context_role: pitch.context_role, - assignment_reason: pitch.assignment_reason.clone(), - narrative_claim: pitch.narrative_claim.clone(), - tension: pitch.tension.clone(), - public_question: pitch.public_question.clone(), - focus_record, - supporting_records, - }) - } -} - -fn editorial_agenda_candidate_digest(agenda: &WorldNewspaperEditorialAgenda) -> Result { - Ok(format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(agenda)?) - )) -} - -fn normalize_query_terms(values: &mut Vec, label: &str) -> Result<()> { - for value in values.iter_mut() { - *value = value.trim().to_owned(); - if value.is_empty() || value.chars().count() > 80 || value.chars().any(char::is_control) { - return Err(anyhow!("{label} is malformed")); - } - } - values.sort_by_key(|value| value.to_lowercase()); - values.dedup_by(|left, right| left.eq_ignore_ascii_case(right)); - Ok(()) -} - -fn public_record_matches(record: &PublicRecordProjection, query: &PublicRecordQuery) -> bool { - if !query.channels.is_empty() && !query.channels.contains(&record.channel) { - return false; - } - if !query.assertion_statuses.is_empty() - && !record - .facts - .iter() - .any(|fact| query.assertion_statuses.contains(&fact.assertion_status)) - { - return false; - } - let entity_names = record - .facts - .iter() - .flat_map(|fact| { - fact.named_people - .iter() - .map(|person| person.name.as_str()) - .chain(fact.institutions.iter().map(String::as_str)) - .chain(fact.populations.iter().map(String::as_str)) - .chain(fact.places.iter().map(String::as_str)) - }) - .collect::>(); - if !query.entity_names.is_empty() - && !query.entity_names.iter().any(|expected| { - entity_names - .iter() - .any(|actual| actual.eq_ignore_ascii_case(expected)) - }) - { - return false; - } - if query.terms.is_empty() { - return true; - } - let searchable = std::iter::once(record.headline.as_str()) - .chain(std::iter::once(record.channel.as_str())) - .chain(std::iter::once(record.reliability.as_str())) - .chain(record.facts.iter().map(|fact| fact.account.as_str())) - .chain(entity_names) - .collect::>() - .join("\n") - .to_lowercase(); - match query.match_terms { - PublicRecordTermMatch::Any => query - .terms - .iter() - .any(|term| searchable.contains(&term.to_lowercase())), - PublicRecordTermMatch::All => query - .terms - .iter() - .all(|term| searchable.contains(&term.to_lowercase())), - } -} - -#[async_trait] -impl ModelAgentTool for NarrativeSelectionWorkbench<'_> { - type Action = NarrativeSelectionAction; - type Output = WorldNewspaperEditorialAgenda; - type Finding = NarrativeSelectionFinding; - - fn action_schema(&self) -> std::result::Result { - let story_budget = self.max_articles; - let journalist_ids = self - .newsroom - .journalists - .iter() - .map(|journalist| journalist.staff.id.clone()) - .collect::>(); - let propose_schema = serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":[ - "tool", - "issue_shape", - "issue_shape_rationale", - "dominant_throughline", - "reader_stake", - "story_pitches" - ], - "properties":{ - "tool":{"const":"propose_agenda"}, - "issue_shape":{"type":"string","enum":["special_issue","general_issue"]}, - "issue_shape_rationale":{"type":"string","minLength":1,"maxLength":500}, - "dominant_throughline":{"type":"string","minLength":1,"maxLength":500}, - "reader_stake":{"type":"string","minLength":1,"maxLength":500}, - "story_pitches":{ - "type":"array", - "minItems":1, - "maxItems":story_budget, - "items":{ - "type":"object", - "additionalProperties":false, - "required":[ - "lead", - "section", - "journalist_id", - "narrative_function", - "context_role", - "assignment_reason", - "citations", - "focus_citation", - "narrative_claim", - "tension", - "public_question", - "conflict_axis" - ], - "properties":{ - "lead":{"type":"boolean"}, - "section":{"type":"string","enum":ALLOWED_SECTIONS}, - "journalist_id":{"type":"string","enum":journalist_ids}, - "narrative_function":{"type":"string","enum":[ - "lead_chronology","consequence","accountability", - "opposition","counter_narrative","independent_beat" - ]}, - "context_role":{"type":"string","enum":[ - "owns_issue_chronology","assumes_issue_chronology","self_contained" - ]}, - "assignment_reason":{"type":"string","minLength":1,"maxLength":500}, - "citations":{ - "type":"array", - "minItems":1, - "uniqueItems":true, - "items":{"type":"string","minLength":1,"maxLength":240} - }, - "focus_citation":{"type":"string","minLength":1,"maxLength":240}, - "narrative_claim":{"type":"string","minLength":1,"maxLength":500}, - "tension":{"type":"string","minLength":1,"maxLength":500}, - "public_question":{"type":"string","minLength":1,"maxLength":500} - ,"conflict_axis":{ - "oneOf":[ - {"type":"null"}, - { - "type":"object", - "additionalProperties":false, - "required":["first_party","first_party_citation","first_party_move","opposing_party","opposing_party_citation","opposing_party_move","conflict"], - "properties":{ - "first_party":{"type":"string","minLength":1,"maxLength":160}, - "first_party_citation":{"type":"string","minLength":1,"maxLength":160}, - "first_party_move":{"type":"string","minLength":1,"maxLength":500}, - "opposing_party":{"type":"string","minLength":1,"maxLength":160}, - "opposing_party_citation":{"type":"string","minLength":1,"maxLength":160}, - "opposing_party_move":{"type":"string","minLength":1,"maxLength":500}, - "conflict":{"type":"string","minLength":1,"maxLength":500} - } - } - ] - } - } - } - } - } - }); - let cursor_schema = serde_json::json!({"anyOf":[ - {"type":"string","minLength":1,"maxLength":240}, - {"type":"null"} - ]}); - let assertion_status_schema = - serde_json::to_value(schema_for!(WorldNewspaperAssertionStatus)) - .map_err(|error| error.to_string())?; - let assertion_statuses = assertion_status_schema - .get("enum") - .cloned() - .ok_or_else(|| "public assertion status schema omitted its enum".to_owned())?; - let query_schema = serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":[ - "tool","terms","match_terms","entity_names", - "assertion_statuses","channels","order","cursor","limit" - ], - "properties":{ - "tool":{"const":"query_public_records"}, - "terms":{"type":"array","maxItems":6,"uniqueItems":true, - "items":{"type":"string","minLength":1,"maxLength":80}}, - "match_terms":{"type":"string","enum":["any","all"]}, - "entity_names":{"type":"array","maxItems":6,"uniqueItems":true, - "items":{"type":"string","minLength":1,"maxLength":80}}, - "assertion_statuses":{"type":"array","maxItems":5,"uniqueItems":true, - "items":{"type":"string","enum":assertion_statuses}}, - "channels":{"type":"array","maxItems":6,"uniqueItems":true, - "items":{"type":"string","minLength":1,"maxLength":240}}, - "order":{"type":"string","enum":["newest","oldest"]}, - "cursor":cursor_schema, - "limit":{"type":"integer","minimum":1,"maximum":MAX_PUBLIC_RECORD_QUERY_RESULTS} - } - }); - let commands = vec![ - query_schema, - serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["tool","record_ids"], - "properties":{ - "tool":{"const":"fetch_public_records"}, - "record_ids":{ - "type":"array", - "minItems":1, - "maxItems":MAX_PUBLIC_RECORD_QUERY_RESULTS, - "uniqueItems":true, - "items":{"type":"string","minLength":1,"maxLength":240} - } - } - }), - propose_schema, - serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["tool","candidate_digest"], - "properties":{ - "tool":{"const":"commit_agenda"}, - "candidate_digest":{"type":"string","minLength":71,"maxLength":71} - } - }), - ]; - let command_schema = serde_json::json!({"oneOf":commands}); - let mut schema = serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["command"], - "properties":{"command":command_schema} - }); - crate::model_connector::project_strict_responses_schema(&mut schema) - .map_err(|error| error.to_string())?; - Ok(schema) - } - - fn context_snapshot(&self) -> Option { - serde_json::to_value(self.context()).ok() - } - - async fn invoke( - &mut self, - action: Self::Action, - _context: &ModelAgentToolContext, - ) -> ModelAgentToolOutcome { - match action.command { - NarrativeSelectionCommand::QueryPublicRecords { - terms, - match_terms, - entity_names, - assertion_statuses, - channels, - order, - cursor, - limit, - } => match self.query(PublicRecordQuery { - terms, - match_terms, - entity_names, - assertion_statuses, - channels, - order, - cursor, - limit, - }) { - Ok(observation) => ModelAgentToolOutcome::Continue { - observation, - receipts: Vec::new(), - }, - Err(error) => ModelAgentToolOutcome::Rejected { - finding: NarrativeSelectionFinding::QueryRejected { - reason: error.to_string().chars().take(500).collect(), - }, - receipts: Vec::new(), - }, - }, - NarrativeSelectionCommand::FetchPublicRecords { record_ids } => { - match self.fetch_records(record_ids) { - Ok(observation) => ModelAgentToolOutcome::Continue { - observation, - receipts: Vec::new(), - }, - Err(error) => ModelAgentToolOutcome::Rejected { - finding: NarrativeSelectionFinding::QueryRejected { - reason: error.to_string().chars().take(500).collect(), - }, - receipts: Vec::new(), - }, - } - } - NarrativeSelectionCommand::ProposeAgenda { - issue_shape, - issue_shape_rationale, - dominant_throughline, - reader_stake, - story_pitches, - } => { - let agenda = WorldNewspaperEditorialAgenda { - issue_shape, - issue_shape_rationale, - dominant_throughline, - reader_stake, - story_pitches, - }; - match self.propose_agenda(agenda) { - Ok(observation) => ModelAgentToolOutcome::Continue { - observation, - receipts: Vec::new(), - }, - Err(error) => ModelAgentToolOutcome::Rejected { - finding: NarrativeSelectionFinding::AgendaRejected { - reason: error.to_string().chars().take(500).collect(), - }, - receipts: Vec::new(), - }, - } - } - NarrativeSelectionCommand::CommitAgenda { candidate_digest } => { - match &self.pending_agenda { - Some((expected_digest, agenda)) if &candidate_digest == expected_digest => { - ModelAgentToolOutcome::Accepted { - output: agenda.clone(), - receipts: Vec::new(), - } - } - Some((expected_digest, _)) => ModelAgentToolOutcome::Rejected { - finding: NarrativeSelectionFinding::AgendaRejected { - reason: format!( - "agenda commit names stale candidate {candidate_digest}; current candidate is {expected_digest}" - ), - }, - receipts: Vec::new(), - }, - None => ModelAgentToolOutcome::Rejected { - finding: NarrativeSelectionFinding::AgendaRejected { - reason: "agenda commit requires one reviewed proposal".into(), - }, - receipts: Vec::new(), - }, - } - } - } - } -} - -fn validate_editorial_frame(value: &str, label: &str) -> Result<()> { - if value.trim().is_empty() - || value.trim() != value - || value.chars().count() > 500 - || value.chars().any(char::is_control) - || value.contains(['\r', '\n', '`']) - { - return Err(anyhow!("{label} is not a bounded editorial frame")); - } - Ok(()) -} - -fn validate_staff_member(member: &WorldNewspaperStaffMember, label: &str) -> Result<()> { - validate_single_line(&member.id, 80, &format!("{label} ID"))?; - validate_single_line(&member.name, 80, &format!("{label} name"))?; - validate_editorial_frame(&member.character, &format!("{label} character"))?; - if member.biases.is_empty() - || member.biases.len() > 6 - || member.preferences.is_empty() - || member.preferences.len() > 6 - { - return Err(anyhow!("{label} has an invalid disposition")); - } - for bias in &member.biases { - validate_editorial_frame(bias, &format!("{label} bias"))?; - } - for preference in &member.preferences { - validate_editorial_frame(preference, &format!("{label} preference"))?; - } - Ok(()) -} - -fn validate_newsroom(newsroom: &WorldNewspaperNewsroom) -> Result<()> { - if newsroom.journalists.is_empty() || newsroom.journalists.len() > MAX_FRONT_PAGE_ARTICLES { - return Err(anyhow!("newsroom must employ one to six journalists")); - } - validate_staff_member(&newsroom.assignment_editor, "assignment editor")?; - validate_staff_member(&newsroom.copy_editor, "copy editor")?; - validate_staff_member(&newsroom.night_editor, "Night Editor")?; - let mut staff_ids = BTreeSet::from([ - newsroom.assignment_editor.id.as_str(), - newsroom.copy_editor.id.as_str(), - newsroom.night_editor.id.as_str(), - ]); - let mut staff_names = BTreeSet::from([ - newsroom.assignment_editor.name.as_str(), - newsroom.copy_editor.name.as_str(), - newsroom.night_editor.name.as_str(), - ]); - if staff_ids.len() != 3 || staff_names.len() != 3 { - return Err(anyhow!("newsroom staff identities must be unique")); - } - let mut bylines = BTreeSet::new(); - for journalist in &newsroom.journalists { - validate_staff_member(&journalist.staff, "journalist")?; - validate_single_line(&journalist.byline, 60, "journalist byline")?; - validate_single_line(&journalist.beat, 160, "journalist beat")?; - validate_editorial_frame(&journalist.voice, "journalist voice")?; - if journalist.source_instincts.is_empty() - || journalist.source_instincts.len() > 4 - || journalist.blind_spots.is_empty() - || journalist.blind_spots.len() > 3 - { - return Err(anyhow!( - "journalist source instincts and blind spots must stay bounded" - )); - } - for instinct in &journalist.source_instincts { - validate_editorial_frame(instinct, "journalist source instinct")?; - } - for blind_spot in &journalist.blind_spots { - validate_editorial_frame(blind_spot, "journalist blind spot")?; - } - if !staff_ids.insert(&journalist.staff.id) - || !staff_names.insert(&journalist.staff.name) - || !bylines.insert(journalist.byline.as_str()) - { - return Err(anyhow!( - "newsroom staff identities and bylines must be unique" - )); - } - } - Ok(()) -} - -fn journalist_by_id<'a>( - newsroom: &'a WorldNewspaperNewsroom, - journalist_id: &str, -) -> Result<&'a WorldNewspaperJournalist> { - newsroom - .journalists - .iter() - .find(|journalist| journalist.staff.id == journalist_id) - .ok_or_else(|| anyhow!("editorial pitch assigned an unknown journalist {journalist_id}")) -} - -fn selected_record_ids<'a>(record_ids: &'a [String], label: &str) -> Result> { - if record_ids.is_empty() { - return Err(anyhow!("{label} selected no public record")); - } - let selected = record_ids - .iter() - .map(String::as_str) - .collect::>(); - if selected.len() != record_ids.len() { - return Err(anyhow!("{label} repeats a public record ID")); - } - Ok(selected) -} - -fn validate_editorial_agenda( - records: &[PublicRecordProjection], - newsroom: &WorldNewspaperNewsroom, - agenda: &WorldNewspaperEditorialAgenda, - max_articles: usize, -) -> Result<()> { - let legacy_agenda = agenda.issue_shape_rationale.is_empty(); - if !legacy_agenda { - validate_editorial_frame(&agenda.issue_shape_rationale, "issue-shape rationale")?; - } - validate_editorial_frame(&agenda.dominant_throughline, "dominant throughline")?; - validate_editorial_frame(&agenda.reader_stake, "reader stake")?; - if agenda.story_pitches.is_empty() - || agenda.story_pitches.len() > max_articles.min(records.len()) - { - return Err(anyhow!("editorial agenda exceeded its story budget")); - } - let known_sources = records - .iter() - .map(|record| record.record_id.as_str()) - .collect::>(); - for (index, pitch) in agenda.story_pitches.iter().enumerate() { - if pitch.lead != (index == 0) { - return Err(anyhow!( - "editorial agenda must designate exactly its first pitch as lead" - )); - } - if (index == 0 && pitch.section != "Front Page") - || (index > 0 && pitch.section == "Front Page") - || !ALLOWED_SECTIONS.contains(&pitch.section.as_str()) - { - return Err(anyhow!("editorial pitch {index} chose an invalid section")); - } - journalist_by_id(newsroom, &pitch.journalist_id)?; - if !legacy_agenda { - validate_editorial_frame(&pitch.assignment_reason, "journalist assignment reason")?; - match agenda.issue_shape { - WorldNewspaperIssueShape::SpecialIssue => { - if (index == 0 - && (pitch.context_role != WorldNewspaperContextRole::OwnsIssueChronology - || pitch.narrative_function - != WorldNewspaperNarrativeFunction::LeadChronology)) - || (index > 0 - && pitch.context_role == WorldNewspaperContextRole::OwnsIssueChronology) - { - return Err(anyhow!( - "special issue must give only its lead ownership of the shared chronology" - )); - } - } - WorldNewspaperIssueShape::GeneralIssue => { - if pitch.context_role != WorldNewspaperContextRole::SelfContained { - return Err(anyhow!( - "general-issue stories must own only their independent context" - )); - } - } - } - } - let selected = selected_record_ids(&pitch.citations, &format!("editorial pitch {index}"))?; - if !selected.contains(pitch.focus_citation.as_str()) { - return Err(anyhow!( - "editorial pitch {index} focus record is not in its selected record set" - )); - } - for citation in &pitch.citations { - if !known_sources.contains(citation.as_str()) { - return Err(anyhow!( - "editorial pitch {index} cites unknown public record {citation}" - )); - } - } - validate_editorial_frame(&pitch.narrative_claim, "story narrative claim")?; - validate_editorial_frame(&pitch.tension, "story tension")?; - validate_editorial_frame(&pitch.public_question, "public question")?; - if matches!( - pitch.narrative_function, - WorldNewspaperNarrativeFunction::Accountability - | WorldNewspaperNarrativeFunction::Opposition - | WorldNewspaperNarrativeFunction::CounterNarrative - ) && pitch.conflict_axis.is_none() - { - return Err(anyhow!( - "editorial pitch {index} declares adversarial work without binding two cited parties" - )); - } - if let Some(axis) = &pitch.conflict_axis { - validate_editorial_frame(&axis.first_party, "conflict first party")?; - validate_editorial_frame(&axis.opposing_party, "conflict opposing party")?; - validate_editorial_frame(&axis.first_party_move, "conflict first move")?; - validate_editorial_frame(&axis.opposing_party_move, "conflict opposing move")?; - validate_editorial_frame(&axis.conflict, "conflict axis")?; - if axis.first_party == axis.opposing_party { - return Err(anyhow!( - "editorial pitch {index} binds the same party to both sides" - )); - } - if axis.first_party_citation == axis.opposing_party_citation { - return Err(anyhow!( - "editorial pitch {index} binds both sides to the same public move" - )); - } - for (party, citation, label) in [ - (&axis.first_party, &axis.first_party_citation, "first"), - ( - &axis.opposing_party, - &axis.opposing_party_citation, - "opposing", - ), - ] { - if !selected.contains(citation.as_str()) { - return Err(anyhow!( - "editorial pitch {index} {label} party citation is not selected" - )); - } - let record = records - .iter() - .find(|record| record.record_id == *citation) - .ok_or_else(|| anyhow!("conflict citation is absent from the ledger"))?; - let named = record.facts.iter().any(|fact| { - fact.named_people.iter().any(|person| person.name == *party) - || fact.institutions.iter().any(|name| name == party) - || fact.populations.iter().any(|name| name == party) - }); - if !named { - return Err(anyhow!( - "editorial pitch {index} {label} party is not named by its citation" - )); - } - } - } - } - Ok(()) -} - -fn validate_editorial_alignment( - draft: &EditorialPageDraft, - newsroom: &WorldNewspaperNewsroom, - agenda: &WorldNewspaperEditorialAgenda, -) -> Result<()> { - if draft.articles.len() != agenda.story_pitches.len() { - return Err(anyhow!( - "editorial page does not implement the admitted story selection" - )); - } - for (index, (article, pitch)) in draft.articles.iter().zip(&agenda.story_pitches).enumerate() { - let article_citations = article.citations.iter().collect::>(); - let pitch_citations = pitch.citations.iter().collect::>(); - if article_citations != pitch_citations { - return Err(anyhow!( - "article {index} does not implement its admitted citation grouping" - )); - } - let journalist = journalist_by_id(newsroom, &pitch.journalist_id)?; - if article.section != pitch.section || article.byline != journalist.byline { - return Err(anyhow!( - "article {index} changed its assigned section or journalist" - )); - } - } - Ok(()) -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct EditorialPageDraft { - #[schemars(length(min = 1, max = 6))] - articles: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct EditorialArticleDraft { - #[schemars(length(min = 1, max = 30))] - section: String, - #[schemars(length(min = 1, max = 100))] - headline: String, - #[schemars(length(min = 1, max = 220))] - deck: String, - #[schemars(length(min = 1, max = 60))] - byline: String, - #[schemars(length(max = 100))] - dateline: String, - #[schemars(length(min = 1))] - citations: Vec, - #[schemars(length(min = 2, max = 5))] - paragraphs: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(tag = "tool", rename_all = "snake_case", deny_unknown_fields)] -enum JournalistAction { - FileStory { - #[schemars(length(min = 1, max = 100))] - headline: String, - #[schemars(length(min = 1, max = 220))] - deck: String, - #[schemars(length(max = 100))] - dateline: String, - #[schemars(length(min = 2, max = 5))] - paragraphs: Vec, - }, -} - -#[derive(Clone, Debug, Serialize, PartialEq, Eq)] -#[serde(tag = "kind", rename_all = "snake_case")] -enum JournalistFinding { - StoryRejected { reason: String }, -} - -struct JournalistWorkbench<'a> { - records: &'a [PublicRecordProjection], - article_index: usize, - byline: &'a str, - issue_shape: WorldNewspaperIssueShape, - issue_shape_rationale: &'a str, - dominant_throughline: &'a str, - reader_stake: &'a str, - pitch: &'a WorldNewspaperStoryPitch, -} - -impl JournalistWorkbench<'_> { - fn selected_records(&self) -> Vec<&PublicRecordProjection> { - let selected = self - .pitch - .citations - .iter() - .cloned() - .collect::>(); - public_records_for_ids(self.records, &selected) - } - - fn assignment_snapshot(&self) -> serde_json::Value { - let records = self.selected_records(); - let allowed_datelines = records - .iter() - .flat_map(|record| &record.facts) - .flat_map(|fact| &fact.places) - .cloned() - .collect::>(); - serde_json::json!({ - "issue_shape": self.issue_shape, - "issue_shape_rationale": self.issue_shape_rationale, - "dominant_throughline": self.dominant_throughline, - "reader_stake": self.reader_stake, - "pitch": self.pitch, - "allowed_datelines": allowed_datelines, - "records": records, - }) - } -} - -#[async_trait] -impl ModelAgentTool for JournalistWorkbench<'_> { - type Action = JournalistAction; - type Output = EditorialArticleDraft; - type Finding = JournalistFinding; - - fn action_schema(&self) -> std::result::Result { - let mut schema = serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["tool","headline","deck","dateline","paragraphs"], - "properties":{ - "tool":{"const":"file_story"}, - "headline":{"type":"string","minLength":1,"maxLength":100}, - "deck":{"type":"string","minLength":1,"maxLength":220}, - "dateline":{"type":"string","maxLength":100}, - "paragraphs":{ - "type":"array", - "minItems":2, - "maxItems":5, - "items":{"type":"string"} - } - } - }); - crate::model_connector::project_strict_responses_schema(&mut schema) - .map_err(|error| error.to_string())?; - Ok(schema) - } - - fn context_snapshot(&self) -> Option { - Some(self.assignment_snapshot()) - } - - fn initial_context_snapshot(&self) -> Option { - Some(self.assignment_snapshot()) - } - - async fn invoke( - &mut self, - action: Self::Action, - _context: &ModelAgentToolContext, - ) -> ModelAgentToolOutcome { - let JournalistAction::FileStory { - headline, - deck, - dateline, - paragraphs, - } = action; - let article = EditorialArticleDraft { - section: self.pitch.section.clone(), - headline, - deck, - byline: self.byline.into(), - dateline, - citations: self.pitch.citations.clone(), - paragraphs, - }; - match validate_editorial_article(self.records, &article, self.article_index) { - Ok(()) => ModelAgentToolOutcome::Accepted { - output: article, - receipts: Vec::new(), - }, - Err(error) => ModelAgentToolOutcome::Rejected { - finding: JournalistFinding::StoryRejected { - reason: error.to_string().chars().take(500).collect(), - }, - receipts: Vec::new(), - }, - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(tag = "tool", rename_all = "snake_case", deny_unknown_fields)] -enum NightEditorCloseAction { - SubmitClose { - #[schemars(length(max = 24))] - addressed_query_indices: Vec, - #[schemars(length(max = 6))] - rewrites: Vec, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(deny_unknown_fields)] -struct NightEditorArticleClose { - article_index: u16, - #[schemars(length(min = 1, max = 100))] - headline: String, - #[schemars(length(min = 1, max = 220))] - deck: String, - #[schemars(length(max = 100))] - dateline: String, - #[schemars(length(min = 2, max = 5))] - paragraphs: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(tag = "kind", rename_all = "snake_case")] -enum NightEditorCloseFinding { - CloseRejected { - draft: EditorialPageDraft, - copy_desk: WorldNewspaperCopyDeskReport, - reason: String, - }, -} - -fn night_editor_close_finding( - draft: EditorialPageDraft, - copy_desk: WorldNewspaperCopyDeskReport, - reason: impl Into, -) -> NightEditorCloseFinding { - NightEditorCloseFinding::CloseRejected { - draft, - copy_desk, - reason: reason.into(), - } -} - -#[derive(Debug)] -struct NightEditorCloseOutput { - draft: EditorialPageDraft, - addressed_query_indices: Vec, - changed_article_indices: Vec, -} - -struct PreparedNewspaper { - title: String, - editorial_voice: String, - newsroom: WorldNewspaperNewsroom, - records: Vec, - source_receipt_ids: Vec, - publication_task_binding: String, - binding: String, -} - -fn prepare_newspaper( - campaign: &Campaign, - title: impl Into, - editorial_voice: impl Into, - newsroom: &WorldNewspaperNewsroom, - max_articles: usize, -) -> Result { - if !(1..=MAX_FRONT_PAGE_ARTICLES).contains(&max_articles) { - return Err(anyhow!( - "newspaper front-page article budget must be between 1 and {MAX_FRONT_PAGE_ARTICLES}" - )); - } - let title = title.into(); - if title.trim().is_empty() - || title.trim() != title - || title.chars().count() > 120 - || title.chars().any(char::is_control) - { - return Err(anyhow!("newspaper title is invalid")); - } - let editorial_voice = editorial_voice.into(); - if editorial_voice.trim().is_empty() - || editorial_voice.trim() != editorial_voice - || editorial_voice.chars().count() > 600 - { - return Err(anyhow!("newspaper editorial voice is invalid")); - } - validate_newsroom(newsroom)?; - let records = public_news_records(campaign)?; - let source_receipt_ids = records - .iter() - .map(|record| record.record_id.clone()) - .collect::>(); - let publication_task_binding = - publication_task_binding(campaign, &title, &editorial_voice, newsroom, max_articles)?; - let binding = editorial_binding( - campaign, - &title, - &editorial_voice, - newsroom, - max_articles, - &records, - )?; - Ok(PreparedNewspaper { - title, - editorial_voice, - newsroom: newsroom.clone(), - records, - source_receipt_ids, - publication_task_binding, - binding, - }) -} - -async fn select_editorial_agenda( - model: &dyn ModelPort, - prepared: &PreparedNewspaper, - max_articles: usize, -) -> std::result::Result< - crate::agent::ModelAgentRun, - crate::agent::ModelAgentFailure, -> { - let period_directory = editorial_period_directory(&prepared.records); - let assignment_staff = serde_json::json!({ - "assignment_editor": &prepared.newsroom.assignment_editor, - "journalists": prepared - .newsroom - .journalists - .iter() - .map(assignment_journalist_profile) - .collect::>(), - }); - let instructions = format!( - "You are {editor}, assignment editor of `{title}`. Investigate its frozen public ledger with query_public_records, then assign a page. An empty query browses; terms, exact entity names, status, channel, and an inspected cursor narrow or page. The workbench keeps a compact index of inspected records instead of replaying old query pages; use fetch_public_records with exact IDs when you need their full facts again. Cite only returned record IDs. Search backward when procedure hides the rupture and sideways for opposition, countermoves, reaction, scandal, lived cost, and independent beats.\n\nFirst decide the issue shape. A special issue is earned when one upheaval genuinely reorganizes several parts of public life; its lead alone owns the shared chronology and later stories assume that chronology while performing distinct narrative functions. A general issue carries independent beats whose stories are self-contained. Do not declare a special issue merely because one incident generated many records, and do not manufacture variety when the whole realm is plainly living through one rupture. State the evidence-based rationale.\n\nThe first pitch is the Front Page lead; later pitches use another allowed section. Give each pitch a narrative function and context role. Choose the staff journalist whose beat, biases, source instincts, voice, and blind spots make them the most revealingly partial observer, and state that assignment reason. Give them the exact record grouping, one focus record the lede cannot bury, a pointed narrative claim, the live tension, and the public question. Accountability, opposition, and counter-narrative assignments must also bind a conflict_axis: two distinct people, institutions, or populations, two distinct selected records showing each side's own public move or position, bounded descriptions of those moves, and the conflict the reporter should pursue. A filing delivered to a passive recipient is one move, not two; query for an actual answer, refusal, competing demand, seizure, retreat, or countermove. One cited grievance against an unnamed abstraction is not an opposing side. Consequence, profile, and independent stories may leave conflict_axis null when the ledger honestly supplies no adversarial motion. A routine update to a vivid continuing incident should cite both and say what changed. Remembering, filing, warning, and planning are context unless they themselves produce a public consequence. Editorial frames may insinuate and judge but cannot invent concrete facts. The copy editor, not you or the reporters, owns fact checking.\n\nPropose before committing. The workbench returns issue shape, reporter fit, the lead, and what it would bury; revise or query again if the proof exposes a stronger or more honest page.\n\nPUBLICATION VOICE:\n{voice}\n\nCOMPACT STAFF BOOK:\n{staff}\n\nLEDGER PERIOD DIRECTORY (navigation only; query exact records before citation):\n{directory}", - editor = prepared.newsroom.assignment_editor.name, - title = prepared.title, - voice = prepared.editorial_voice, - staff = serde_json::to_string(&assignment_staff).unwrap_or_default(), - directory = serde_json::to_string(&period_directory).unwrap_or_default(), - ); - let spec = ModelAgentSpec { - stage: "newspaper_narrative_selection_agent_action".into(), - model: MODEL_CAPABLE.into(), - snapshot_binding: prepared.binding.clone(), - instructions, - source_receipt_ids: prepared.source_receipt_ids.clone(), - temperature: Some(0.8), - max_output_tokens: Some(2_000), - max_steps: MAX_NARRATIVE_SELECTION_STEPS, - }; - let mut tool = NarrativeSelectionWorkbench { - records: &prepared.records, - newsroom: &prepared.newsroom, - max_articles, - visible_record_ids: BTreeSet::new(), - completed_queries: BTreeSet::new(), - pending_agenda: None, - }; - crate::agent::run_model_agent(model, &spec, &mut tool).await -} - -fn checkpoint_receipt_chain_digest(receipt_ids: &[String]) -> Result { - Ok(format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(receipt_ids)?) - )) -} - -fn editorial_page_digest(draft: &EditorialPageDraft) -> Result { - Ok(format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(draft)?) - )) -} - -fn production_agenda_checkpoint_id(prepared: &PreparedNewspaper) -> Result { - Ok(format!( - "newspaper-production-agenda:sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(&( - "editorial_agenda", - &prepared.publication_task_binding, - &prepared.binding, - ))?) - )) -} - -fn reporter_assignment_digest( - prepared: &PreparedNewspaper, - agenda_checkpoint_id: &str, - article_index: usize, - pitch: &WorldNewspaperStoryPitch, - journalist: &WorldNewspaperJournalist, -) -> Result { - Ok(format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(&( - &prepared.publication_task_binding, - &prepared.binding, - agenda_checkpoint_id, - article_index, - pitch, - journalist, - ))?) - )) -} - -fn production_article_checkpoint_id( - prepared: &PreparedNewspaper, - agenda_checkpoint_id: &str, - article_index: usize, - assignment_digest: &str, -) -> Result { - Ok(format!( - "newspaper-production-article:sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(&( - &prepared.publication_task_binding, - &prepared.binding, - agenda_checkpoint_id, - article_index, - assignment_digest, - ))?) - )) -} - -fn load_model_receipts( - store: &CampaignStore, - receipt_ids: &[String], - owner: &str, -) -> Result> { - receipt_ids - .iter() - .map(|receipt_id| { - store - .load::("persona_stage_receipt.v1", receipt_id)? - .map(|(_, receipt)| receipt) - .ok_or_else(|| anyhow!("{owner} lost model receipt {receipt_id}")) - }) - .collect() -} - -fn validate_production_receipts( - checkpoint: &WorldNewspaperProductionCheckpoint, - receipts: &[ModelStageReceipt], - expected_stage: &str, - expected_snapshot_binding: &str, -) -> Result<()> { - let receipt_ids = receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - if receipts.is_empty() - || receipt_ids != checkpoint.model_receipt_ids - || receipt_ids.iter().collect::>().len() != receipt_ids.len() - || checkpoint_receipt_chain_digest(&receipt_ids)? != checkpoint.receipt_chain_digest - || production_checkpoint_content_digest( - &checkpoint.publication_task_binding, - &checkpoint.editorial_binding, - &checkpoint.content, - &checkpoint.model_receipt_ids, - &checkpoint.receipt_chain_digest, - )? != checkpoint.content_digest - || receipts.iter().any(|receipt| { - receipt.stage != expected_stage || receipt.snapshot_binding != expected_snapshot_binding - }) - || receipts - .last() - .is_none_or(|receipt| receipt.validation_result != "valid") - { - return Err(anyhow!( - "newspaper production checkpoint receipt binding is invalid" - )); - } - Ok(()) -} - -fn production_checkpoint_content_digest( - publication_task_binding: &str, - editorial_binding: &str, - content: &WorldNewspaperProductionContent, - model_receipt_ids: &[String], - receipt_chain_digest: &str, -) -> Result { - Ok(format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(&( - publication_task_binding, - editorial_binding, - content, - model_receipt_ids, - receipt_chain_digest, - ))?) - )) -} - -fn persist_production_checkpoint( - store: &CampaignStore, - checkpoint: &WorldNewspaperProductionCheckpoint, - receipts: &[ModelStageReceipt], -) -> Result<()> { - store.persist_model_stage_receipts(receipts)?; - store.insert( - "world_newspaper_production_checkpoint.v1", - "ghostlight.world_newspaper_production_checkpoint.v1", - &checkpoint.id, - checkpoint, - )?; - Ok(()) -} - -fn new_agenda_checkpoint( - prepared: &PreparedNewspaper, - agenda: WorldNewspaperEditorialAgenda, - receipts: &[ModelStageReceipt], -) -> Result { - let model_receipt_ids = receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - let content = WorldNewspaperProductionContent::EditorialAgenda { - editorial_agenda: agenda, - }; - let receipt_chain_digest = checkpoint_receipt_chain_digest(&model_receipt_ids)?; - let content_digest = production_checkpoint_content_digest( - &prepared.publication_task_binding, - &prepared.binding, - &content, - &model_receipt_ids, - &receipt_chain_digest, - )?; - Ok(WorldNewspaperProductionCheckpoint { - schema: "ghostlight.world_newspaper_production_checkpoint.v1".into(), - id: production_agenda_checkpoint_id(prepared)?, - publication_task_binding: prepared.publication_task_binding.clone(), - editorial_binding: prepared.binding.clone(), - content, - receipt_chain_digest, - model_receipt_ids, - content_digest, - }) -} - -fn load_agenda_checkpoint( - store: &CampaignStore, - prepared: &PreparedNewspaper, - max_articles: usize, -) -> Result< - Option<( - String, - WorldNewspaperEditorialAgenda, - Vec, - )>, -> { - let id = production_agenda_checkpoint_id(prepared)?; - let Some((_, checkpoint)) = store.load::( - "world_newspaper_production_checkpoint.v1", - &id, - )? - else { - return Ok(None); - }; - let receipts = load_model_receipts(store, &checkpoint.model_receipt_ids, "agenda checkpoint")?; - let WorldNewspaperProductionContent::EditorialAgenda { editorial_agenda } = &checkpoint.content - else { - return Err(anyhow!( - "agenda checkpoint occupies the wrong production slot" - )); - }; - if checkpoint.schema != "ghostlight.world_newspaper_production_checkpoint.v1" - || checkpoint.id != id - || checkpoint.publication_task_binding != prepared.publication_task_binding - || checkpoint.editorial_binding != prepared.binding - { - return Err(anyhow!("newspaper agenda checkpoint identity is invalid")); - } - validate_production_receipts( - &checkpoint, - &receipts, - "newspaper_narrative_selection_agent_action", - &prepared.binding, - )?; - validate_editorial_agenda( - &prepared.records, - &prepared.newsroom, - editorial_agenda, - max_articles, - )?; - Ok(Some((id, editorial_agenda.clone(), receipts))) -} - -fn new_article_checkpoint( - prepared: &PreparedNewspaper, - agenda_checkpoint_id: &str, - article_index: usize, - pitch: &WorldNewspaperStoryPitch, - journalist: &WorldNewspaperJournalist, - article: EditorialArticleDraft, - receipts: &[ModelStageReceipt], -) -> Result { - let assignment_digest = reporter_assignment_digest( - prepared, - agenda_checkpoint_id, - article_index, - pitch, - journalist, - )?; - let model_receipt_ids = receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - let id = production_article_checkpoint_id( - prepared, - agenda_checkpoint_id, - article_index, - &assignment_digest, - )?; - let content = WorldNewspaperProductionContent::FiledArticle { - agenda_checkpoint_id: agenda_checkpoint_id.into(), - article_index: article_index - .try_into() - .map_err(|_| anyhow!("newspaper article index overflow"))?, - assignment_digest, - journalist_id: journalist.staff.id.clone(), - article, - }; - let receipt_chain_digest = checkpoint_receipt_chain_digest(&model_receipt_ids)?; - let content_digest = production_checkpoint_content_digest( - &prepared.publication_task_binding, - &prepared.binding, - &content, - &model_receipt_ids, - &receipt_chain_digest, - )?; - Ok(WorldNewspaperProductionCheckpoint { - schema: "ghostlight.world_newspaper_production_checkpoint.v1".into(), - id, - publication_task_binding: prepared.publication_task_binding.clone(), - editorial_binding: prepared.binding.clone(), - content, - receipt_chain_digest, - model_receipt_ids, - content_digest, - }) -} - -fn load_article_checkpoint( - store: &CampaignStore, - prepared: &PreparedNewspaper, - agenda_checkpoint_id: &str, - article_index: usize, - pitch: &WorldNewspaperStoryPitch, - journalist: &WorldNewspaperJournalist, -) -> Result)>> { - let assignment_digest = reporter_assignment_digest( - prepared, - agenda_checkpoint_id, - article_index, - pitch, - journalist, - )?; - let id = production_article_checkpoint_id( - prepared, - agenda_checkpoint_id, - article_index, - &assignment_digest, - )?; - let Some((_, checkpoint)) = store.load::( - "world_newspaper_production_checkpoint.v1", - &id, - )? - else { - return Ok(None); - }; - let receipts = load_model_receipts(store, &checkpoint.model_receipt_ids, "article checkpoint")?; - let WorldNewspaperProductionContent::FiledArticle { - agenda_checkpoint_id: stored_agenda_checkpoint_id, - article_index: stored_article_index, - assignment_digest: stored_assignment_digest, - journalist_id, - article, - } = &checkpoint.content - else { - return Err(anyhow!( - "article checkpoint occupies the wrong production slot" - )); - }; - let snapshot_binding = format!( - "{}:journalist:{}:article:{}", - prepared.binding, journalist.staff.id, article_index - ); - if checkpoint.schema != "ghostlight.world_newspaper_production_checkpoint.v1" - || checkpoint.id != id - || checkpoint.publication_task_binding != prepared.publication_task_binding - || checkpoint.editorial_binding != prepared.binding - || stored_agenda_checkpoint_id != agenda_checkpoint_id - || usize::from(*stored_article_index) != article_index - || stored_assignment_digest != &assignment_digest - || journalist_id != &journalist.staff.id - { - return Err(anyhow!("newspaper article checkpoint identity is invalid")); - } - validate_production_receipts( - &checkpoint, - &receipts, - "newspaper_journalist_agent_action", - &snapshot_binding, - )?; - validate_editorial_article(&prepared.records, article, article_index)?; - if article.section != pitch.section - || article.byline != journalist.byline - || article.citations.iter().collect::>() - != pitch.citations.iter().collect::>() - { - return Err(anyhow!( - "newspaper article checkpoint changed its exact assignment" - )); - } - Ok(Some((article.clone(), receipts))) -} - -async fn run_assigned_journalists( - model: &dyn ModelPort, - prepared: &PreparedNewspaper, - agenda: &WorldNewspaperEditorialAgenda, - agenda_checkpoint_id: &str, - selection_receipts: &[ModelStageReceipt], - store: &CampaignStore, -) -> std::result::Result< - (EditorialPageDraft, Vec), - crate::agent::ModelAgentFailure, -> { - let mut articles = Vec::with_capacity(agenda.story_pitches.len()); - let mut receipts = Vec::new(); - for (index, pitch) in agenda.story_pitches.iter().enumerate() { - let journalist = match journalist_by_id(&prepared.newsroom, &pitch.journalist_id) { - Ok(journalist) => journalist, - Err(error) => { - return Err(crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts, - }); - } - }; - match load_article_checkpoint( - store, - prepared, - agenda_checkpoint_id, - index, - pitch, - journalist, - ) { - Ok(Some((article, article_receipts))) => { - articles.push(article); - receipts.extend(article_receipts); - continue; - } - Ok(None) => {} - Err(error) => { - return Err(crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts, - }); - } - } - let reporter_identity = serde_json::to_string(journalist).unwrap_or_default(); - let instructions = format!( - "REPORTER'S HOUSE CHARTER\n\nYou file for `{title}`. You are a partisan storyteller, not the newsroom's fact checker. The assignment editor has already chosen the story, its focus event, its public question, and the evidence available for this filing. Make the strongest memorable case that assignment supports. Lead with the focus event. Use selection, sequence, contrast, and juxtaposition to imply meaning. Expose hypocrisy or conflict that your own instincts would recognize, and make the costs your beat understands vivid. A news article is not a recital of every supplied fact: omit material that does not serve the assigned story.\n\nShape the article for its declared context role. When you own an issue chronology, establish that chronology once and drive it toward the new consequence. When you assume the issue chronology, do not reconstruct the lead story; connect to it with only the minimum clause needed to make your distinct fact intelligible. When the story is self-contained, establish only its own facts. A continuing story must say what changed. Routine handling belongs behind the rupture unless the handling itself causes a public consequence. Do not repeat the deck as the first paragraph or summarize the same fact three ways to fill space.\n\nUse only the current workbench records for concrete events, people, institutions, places, identity attributes, chronology, quotations, motives, and outcomes. Preserve disputes through natural attribution. You may be cutting, emotional, insinuating, metaphorical, or politically judgmental without converting an insinuation into a sourced causal fact. Do not discuss records, citations, verification, assertion statuses, or missing evidence in reader copy. The copy editor will fact-check the filed story later. File two to five substantial paragraphs. For a lead, use exactly one value from `allowed_datelines` when that list is nonempty; when it is empty, leave the dateline empty. Non-leads may use an allowed value or leave it empty.\n\nPUBLICATION VOICE:\n{voice}\n\nRECURRING JOURNALIST\n\nYou are {name}. Readers should learn what you notice, whom you distrust, which sources you seek, where your sympathies lie, and what you routinely get wrong. Treat the identity below as your stable point of view across issues, not a list of phrases to repeat. Let it govern selection, sourcing, rhythm, humor, indignation, and what you leave for another reporter. Do not flatten yourself into the publication's generic house voice.\n\nYOUR RECURRING IDENTITY:\n{reporter_identity}", - name = journalist.staff.name, - title = prepared.title, - voice = prepared.editorial_voice, - ); - let mut causal_sources = pitch - .citations - .iter() - .cloned() - .chain( - selection_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()), - ) - .collect::>() - .into_iter() - .collect::>(); - causal_sources.sort(); - let spec = ModelAgentSpec { - stage: "newspaper_journalist_agent_action".into(), - model: MODEL_CAPABLE.into(), - snapshot_binding: format!( - "{}:journalist:{}:article:{}", - prepared.binding, journalist.staff.id, index - ), - instructions, - source_receipt_ids: causal_sources, - temperature: Some(0.9), - max_output_tokens: Some(2_200), - max_steps: 2, - }; - let mut workbench = JournalistWorkbench { - records: &prepared.records, - article_index: index, - byline: &journalist.byline, - issue_shape: agenda.issue_shape, - issue_shape_rationale: &agenda.issue_shape_rationale, - dominant_throughline: &agenda.dominant_throughline, - reader_stake: &agenda.reader_stake, - pitch, - }; - match crate::agent::run_model_agent(model, &spec, &mut workbench).await { - Ok(run) => { - let checkpoint = match new_article_checkpoint( - prepared, - agenda_checkpoint_id, - index, - pitch, - journalist, - run.output.clone(), - &run.receipts, - ) { - Ok(checkpoint) => checkpoint, - Err(error) => { - let mut failed_receipts = receipts; - failed_receipts.extend(run.receipts); - return Err(crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts: failed_receipts, - }); - } - }; - if let Err(error) = persist_production_checkpoint(store, &checkpoint, &run.receipts) - { - let mut failed_receipts = receipts; - failed_receipts.extend(run.receipts); - return Err(crate::agent::ModelAgentFailure { - message: error.to_string(), - receipts: failed_receipts, - }); - } - articles.push(run.output); - receipts.extend(run.receipts); - } - Err(mut failure) => { - let persistence_error = store - .persist_model_stage_receipts(&failure.receipts) - .err() - .map(|error| error.to_string()); - receipts.append(&mut failure.receipts); - return Err(crate::agent::ModelAgentFailure { - message: persistence_error.map_or(failure.message.clone(), |error| { - format!( - "{}; failed to persist rejected journalist receipts: {error}", - failure.message - ) - }), - receipts, - }); - } - } - } - Ok((EditorialPageDraft { articles }, receipts)) -} - -fn close_checkpoint_identity( - publication_task_binding: &str, - editorial_binding: &str, - origin: &WorldNewspaperCloseOrigin, - source_checkpoint_id: Option<&str>, - editorial_agenda: &WorldNewspaperEditorialAgenda, - draft: &EditorialPageDraft, - copy_desk: &WorldNewspaperCopyDeskReport, - model_receipt_ids: &[String], - receipt_chain_digest: &str, -) -> Result { - Ok(format!( - "newspaper-close:sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(&( - publication_task_binding, - editorial_binding, - origin, - source_checkpoint_id, - editorial_agenda, - draft, - copy_desk, - model_receipt_ids, - receipt_chain_digest, - ))?) - )) -} - -fn new_close_checkpoint( - prepared: &PreparedNewspaper, - origin: WorldNewspaperCloseOrigin, - source_checkpoint_id: Option, - editorial_agenda: WorldNewspaperEditorialAgenda, - draft: EditorialPageDraft, - copy_desk: WorldNewspaperCopyDeskReport, - receipts: &[ModelStageReceipt], -) -> Result { - let model_receipt_ids = receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - let receipt_chain_digest = checkpoint_receipt_chain_digest(&model_receipt_ids)?; - let id = close_checkpoint_identity( - &prepared.publication_task_binding, - &prepared.binding, - &origin, - source_checkpoint_id.as_deref(), - &editorial_agenda, - &draft, - ©_desk, - &model_receipt_ids, - &receipt_chain_digest, - )?; - Ok(WorldNewspaperCloseCheckpoint { - schema: "ghostlight.world_newspaper_close_checkpoint.v1".into(), - id, - publication_task_binding: prepared.publication_task_binding.clone(), - editorial_binding: prepared.binding.clone(), - origin, - source_checkpoint_id, - editorial_agenda, - draft, - copy_desk, - model_receipt_ids, - receipt_chain_digest, - }) -} - -fn persist_close_checkpoint( - store: &CampaignStore, - checkpoint: &WorldNewspaperCloseCheckpoint, -) -> Result<()> { - let kind = "world_newspaper_close_checkpoint.v1"; - if let Some((_, existing)) = - store.load::(kind, &checkpoint.id)? - { - if existing != *checkpoint { - return Err(anyhow!( - "immutable newspaper close checkpoint conflict: {}", - checkpoint.id - )); - } - return Ok(()); - } - store.insert( - kind, - "ghostlight.world_newspaper_close_checkpoint.v1", - &checkpoint.id, - checkpoint, - )?; - Ok(()) -} - -fn persist_newspaper_completion( - store: &CampaignStore, - publication_task_binding: &str, - binding: &str, - source_checkpoint_id: Option, - composition: &WorldNewspaperComposition, -) -> Result<()> { - let kind = "world_newspaper_composition.v3"; - let record = PersistedWorldNewspaperComposition { - schema: "ghostlight.persisted_world_newspaper_composition.v3".into(), - publication_task_binding: publication_task_binding.into(), - editorial_binding: binding.into(), - source_checkpoint_id, - composition: composition.clone(), - }; - if let Some((_, existing)) = - store.load::(kind, publication_task_binding)? - { - if existing != record { - return Err(anyhow!( - "immutable accepted newspaper composition conflict for {binding}" - )); - } - return Ok(()); - } - store.insert( - kind, - "ghostlight.persisted_world_newspaper_composition.v3", - publication_task_binding, - &record, - )?; - Ok(()) -} - -fn validate_copy_desk_report( - draft: &EditorialPageDraft, - report: &WorldNewspaperCopyDeskReport, -) -> Result<()> { - validate_single_line(&report.assessment, 500, "copy-desk assessment")?; - for query in &report.queries { - validate_single_line(&query.claim_or_phrase, 500, "copy-desk claim")?; - validate_single_line(&query.reason, 500, "copy-desk reason")?; - validate_grounding_finding_target(draft, query)?; - } - Ok(()) -} - -fn validate_close_checkpoint( - checkpoint: &WorldNewspaperCloseCheckpoint, - prepared: &PreparedNewspaper, - max_articles: usize, - receipts: &[ModelStageReceipt], -) -> Result<()> { - if checkpoint.schema != "ghostlight.world_newspaper_close_checkpoint.v1" - || checkpoint.publication_task_binding != prepared.publication_task_binding - || checkpoint.editorial_binding != prepared.binding - || receipts.len() != checkpoint.model_receipt_ids.len() - { - return Err(anyhow!("newspaper close checkpoint is invalid")); - } - if checkpoint.origin != WorldNewspaperCloseOrigin::InitialCopyDesk - || checkpoint.source_checkpoint_id.is_some() - { - return Err(anyhow!( - "newspaper close checkpoint does not belong to the current newsroom" - )); - } - let receipt_ids = receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - if receipt_ids != checkpoint.model_receipt_ids - || receipt_ids.iter().collect::>().len() != receipt_ids.len() - || checkpoint_receipt_chain_digest(&receipt_ids)? != checkpoint.receipt_chain_digest - || close_checkpoint_identity( - &checkpoint.publication_task_binding, - &checkpoint.editorial_binding, - &checkpoint.origin, - checkpoint.source_checkpoint_id.as_deref(), - &checkpoint.editorial_agenda, - &checkpoint.draft, - &checkpoint.copy_desk, - &checkpoint.model_receipt_ids, - &checkpoint.receipt_chain_digest, - )? != checkpoint.id - { - return Err(anyhow!( - "newspaper close checkpoint receipt binding is invalid" - )); - } - if receipts - .iter() - .rev() - .find(|receipt| receipt.stage == "newspaper_copy_desk") - .map(|receipt| receipt.storage_key()) - != receipt_ids.last().map(String::as_str) - { - return Err(anyhow!( - "newspaper close checkpoint lost its final copy-desk receipt" - )); - } - validate_editorial_agenda( - &prepared.records, - &prepared.newsroom, - &checkpoint.editorial_agenda, - max_articles, - )?; - validate_editorial_draft(&prepared.records, &checkpoint.draft, max_articles)?; - validate_editorial_alignment( - &checkpoint.draft, - &prepared.newsroom, - &checkpoint.editorial_agenda, - )?; - validate_copy_desk_report(&checkpoint.draft, &checkpoint.copy_desk)?; - Ok(()) -} - -fn load_close_checkpoint( - store: &CampaignStore, - prepared: &PreparedNewspaper, - max_articles: usize, -) -> Result)>> { - let checkpoints = store - .load_all::("world_newspaper_close_checkpoint.v1")? - .into_iter() - .filter(|checkpoint| { - checkpoint.origin == WorldNewspaperCloseOrigin::InitialCopyDesk - && checkpoint.publication_task_binding == prepared.publication_task_binding - }) - .collect::>(); - if checkpoints.is_empty() { - return Ok(None); - } - if checkpoints.len() != 1 { - return Err(anyhow!( - "newspaper close task has multiple immutable checkpoints" - )); - } - let checkpoint = checkpoints.into_iter().next().expect("one checkpoint"); - let receipts = load_model_receipts(store, &checkpoint.model_receipt_ids, "newspaper close")?; - validate_close_checkpoint(&checkpoint, prepared, max_articles, &receipts)?; - Ok(Some((checkpoint, receipts))) -} - -fn editorial_draft_from_issue(issue: &WorldNewspaperIssue) -> Result { - let articles = issue - .articles - .iter() - .map(|article| { - let citations = article - .sources - .iter() - .map(|source| { - if source.source_news_ids.len() != 1 { - return Err(anyhow!( - "printed newspaper source does not name exactly one public record" - )); - } - Ok(source.source_news_ids[0].clone()) - }) - .collect::>>()?; - Ok(EditorialArticleDraft { - section: article.section.clone(), - headline: article.headline.clone(), - deck: article.deck.clone(), - byline: article.byline.clone(), - dateline: article.dateline.clone().unwrap_or_default(), - citations, - paragraphs: article.paragraphs.clone(), - }) - }) - .collect::>>()?; - Ok(EditorialPageDraft { articles }) -} - -fn validate_persisted_composition( - store: &CampaignStore, - campaign: &Campaign, - prepared: &PreparedNewspaper, - max_articles: usize, - persisted: &PersistedWorldNewspaperComposition, -) -> Result<()> { - let composition = &persisted.composition; - if persisted.schema != "ghostlight.persisted_world_newspaper_composition.v3" - || persisted.publication_task_binding != prepared.publication_task_binding - || persisted.editorial_binding != prepared.binding - || composition.schema != "ghostlight.world_newspaper_composition.v3" - || composition.issue.schema != "ghostlight.world_newspaper_issue.v3" - || composition.issue.source_world_revision != campaign.revision - || composition.issue.title != prepared.title - || composition.issue.edition_label != EDITION_LABEL - { - return Err(anyhow!("persisted newspaper composition is invalid")); - } - if composition.issue.articles.is_empty() { - if persisted.source_checkpoint_id.is_some() - || composition.issue.id - != empty_issue_id(campaign, &prepared.title, &prepared.newsroom)? - || composition.issue.at != campaign.world_time - || composition.issue.lead_article_id.is_some() - || composition.issue.editorial_agenda.is_some() - || !composition.issue.editorial_receipt_ids.is_empty() - || !composition.model_receipts.is_empty() - || !composition.copy_desk.queries.is_empty() - || composition.press_close.schema != "ghostlight.world_newspaper_press_close.v1" - || composition.press_close.source_checkpoint_id != "no-edition" - || !composition.press_close.copy_desk_receipt_id.is_empty() - || !composition.press_close.night_editor_receipt_id.is_empty() - || composition.press_close.night_editor_action_applied - || !composition.press_close.addressed_query_indices.is_empty() - || !composition.press_close.changed_article_indices.is_empty() - || composition.press_close.source_page_digest != "no-edition" - || composition.press_close.printed_page_digest != "no-edition" - { - return Err(anyhow!("persisted no-edition newspaper is invalid")); - } - return Ok(()); - } - - let source_checkpoint_id = persisted - .source_checkpoint_id - .as_deref() - .ok_or_else(|| anyhow!("persisted newspaper lost its close checkpoint"))?; - let checkpoint = store - .load::( - "world_newspaper_close_checkpoint.v1", - source_checkpoint_id, - )? - .map(|(_, checkpoint)| checkpoint) - .ok_or_else(|| anyhow!("persisted newspaper close checkpoint is missing"))?; - let checkpoint_receipts = - load_model_receipts(store, &checkpoint.model_receipt_ids, "persisted newspaper")?; - validate_close_checkpoint(&checkpoint, prepared, max_articles, &checkpoint_receipts)?; - if composition.model_receipts.len() != checkpoint_receipts.len() + 1 - || !composition.model_receipts.starts_with(&checkpoint_receipts) - || composition.copy_desk != checkpoint.copy_desk - || composition.issue.editorial_agenda.as_ref() != Some(&checkpoint.editorial_agenda) - || composition.press_close.schema != "ghostlight.world_newspaper_press_close.v1" - || composition.press_close.source_checkpoint_id != checkpoint.id - || composition.press_close.copy_desk_receipt_id - != checkpoint - .model_receipt_ids - .last() - .cloned() - .unwrap_or_default() - { - return Err(anyhow!("persisted newspaper press lineage is invalid")); - } - for receipt in &composition.model_receipts { - let stored = store - .load::("persona_stage_receipt.v1", receipt.storage_key())? - .map(|(_, stored)| stored) - .ok_or_else(|| anyhow!("persisted newspaper model receipt is missing"))?; - if !stored.same_receipted_content(receipt) { - return Err(anyhow!("persisted newspaper model receipt changed")); - } - } - let night_editor_receipt = composition - .model_receipts - .last() - .expect("non-empty edition has one closing receipt"); - if night_editor_receipt.stage != "newspaper_night_editor_close_agent_action" - || composition.press_close.night_editor_receipt_id != night_editor_receipt.storage_key() - { - return Err(anyhow!("persisted newspaper lost its Night Editor close")); - } - - let printed_draft = editorial_draft_from_issue(&composition.issue)?; - let addressed_queries = composition - .press_close - .addressed_query_indices - .iter() - .map(|index| usize::from(*index)) - .collect::>(); - let expected_queries = (0..checkpoint.copy_desk.queries.len()).collect::>(); - let changed_articles = composition - .press_close - .changed_article_indices - .iter() - .map(|index| usize::from(*index)) - .collect::>(); - let required_changed_articles = checkpoint - .copy_desk - .queries - .iter() - .map(|query| usize::from(query.article_index)) - .collect::>(); - if editorial_page_digest(&checkpoint.draft)? != composition.press_close.source_page_digest - || editorial_page_digest(&printed_draft)? != composition.press_close.printed_page_digest - || composition.issue.editorial_receipt_ids - != composition - .model_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>() - || (composition.press_close.night_editor_action_applied - && (addressed_queries != expected_queries - || addressed_queries.len() - != composition.press_close.addressed_query_indices.len() - || changed_articles != required_changed_articles - || changed_articles.len() != composition.press_close.changed_article_indices.len() - || changed_articles - .iter() - .any(|index| *index >= checkpoint.draft.articles.len()))) - || (!composition.press_close.night_editor_action_applied - && (!addressed_queries.is_empty() - || !changed_articles.is_empty() - || printed_draft != checkpoint.draft - || night_editor_receipt.validation_result != "semantic_invalid")) - { - return Err(anyhow!("persisted newspaper press witness is invalid")); - } - let expected_issue = lower_editorial_page( - campaign, - prepared.title.clone(), - &prepared.records, - Some(checkpoint.editorial_agenda), - printed_draft, - &composition.model_receipts, - )?; - if composition.issue != expected_issue { - return Err(anyhow!("persisted newspaper issue cannot be re-derived")); - } - Ok(()) -} - -async fn close_world_newspaper( - model: &dyn ModelPort, - campaign: &Campaign, - prepared: &PreparedNewspaper, - max_articles: usize, - store: &CampaignStore, - checkpoint: WorldNewspaperCloseCheckpoint, - mut receipts: Vec, -) -> Result { - validate_close_checkpoint(&checkpoint, prepared, max_articles, &receipts)?; - let source_json = source_json_for_copy_queries( - &prepared.records, - &checkpoint.editorial_agenda, - &checkpoint.copy_desk, - )?; - let progress = match run_night_editor_close( - model, - &prepared.records, - max_articles, - &prepared.binding, - &prepared.title, - &prepared.editorial_voice, - &prepared.newsroom, - &checkpoint.editorial_agenda, - &source_json, - &prepared.source_receipt_ids, - &receipts, - &checkpoint.id, - checkpoint.draft.clone(), - checkpoint.copy_desk.clone(), - ) - .await - { - Ok(progress) => progress, - Err(failure) => { - store.persist_model_stage_receipts(&failure.receipts)?; - receipts.extend(failure.receipts); - return Err(composition_failure(failure.message, receipts)); - } - }; - let ( - closing_receipts, - final_draft, - action_applied, - addressed_query_indices, - changed_article_indices, - ) = match progress { - ModelAgentProgress::Accepted(run) => ( - run.receipts, - run.output.draft, - true, - run.output.addressed_query_indices, - run.output.changed_article_indices, - ), - ModelAgentProgress::Exhausted(exhausted) => ( - exhausted.receipts, - checkpoint.draft.clone(), - false, - Vec::new(), - Vec::new(), - ), - }; - let night_editor_receipt_id = closing_receipts - .last() - .map(|receipt| receipt.storage_key().to_owned()) - .ok_or_else(|| anyhow!("Night Editor close produced no model receipt"))?; - store.persist_model_stage_receipts(&closing_receipts)?; - receipts.extend(closing_receipts); - let issue = lower_editorial_page( - campaign, - prepared.title.clone(), - &prepared.records, - Some(checkpoint.editorial_agenda.clone()), - final_draft.clone(), - &receipts, - )?; - let press_close = WorldNewspaperPressClose { - schema: "ghostlight.world_newspaper_press_close.v1".into(), - source_checkpoint_id: checkpoint.id.clone(), - copy_desk_receipt_id: checkpoint - .model_receipt_ids - .last() - .cloned() - .ok_or_else(|| anyhow!("newspaper close checkpoint has no copy-desk receipt"))?, - night_editor_receipt_id, - night_editor_action_applied: action_applied, - addressed_query_indices, - changed_article_indices, - source_page_digest: editorial_page_digest(&checkpoint.draft)?, - printed_page_digest: editorial_page_digest(&final_draft)?, - }; - let composition = WorldNewspaperComposition { - schema: "ghostlight.world_newspaper_composition.v3".into(), - issue, - copy_desk: checkpoint.copy_desk, - press_close, - model_receipts: receipts, - }; - persist_newspaper_completion( - store, - &prepared.publication_task_binding, - &prepared.binding, - Some(checkpoint.id), - &composition, - )?; - Ok(composition) -} - -pub async fn advance_world_newspaper( - model: &dyn ModelPort, - campaign: &Campaign, - title: impl Into, - editorial_voice: impl Into, - newsroom: &WorldNewspaperNewsroom, - max_articles: usize, - store: &CampaignStore, -) -> Result { - let prepared = prepare_newspaper(campaign, title, editorial_voice, newsroom, max_articles)?; - if let Some((_, persisted)) = store.load::( - "world_newspaper_composition.v3", - &prepared.publication_task_binding, - )? { - validate_persisted_composition(store, campaign, &prepared, max_articles, &persisted)?; - return Ok(persisted.composition); - } - if let Some((checkpoint, receipts)) = load_close_checkpoint(store, &prepared, max_articles)? { - return close_world_newspaper( - model, - campaign, - &prepared, - max_articles, - store, - checkpoint, - receipts, - ) - .await; - } - if prepared.records.is_empty() { - let issue = WorldNewspaperIssue { - schema: "ghostlight.world_newspaper_issue.v3".into(), - id: empty_issue_id(campaign, &prepared.title, &prepared.newsroom)?, - title: prepared.title.clone(), - edition_label: "No edition issued".into(), - at: campaign.world_time, - source_world_revision: campaign.revision, - lead_article_id: None, - editorial_agenda: None, - articles: Vec::new(), - editorial_receipt_ids: Vec::new(), - }; - let composition = WorldNewspaperComposition { - schema: "ghostlight.world_newspaper_composition.v3".into(), - issue, - copy_desk: WorldNewspaperCopyDeskReport { - assessment: "No public source material was available, so no edition was issued." - .into(), - queries: Vec::new(), - }, - press_close: WorldNewspaperPressClose { - schema: "ghostlight.world_newspaper_press_close.v1".into(), - source_checkpoint_id: "no-edition".into(), - copy_desk_receipt_id: String::new(), - night_editor_receipt_id: String::new(), - night_editor_action_applied: false, - addressed_query_indices: Vec::new(), - changed_article_indices: Vec::new(), - source_page_digest: "no-edition".into(), - printed_page_digest: "no-edition".into(), - }, - model_receipts: Vec::new(), - }; - persist_newspaper_completion( - store, - &prepared.publication_task_binding, - &prepared.binding, - None, - &composition, - )?; - return Ok(composition); - } - let (agenda_checkpoint_id, agenda, mut receipts) = - if let Some(checkpoint) = load_agenda_checkpoint(store, &prepared, max_articles)? { - checkpoint - } else { - let agenda_run = match select_editorial_agenda(model, &prepared, max_articles).await { - Ok(run) => run, - Err(failure) => { - store.persist_model_stage_receipts(&failure.receipts)?; - return Err(composition_failure(failure.message, failure.receipts)); - } - }; - let checkpoint = - new_agenda_checkpoint(&prepared, agenda_run.output.clone(), &agenda_run.receipts)?; - persist_production_checkpoint(store, &checkpoint, &agenda_run.receipts)?; - (checkpoint.id, agenda_run.output, agenda_run.receipts) - }; - let selected_source_json = source_json_for_agenda(&prepared.records, Some(&agenda))?; - let (draft, journalist_receipts) = run_assigned_journalists( - model, - &prepared, - &agenda, - &agenda_checkpoint_id, - &receipts, - store, - ) - .await - .map_err(|failure| { - let mut all_receipts = receipts.clone(); - all_receipts.extend(failure.receipts); - composition_failure(failure.message, all_receipts) - })?; - receipts.extend(journalist_receipts); - validate_editorial_draft(&prepared.records, &draft, max_articles)?; - validate_editorial_alignment(&draft, &prepared.newsroom, &agenda)?; - store.persist_model_stage_receipts(&receipts)?; - let page_digest = editorial_page_digest(&draft)?; - let journalist_receipt_ids = receipts - .iter() - .filter(|receipt| receipt.stage == "newspaper_journalist_agent_action") - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - let copy_desk = match run_copy_desk( - model, - format!("{}:draft:{page_digest}", prepared.binding), - &selected_source_json, - &prepared.newsroom.copy_editor, - &prepared.source_receipt_ids, - &journalist_receipt_ids, - &draft, - &mut receipts, - ) - .await - { - Ok(report) => report, - Err(error) => { - store.persist_model_stage_receipts(&receipts)?; - return Err(composition_failure(error.to_string(), receipts)); - } - }; - store.persist_model_stage_receipts(&receipts)?; - let checkpoint = new_close_checkpoint( - &prepared, - WorldNewspaperCloseOrigin::InitialCopyDesk, - None, - agenda, - draft, - copy_desk, - &receipts, - )?; - validate_close_checkpoint(&checkpoint, &prepared, max_articles, &receipts)?; - persist_close_checkpoint(store, &checkpoint)?; - close_world_newspaper( - model, - campaign, - &prepared, - max_articles, - store, - checkpoint, - receipts, - ) - .await -} - -#[cfg(test)] -async fn compose_world_newspaper( - model: &dyn ModelPort, - campaign: &Campaign, - title: impl Into, - editorial_voice: impl Into, - max_articles: usize, -) -> Result { - let directory = tempfile::tempdir()?; - let store = CampaignStore::open(directory.path().join("campaign.cc"))?; - advance_world_newspaper( - model, - campaign, - title, - editorial_voice, - &canopy_ledger_newsroom(), - max_articles, - &store, - ) - .await -} - -struct NightEditorCloseWorkbench<'a> { - records: &'a [PublicRecordProjection], - max_articles: usize, - draft: EditorialPageDraft, - copy_desk: WorldNewspaperCopyDeskReport, -} - -#[async_trait] -impl ModelAgentTool for NightEditorCloseWorkbench<'_> { - type Action = NightEditorCloseAction; - type Output = NightEditorCloseOutput; - type Finding = NightEditorCloseFinding; - - fn action_schema(&self) -> std::result::Result { - let mut rewrite_schema = serde_json::to_value(schema_for!(NightEditorArticleClose)) - .map_err(|error| error.to_string())?; - let definitions = rewrite_schema - .as_object_mut() - .and_then(|schema| schema.remove("$defs")) - .unwrap_or_else(|| serde_json::json!({})); - if let Some(schema) = rewrite_schema.as_object_mut() { - schema.remove("$schema"); - } - let article_indices = (0..self.max_articles) - .map(serde_json::Value::from) - .collect::>(); - rewrite_schema["properties"]["article_index"] = serde_json::json!({ - "type":"integer", - "enum":article_indices - }); - let mut schema = serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["tool", "addressed_query_indices", "rewrites"], - "properties":{ - "tool":{"const":"submit_close"}, - "addressed_query_indices":{ - "type":"array", - "uniqueItems":true, - "items":{"type":"integer", "minimum":0, "maximum":65535} - }, - "rewrites":{ - "type":"array", - "minItems":0, - "maxItems":self.max_articles, - "uniqueItems":true, - "items":rewrite_schema - } - }, - "$defs":definitions - }); - crate::model_connector::project_strict_responses_schema(&mut schema) - .map_err(|error| error.to_string())?; - Ok(schema) - } - - async fn invoke( - &mut self, - action: Self::Action, - _context: &ModelAgentToolContext, - ) -> ModelAgentToolOutcome { - let output = match apply_night_editor_close(&self.draft, &self.copy_desk, action) { - Ok(output) => output, - Err(error) => { - return ModelAgentToolOutcome::Rejected { - finding: night_editor_close_finding( - self.draft.clone(), - self.copy_desk.clone(), - format!("The proposed deadline close was not admitted: {error}"), - ), - receipts: Vec::new(), - }; - } - }; - if let Err(error) = validate_editorial_draft(self.records, &output.draft, self.max_articles) - { - return ModelAgentToolOutcome::Rejected { - finding: night_editor_close_finding( - self.draft.clone(), - self.copy_desk.clone(), - format!("The proposed deadline close produced invalid copy: {error}"), - ), - receipts: Vec::new(), - }; - } - ModelAgentToolOutcome::Accepted { - output, - receipts: Vec::new(), - } - } -} - -fn apply_night_editor_close( - original: &EditorialPageDraft, - copy_desk: &WorldNewspaperCopyDeskReport, - action: NightEditorCloseAction, -) -> Result { - let NightEditorCloseAction::SubmitClose { - addressed_query_indices, - rewrites, - } = action; - let expected_queries = (0..copy_desk.queries.len()).collect::>(); - let addressed_queries = addressed_query_indices - .iter() - .map(|index| usize::from(*index)) - .collect::>(); - if addressed_queries != expected_queries - || addressed_queries.len() != addressed_query_indices.len() - { - return Err(anyhow!( - "the Night Editor must disposition every copy-desk query exactly once" - )); - } - let affected = copy_desk - .queries - .iter() - .map(|query| usize::from(query.article_index)) - .collect::>(); - if affected - .iter() - .any(|article_index| *article_index >= original.articles.len()) - { - return Err(anyhow!("rejecting desk named an invalid article")); - } - let mut draft = original.clone(); - let mut rewritten = BTreeSet::new(); - for rewrite in rewrites { - let article_index = usize::from(rewrite.article_index); - if article_index >= original.articles.len() || !rewritten.insert(article_index) { - return Err(anyhow!( - "deadline close names an invalid or duplicate article" - )); - } - let article = draft - .articles - .get_mut(article_index) - .ok_or_else(|| anyhow!("deadline close names an invalid article"))?; - article.headline = rewrite.headline; - article.deck = rewrite.deck; - article.dateline = rewrite.dateline; - article.paragraphs = rewrite.paragraphs; - } - if rewritten != affected { - return Err(anyhow!( - "the Night Editor must rewrite exactly the copy-queried articles in one bounded pass" - )); - } - Ok(NightEditorCloseOutput { - draft, - addressed_query_indices, - changed_article_indices: rewritten.into_iter().map(|index| index as u16).collect(), - }) -} - -#[allow(clippy::too_many_arguments)] -async fn run_night_editor_close( - model: &dyn ModelPort, - records: &[PublicRecordProjection], - max_articles: usize, - binding: &str, - title: &str, - editorial_voice: &str, - newsroom: &WorldNewspaperNewsroom, - agenda: &WorldNewspaperEditorialAgenda, - source_json: &str, - source_receipt_ids: &[String], - prior_receipts: &[ModelStageReceipt], - checkpoint_id: &str, - draft: EditorialPageDraft, - copy_desk: WorldNewspaperCopyDeskReport, -) -> std::result::Result, crate::agent::ModelAgentFailure> -{ - let numbered_queries = copy_desk - .queries - .iter() - .enumerate() - .map(|(query_index, query)| serde_json::json!({"query_index":query_index, "query":query})) - .collect::>(); - let affected_article_indices = copy_desk - .queries - .iter() - .map(|query| usize::from(query.article_index)) - .collect::>(); - let affected_assignments = agenda - .story_pitches - .iter() - .enumerate() - .filter(|(article_index, _)| affected_article_indices.contains(article_index)) - .map(|(article_index, pitch)| { - serde_json::json!({"article_index": article_index, "assignment": pitch}) - }) - .collect::>(); - let queried_articles = draft - .articles - .iter() - .enumerate() - .filter(|(article_index, _)| affected_article_indices.contains(article_index)) - .map(|(article_index, article)| { - serde_json::json!({"article_index": article_index, "article": article}) - }) - .collect::>(); - let affected_journalist_ids = copy_desk - .queries - .iter() - .filter_map(|query| agenda.story_pitches.get(usize::from(query.article_index))) - .map(|pitch| pitch.journalist_id.as_str()) - .collect::>(); - let affected_journalists = newsroom - .journalists - .iter() - .filter(|journalist| affected_journalist_ids.contains(journalist.staff.id.as_str())) - .collect::>(); - let instructions = format!( - "You are {night_editor}, Night Editor of `{title}`. The copy editor has lodged one complete numbered factual checklist and the press closes after this action. Address every item, replacing exactly the articles named by that checklist. Preserve each reporter's argument, urgency, style, and insinuation while making the smallest changes that resolve the cited defect. Do not select stories, widen sources, or improve unrelated articles. Sections, bylines, citations, story order, and assignments are frozen. Nobody rereads the final prose before printing; a later edition may correct a mistake.\n\nKeep distinct reports grammatically distinct when causation is not established and attribute disputes naturally. Do not expose the checklist or verification machinery in reader copy. If there are no queries, submit an unchanged close with empty lists.\n\nNIGHT EDITOR:\n{night_profile}\n\nAFFECTED REPORTERS:\n{reporters}\n\nPUBLICATION VOICE:\n{editorial_voice}\n\nAFFECTED ASSIGNMENTS:\n{agenda_json}\n\nFACTS FOR QUERIED ARTICLES:\n{source_json}\n\nQUERIED ARTICLES:\n{draft_json}\n\nNUMBERED QUERIES:\n{query_json}", - night_editor = newsroom.night_editor.name, - title = title, - night_profile = serde_json::to_string(&newsroom.night_editor).unwrap_or_default(), - reporters = serde_json::to_string(&affected_journalists).unwrap_or_default(), - editorial_voice = editorial_voice, - agenda_json = serde_json::to_string_pretty(&serde_json::json!({ - "dominant_throughline": agenda.dominant_throughline, - "reader_stake": agenda.reader_stake, - "assignments": affected_assignments, - })) - .unwrap_or_default(), - source_json = source_json, - draft_json = serde_json::to_string_pretty(&queried_articles).unwrap_or_default(), - query_json = serde_json::to_string_pretty(&numbered_queries).unwrap_or_default(), - ); - let mut causal_sources = source_receipt_ids - .iter() - .cloned() - .chain( - prior_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()), - ) - .chain(std::iter::once(checkpoint_id.to_owned())) - .collect::>() - .into_iter() - .collect::>(); - causal_sources.sort(); - let spec = ModelAgentSpec { - stage: "newspaper_night_editor_close_agent_action".into(), - model: MODEL_BALANCED.into(), - snapshot_binding: format!("{binding}:night-editor-close:{checkpoint_id}"), - instructions, - source_receipt_ids: causal_sources, - temperature: Some(0.35), - max_output_tokens: Some(4_500), - max_steps: 1, - }; - let mut tool = NightEditorCloseWorkbench { - records, - max_articles, - draft, - copy_desk, - }; - crate::agent::run_model_agent_progress(model, &spec, &mut tool).await -} - -async fn run_copy_desk( - model: &dyn ModelPort, - snapshot_binding: String, - source_json: &str, - copy_editor: &WorldNewspaperStaffMember, - source_receipt_ids: &[String], - editorial_source_receipt_ids: &[String], - draft: &EditorialPageDraft, - receipts: &mut Vec, -) -> Result { - let verifier_schema = serde_json::to_value(schema_for!(WorldNewspaperCopyDeskReport))?; - let verifier_request = ModelStageRequest { - stage: "newspaper_copy_desk".into(), - model: MODEL_CAPABLE.into(), - snapshot_binding, - lived_stream: format!( - "You are {}, the publication's copy editor. Act as the sole factual query desk, not a rewriting model or publication judge. Compare every concrete reader-facing claim with only its cited notes. Query invented or overconfident facts, quotations, identities, offices, places, numbers, motives, outcomes, chronology, spatial relationships, affiliations, or private knowledge. Assertion status is exhaustive: an attempted or adopted course does not prove embedded acts completed, and a public declaration proves only the declaration. Supported identity attributes are exhaustive; an empty list supports no pronoun, title, kinship, office, membership, or affiliation. Shared location does not establish unstated geometry. Preserve disputes through attribution.\n\nMetaphor, wit, contrast, opinion, political characterization, and juxtaposition are editorial language unless they smuggle in a concrete fact or causal outcome. Return the complete query set at once. Each claim_or_phrase must be an exact unique substring of its article. Never propose replacement copy and never query a staff byline merely because the world ledger does not name the employee.\n\nCOPY EDITOR:\n{}\n\nFACT DESK:\n{}\n\nPROPOSED PAGE:\n{}", - copy_editor.name, - serde_json::to_string(copy_editor)?, - source_json, - serde_json::to_string_pretty(draft)?, - ), - output_schema: Some(verifier_schema), - source_receipt_ids: source_receipt_ids - .iter() - .cloned() - .chain(editorial_source_receipt_ids.iter().cloned()) - .collect(), - temperature: Some(0.0), - max_output_tokens: Some(1_500), - }; - let verifier_output = run_validated_stage(model, &verifier_request) - .await - .map_err(|error| anyhow!("newspaper copy-desk inference failed: {error}"))?; - receipts.push(verifier_output.receipt); - let receipt_index = receipts.len() - 1; - let verifier_structured = verifier_output - .structured - .ok_or_else(|| anyhow!("newspaper copy desk returned no structured output")); - let verifier_structured = match verifier_structured { - Ok(structured) => structured, - Err(error) => { - mark_semantic_invalid(&mut receipts[receipt_index], &error); - return Err(error); - } - }; - let report: WorldNewspaperCopyDeskReport = match serde_json::from_value(verifier_structured) { - Ok(report) => report, - Err(error) => { - let error = anyhow!("newspaper copy desk returned an invalid report: {error}"); - mark_semantic_invalid(&mut receipts[receipt_index], &error); - return Err(error); - } - }; - if let Err(error) = validate_copy_desk_report(draft, &report) { - mark_semantic_invalid(&mut receipts[receipt_index], &error); - return Err(error); - } - Ok(report) -} - -pub fn render_world_newspaper_markdown(issue: &WorldNewspaperIssue) -> String { - let mut rendered = format!( - "# {}\n\n*{}*\n\n---\n", - escape_markdown_text(&issue.title), - escape_markdown_text(&issue.edition_label) - ); - for (index, article) in issue.articles.iter().enumerate() { - if index > 0 { - rendered.push_str(&format!( - "\n---\n\n### {}\n", - escape_markdown_text(&article.section) - )); - } - rendered.push_str(&format!( - "\n## {}\n\n", - escape_markdown_text(&article.headline) - )); - rendered.push_str(&format!("*{}*\n\n", escape_markdown_text(&article.deck))); - rendered.push_str(&format!( - "**{}**\n\n", - escape_markdown_text(&article.byline) - )); - for (paragraph_index, paragraph) in article.paragraphs.iter().enumerate() { - if paragraph_index == 0 - && let Some(dateline) = &article.dateline - { - rendered.push_str(&format!( - "**{} —** {}\n\n", - escape_markdown_text(dateline), - escape_markdown_text(paragraph) - )); - } else { - rendered.push_str(&escape_markdown_text(paragraph)); - rendered.push_str("\n\n"); - } - } - } - rendered.trim_end().to_owned() + "\n" -} - -fn escape_markdown_text(value: &str) -> String { - let mut escaped = String::with_capacity(value.len()); - let characters = value.chars().collect::>(); - let line_prefix_escape = markdown_line_prefix_escape(&characters); - for (index, character) in characters.into_iter().enumerate() { - if line_prefix_escape == Some(index) { - escaped.push('\\'); - } - match character { - '&' => escaped.push_str("&"), - '<' => escaped.push_str("<"), - '>' => escaped.push_str(">"), - '\\' | '`' | '*' | '_' | '{' | '}' | '[' | ']' | '#' | '|' | '~' => { - escaped.push('\\'); - escaped.push(character); - } - _ => escaped.push(character), - } - } - escaped -} - -fn markdown_line_prefix_escape(characters: &[char]) -> Option { - if matches!(characters.first(), Some('-' | '+')) { - return Some(0); - } - let digit_count = characters - .iter() - .take(9) - .take_while(|character| character.is_ascii_digit()) - .count(); - if digit_count > 0 - && matches!(characters.get(digit_count), Some('.' | ')')) - && characters - .get(digit_count + 1) - .is_some_and(|character| character.is_whitespace()) - { - return Some(digit_count); - } - None -} - -pub fn render_world_newspaper_audit_markdown(issue: &WorldNewspaperIssue) -> String { - let mut rendered = format!( - "# Editorial provenance: {}\n\n- Source world revision: {}\n- Editorial receipts: {}\n", - escape_markdown_text(&issue.title), - issue.source_world_revision, - escaped_join(&issue.editorial_receipt_ids) - ); - if let Some(agenda) = &issue.editorial_agenda { - rendered.push_str(&format!( - "\n## Editorial agenda\n\n- Issue shape: {:?}\n- Issue-shape rationale: {}\n- Dominant throughline: {}\n- Reader stake: {}\n", - agenda.issue_shape, - escape_markdown_text(&agenda.issue_shape_rationale), - escape_markdown_text(&agenda.dominant_throughline), - escape_markdown_text(&agenda.reader_stake), - )); - for (index, pitch) in agenda.story_pitches.iter().enumerate() { - rendered.push_str(&format!( - "\n### Pitch {}{}\n\n- Journalist: {}\n- Narrative function: {:?}\n- Context role: {:?}\n- Assignment reason: {}\n- Public records: {}\n- Focus record: {}\n- Narrative claim: {}\n- Tension: {}\n- Public question: {}\n", - index + 1, - if pitch.lead { " (lead)" } else { "" }, - escape_markdown_text(&pitch.journalist_id), - pitch.narrative_function, - pitch.context_role, - escape_markdown_text(&pitch.assignment_reason), - escaped_join(&pitch.citations), - escape_markdown_text(&pitch.focus_citation), - escape_markdown_text(&pitch.narrative_claim), - escape_markdown_text(&pitch.tension), - escape_markdown_text(&pitch.public_question), - )); - } - } - for article in &issue.articles { - rendered.push_str(&format!( - "\n## {}\n\n- Article ID: {}\n", - escape_markdown_text(&article.headline), - escape_markdown_text(&article.id), - )); - for source in &article.sources { - let source_time = if source.source_times.is_empty() { - String::new() - } else { - format!( - "- Source time: {}\n", - source - .source_times - .iter() - .map(DateTime::::to_rfc3339) - .collect::>() - .join(", ") - ) - }; - rendered.push_str(&format!( - "\n### Citation {}\n\n- Source news: {}\n{}- Source channels: {}\n- Source reliability: {}\n", - escape_markdown_text(&source.citation), - escaped_join(&source.source_news_ids), - source_time, - escaped_join(&source.source_channels), - escaped_join(&source.source_reliability), - )); - for (fact_index, fact) in source.facts.iter().enumerate() { - let named_people = if fact.named_people.is_empty() { - "None asserted".into() - } else { - fact.named_people - .iter() - .map(|person| { - let attributes = if person.supported_identity_attributes.is_empty() { - "none asserted".into() - } else { - escaped_join(&person.supported_identity_attributes) - }; - format!( - "{} (supported identity attributes: {})", - escape_markdown_text(&person.name), - attributes - ) - }) - .collect::>() - .join(", ") - }; - let account_boundary = if fact.account.chars().count() - == MAX_PUBLIC_EVENT_SUMMARY_CHARS - { - format!( - "\n- Account boundary: This immutable source account reaches the owned {}-character public-event summary limit; the audit shows the complete stored account and asserts nothing beyond it.", - MAX_PUBLIC_EVENT_SUMMARY_CHARS - ) - } else { - String::new() - }; - rendered.push_str(&format!( - "\n#### Fact {}\n\n- Exact committed account: {}{}\n- Assertion status: {}\n- Committed events: {}\n- Named people: {}\n- Institutions: {}\n- Populations: {}\n- Places: {}\n", - fact_index + 1, - escape_markdown_text(&fact.account), - account_boundary, - serde_json::to_value(&fact.assertion_status) - .ok() - .and_then(|value| value.as_str().map(str::to_owned)) - .unwrap_or_else(|| "invalid_assertion_status".into()), - escaped_join(&fact.event_ids), - named_people, - escaped_or_none(&fact.institutions), - escaped_or_none(&fact.populations), - escaped_or_none(&fact.places), - )); - } - } - } - rendered -} - -fn escaped_or_none(values: &[String]) -> String { - if values.is_empty() { - "None asserted".into() - } else { - escaped_join(values) - } -} - -fn escaped_join(values: &[String]) -> String { - values - .iter() - .map(|value| escape_markdown_text(value)) - .collect::>() - .join(", ") -} - -fn public_news_records(campaign: &Campaign) -> Result> { - let events = campaign - .events - .iter() - .map(|event| (event.id.as_str(), event)) - .collect::>(); - let mut news = campaign.news.iter().collect::>(); - news.sort_by(|left, right| right.at.cmp(&left.at).then_with(|| left.id.cmp(&right.id))); - let mut record_ids = BTreeSet::new(); - for issue in &news { - if !record_ids.insert(issue.id.as_str()) { - return Err(anyhow!("public news ledger repeats record ID {}", issue.id)); - } - } - news.into_iter() - .map(|issue| public_news_record(campaign, issue, &events)) - .collect() -} - -fn editorial_period_directory( - records: &[PublicRecordProjection], -) -> Vec { - const MAX_COMPLETED_HEADLINES_PER_PERIOD: usize = 12; - - let mut periods = BTreeMap::, (Vec, BTreeSet, usize)>::new(); - for record in records { - let entry = periods.entry(record.at).or_default(); - if record.facts.iter().any(|fact| { - fact.assertion_status == WorldNewspaperAssertionStatus::MaterialChangeCommitted - }) { - if entry.1.insert(record.headline.clone()) { - entry.0.push(record.headline.clone()); - } - } else { - entry.2 = entry.2.saturating_add(1); - } - } - periods - .into_iter() - .rev() - .map( - |(at, (completed_change_headlines, _, other_record_count))| { - let completed_change_count = completed_change_headlines.len(); - EditorialPeriodDirectoryEntry { - at, - completed_change_headlines: completed_change_headlines - .into_iter() - .take(MAX_COMPLETED_HEADLINES_PER_PERIOD) - .collect(), - completed_change_count, - other_record_count, - } - }, - ) - .collect() -} - -fn public_news_record( - campaign: &Campaign, - issue: &NewsIssue, - events: &BTreeMap<&str, &Event>, -) -> Result { - if issue.event_ids.is_empty() { - return Err(anyhow!("news item {} has no committed event", issue.id)); - } - let facts = issue - .event_ids - .iter() - .map(|event_id| { - let event = events - .get(event_id.as_str()) - .copied() - .ok_or_else(|| anyhow!("news item {} cites unknown event {event_id}", issue.id))?; - if !event.public_channels.contains(&issue.channel) { - return Err(anyhow!( - "news item {} uses channel absent from event {event_id}", - issue.id - )); - } - let summary = event.summary.trim().to_owned(); - Ok(WorldNewspaperSourceFact { - event_ids: vec![event.id.clone()], - assertion_status: event.public_assertion_status(), - account: summary.clone(), - named_people: event - .actor_ids - .iter() - .filter_map(|id| campaign.actors.get(id)) - .filter(|actor| summary_mentions_name(&summary, &actor.name)) - .map(|actor| WorldNewspaperNamedPerson { - name: actor.name.clone(), - supported_identity_attributes: Vec::new(), - }) - .collect(), - institutions: event - .institution_ids - .iter() - .filter_map(|id| campaign.institutions.get(id)) - .filter(|institution| summary_mentions_name(&summary, &institution.name)) - .map(|institution| institution.name.clone()) - .collect(), - populations: event - .gestalt_ids - .iter() - .filter_map(|id| campaign.gestalts.get(id)) - .filter(|gestalt| summary_mentions_name(&summary, &gestalt.name)) - .map(|gestalt| gestalt.name.clone()) - .collect(), - places: event - .location_ids - .iter() - .filter_map(|id| campaign.locations.get(id)) - .filter(|place| { - event.location_ids.len() == 1 - || summary_mentions_name(&summary, &place.name) - }) - .map(|place| place.name.clone()) - .collect(), - }) - }) - .collect::>>()?; - if facts.iter().any(|fact| fact.account.is_empty()) { - return Err(anyhow!("news item {} cites an empty event", issue.id)); - } - Ok(PublicRecordProjection { - record_id: issue.id.clone(), - at: issue.at, - channel: issue.channel.clone(), - headline: issue.headline.clone(), - reliability: issue.reliability.clone(), - facts, - }) -} - -fn summary_mentions_name(summary: &str, name: &str) -> bool { - let summary = summary.to_lowercase(); - let name = name.to_lowercase(); - if name.is_empty() { - return false; - } - summary.match_indices(&name).any(|(start, matched)| { - let before = summary[..start].chars().next_back(); - let after = summary[start + matched.len()..].chars().next(); - before.is_none_or(|character| !character.is_alphanumeric()) - && after.is_none_or(|character| !character.is_alphanumeric()) - }) -} - -fn public_records_for_ids<'a>( - records: &'a [PublicRecordProjection], - record_ids: &BTreeSet, -) -> Vec<&'a PublicRecordProjection> { - records - .iter() - .filter(|record| record_ids.contains(&record.record_id)) - .collect() -} - -fn source_json_for_agenda( - records: &[PublicRecordProjection], - agenda: Option<&WorldNewspaperEditorialAgenda>, -) -> Result { - let record_ids = agenda.map_or_else( - || { - records - .iter() - .map(|record| record.record_id.clone()) - .collect() - }, - |agenda| { - agenda - .story_pitches - .iter() - .flat_map(|pitch| pitch.citations.iter().cloned()) - .collect() - }, - ); - Ok(serde_json::to_string_pretty(&public_records_for_ids( - records, - &record_ids, - ))?) -} - -fn source_json_for_copy_queries( - records: &[PublicRecordProjection], - agenda: &WorldNewspaperEditorialAgenda, - copy_desk: &WorldNewspaperCopyDeskReport, -) -> Result { - let mut record_ids = BTreeSet::new(); - for query in ©_desk.queries { - let pitch = agenda - .story_pitches - .get(usize::from(query.article_index)) - .ok_or_else(|| anyhow!("copy-desk query names an unknown article"))?; - record_ids.extend(pitch.citations.iter().cloned()); - } - Ok(serde_json::to_string_pretty(&public_records_for_ids( - records, - &record_ids, - ))?) -} - -fn validate_editorial_draft( - records: &[PublicRecordProjection], - draft: &EditorialPageDraft, - max_articles: usize, -) -> Result<()> { - if draft.articles.is_empty() || draft.articles.len() > max_articles.min(records.len()) { - return Err(anyhow!("editorial page exceeded its story budget")); - } - let mut headlines = BTreeSet::new(); - for (index, article) in draft.articles.iter().enumerate() { - validate_editorial_article(records, article, index)?; - if !headlines.insert(article.headline.to_lowercase()) { - return Err(anyhow!("front page repeats a headline")); - } - } - Ok(()) -} - -fn validate_editorial_article( - records: &[PublicRecordProjection], - article: &EditorialArticleDraft, - index: usize, -) -> Result<()> { - if (index == 0 && article.section != "Front Page") - || (index > 0 && article.section == "Front Page") - || !ALLOWED_SECTIONS.contains(&article.section.as_str()) - { - return Err(anyhow!("article {index} used an invalid section")); - } - validate_single_line(&article.headline, 100, "headline")?; - validate_single_line(&article.deck, 220, "deck")?; - validate_single_line(&article.byline, 60, "byline")?; - if article.headline.ends_with('…') || article.headline.ends_with("...") { - return Err(anyhow!("article {index} headline ends in truncation")); - } - if article.headline.eq_ignore_ascii_case(&article.deck) { - return Err(anyhow!("article {index} deck repeats its headline")); - } - let known_sources = records - .iter() - .map(|record| record.record_id.as_str()) - .collect::>(); - for citation in selected_record_ids(&article.citations, &format!("article {index}"))? { - if !known_sources.contains(citation) { - return Err(anyhow!( - "article {index} cites unknown public record {citation}" - )); - } - } - let source_datelines = records - .iter() - .map(|record| { - ( - record.record_id.as_str(), - record - .facts - .iter() - .flat_map(|fact| fact.places.iter().map(String::as_str)) - .collect::>(), - ) - }) - .collect::>(); - let cited_dateline_supported = article - .citations - .iter() - .any(|citation| source_datelines[citation.as_str()].contains(article.dateline.as_str())); - let cited_place_available = article - .citations - .iter() - .any(|citation| !source_datelines[citation.as_str()].is_empty()); - if !article.dateline.is_empty() && !cited_dateline_supported { - return Err(anyhow!( - "article {index} invented or misattributed a dateline" - )); - } - if index == 0 && article.dateline.is_empty() && cited_place_available { - return Err(anyhow!( - "the lead article must use a cited source place as its dateline" - )); - } - if !(2..=5).contains(&article.paragraphs.len()) { - return Err(anyhow!( - "article {index} must contain two to five paragraphs" - )); - } - for paragraph in &article.paragraphs { - let text = paragraph.trim(); - if text != paragraph - || text.chars().count() < 40 - || text.chars().count() > 900 - || text.contains(['\r', '\n']) - { - return Err(anyhow!("article {index} contains a malformed paragraph")); - } - if article.citations.iter().any(|citation| { - records - .iter() - .find(|record| record.record_id == *citation) - .is_some_and(|record| record.facts.iter().any(|fact| fact.account.trim() == text)) - }) { - return Err(anyhow!( - "article {index} printed a source summary as final copy" - )); - } - } - validate_no_reader_plumbing( - &format!( - "{} {} {} {} {}", - article.headline, - article.deck, - article.byline, - article.dateline, - article.paragraphs.join(" ") - ), - &format!("article {index}"), - ) -} - -fn validate_no_reader_plumbing(value: &str, label: &str) -> Result<()> { - let reader_copy = value.to_lowercase(); - for leaked in [ - "world revision", - "event:", - "strategic:", - "committed public channel", - "selected action", - "supplied gestalt", - "resolution cover", - "source_news_id", - "source news id", - ] { - if reader_copy.contains(leaked) { - return Err(anyhow!("{label} leaked newsroom plumbing: {leaked}")); - } - } - Ok(()) -} - -fn validate_single_line(value: &str, max_chars: usize, label: &str) -> Result<()> { - if value.trim().is_empty() - || value.trim() != value - || value.chars().count() > max_chars - || value.contains(['\r', '\n']) - || value.contains('`') - || value.starts_with('#') - { - return Err(anyhow!("{label} is not valid reader-facing copy")); - } - Ok(()) -} - -fn validate_grounding_finding_target( - draft: &EditorialPageDraft, - finding: &WorldNewspaperGroundingFinding, -) -> Result<()> { - let occurrence_count = - article_passage_occurrence_count(draft, finding.article_index, &finding.claim_or_phrase) - .ok_or_else(|| anyhow!("copy desk returned an invalid article index"))?; - if occurrence_count != 1 { - return Err(anyhow!( - "copy-desk claim_or_phrase must be one exact contiguous phrase occurring once in the named article" - )); - } - Ok(()) -} - -fn article_passage_occurrence_count( - draft: &EditorialPageDraft, - article_index: u16, - passage: &str, -) -> Option { - let article = draft.articles.get(usize::from(article_index))?; - Some( - [ - article.headline.as_str(), - article.deck.as_str(), - article.dateline.as_str(), - ] - .into_iter() - .chain(article.paragraphs.iter().map(String::as_str)) - .map(|text| text.match_indices(passage).count()) - .sum::(), - ) -} - -fn lower_editorial_page( - campaign: &Campaign, - title: String, - records: &[PublicRecordProjection], - editorial_agenda: Option, - draft: EditorialPageDraft, - receipts: &[ModelStageReceipt], -) -> Result { - let source_map = records - .iter() - .map(|record| (record.record_id.as_str(), record)) - .collect::>(); - let selected_record_ids = draft - .articles - .iter() - .flat_map(|article| article.citations.iter().cloned()) - .collect::>(); - let citation_labels = records - .iter() - .filter(|record| selected_record_ids.contains(&record.record_id)) - .enumerate() - .map(|(index, record)| (record.record_id.as_str(), (index + 1).to_string())) - .collect::>(); - let mut articles = Vec::with_capacity(draft.articles.len()); - for (index, article) in draft.articles.into_iter().enumerate() { - let selected_records = article - .citations - .iter() - .map(|record_id| { - source_map - .get(record_id.as_str()) - .copied() - .ok_or_else(|| anyhow!("editorial lowering lost public record {record_id}")) - }) - .collect::>>()?; - let audit_sources = selected_records - .iter() - .map(|record| WorldNewspaperSourceCitation { - citation: citation_labels[record.record_id.as_str()].clone(), - source_news_ids: vec![record.record_id.clone()], - source_times: vec![record.at], - source_channels: vec![record.channel.clone()], - source_reliability: vec![record.reliability.clone()], - facts: record.facts.clone(), - }) - .collect::>(); - let identity = rmp_serde::to_vec_named(&( - NEWSROOM_CONTRACT_VERSION, - campaign.id, - campaign.revision, - index, - &article.section, - &article.headline, - &article.deck, - &article.byline, - &article.dateline, - &article.paragraphs, - &audit_sources, - ))?; - articles.push(WorldNewspaperArticle { - id: format!("article:sha256:{:x}", Sha256::digest(identity)), - section: article.section, - headline: article.headline, - deck: article.deck, - byline: article.byline, - dateline: (!article.dateline.is_empty()).then_some(article.dateline), - paragraphs: article.paragraphs, - sources: audit_sources, - }); - } - let receipt_ids = receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - let at = records - .iter() - .map(|record| record.at) - .max() - .unwrap_or(campaign.world_time); - let identity = rmp_serde::to_vec_named(&( - campaign.id, - campaign.revision, - &title, - EDITION_LABEL, - &editorial_agenda, - articles - .iter() - .map(|article| &article.id) - .collect::>(), - &receipt_ids, - ))?; - Ok(WorldNewspaperIssue { - schema: "ghostlight.world_newspaper_issue.v3".into(), - id: format!("newspaper:sha256:{:x}", Sha256::digest(identity)), - title, - edition_label: EDITION_LABEL.into(), - at, - source_world_revision: campaign.revision, - lead_article_id: articles.first().map(|article| article.id.clone()), - editorial_agenda, - articles, - editorial_receipt_ids: receipt_ids, - }) -} - -fn publication_task_binding( - campaign: &Campaign, - title: &str, - voice: &str, - newsroom: &WorldNewspaperNewsroom, - max_articles: usize, -) -> Result { - let bytes = rmp_serde::to_vec_named(&( - NEWSROOM_CONTRACT_VERSION, - campaign.id, - campaign.revision, - title, - voice, - newsroom, - max_articles, - ))?; - Ok(format!( - "campaign:{}:revision:{}:newspaper-task:sha256:{:x}", - campaign.id, - campaign.revision, - Sha256::digest(bytes) - )) -} - -fn editorial_binding( - campaign: &Campaign, - title: &str, - voice: &str, - newsroom: &WorldNewspaperNewsroom, - max_articles: usize, - records: &[PublicRecordProjection], -) -> Result { - let bytes = rmp_serde::to_vec_named(&( - NEWSROOM_CONTRACT_VERSION, - campaign.id, - campaign.revision, - campaign.world_time, - title, - voice, - newsroom, - max_articles, - records, - ))?; - Ok(format!( - "campaign:{}:revision:{}:newspaper:sha256:{:x}", - campaign.id, - campaign.revision, - Sha256::digest(bytes) - )) -} - -fn empty_issue_id( - campaign: &Campaign, - title: &str, - newsroom: &WorldNewspaperNewsroom, -) -> Result { - let identity = rmp_serde::to_vec_named(&( - NEWSROOM_CONTRACT_VERSION, - campaign.id, - campaign.revision, - title, - newsroom, - "no-edition", - ))?; - Ok(format!("newspaper:sha256:{:x}", Sha256::digest(identity))) -} - -fn mark_semantic_invalid(receipt: &mut ModelStageReceipt, error: &anyhow::Error) { - let error: String = error.to_string().chars().take(1_000).collect(); - let original_binding = receipt.snapshot_binding.clone(); - let source_chain_digest = Sha256::digest( - rmp_serde::to_vec_named(&receipt.source_receipt_ids) - .expect("model receipt source chains must be serializable"), - ); - receipt.rebind_snapshot(format!( - "{original_binding}:semantic-invalid:sources:sha256:{source_chain_digest:x}:error:sha256:{:x}", - Sha256::digest(error.as_bytes()), - )); - receipt.validation_result = "semantic_invalid".into(); - receipt.local_validation_error = Some(error); -} - -fn composition_failure( - message: impl Into, - model_receipts: Vec, -) -> anyhow::Error { - anyhow::Error::new(WorldNewspaperCompositionFailure { - message: message.into(), - model_receipts, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use async_trait::async_trait; - use std::{collections::VecDeque, sync::Mutex}; - - struct ScriptedNewspaperModel { - responses: Mutex>, - requests: Mutex>, - } - - impl ScriptedNewspaperModel { - fn new(responses: impl IntoIterator) -> Self { - Self { - responses: Mutex::new(responses.into_iter().map(str::to_owned).collect()), - requests: Mutex::new(Vec::new()), - } - } - - fn requests(&self) -> Vec { - self.requests.lock().unwrap().clone() - } - } - - #[async_trait] - impl ModelPort for ScriptedNewspaperModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.requests.lock().unwrap().push(request.clone()); - if request.stage == "newspaper_narrative_selection_agent_action" - && request.lived_stream.contains("candidate_digest") - { - let digest = request - .lived_stream - .match_indices("sha256:") - .filter_map(|(index, _)| request.lived_stream.get(index..index + 71)) - .filter(|candidate| { - candidate[7..] - .chars() - .all(|character| character.is_ascii_hexdigit()) - }) - .last() - .ok_or_else(|| anyhow!("fixture transcript omitted candidate digest"))?; - return Ok(serde_json::json!({ - "command":{ - "tool":"commit_agenda", - "candidate_digest":digest, - } - }) - .to_string()); - } - let response = self - .responses - .lock() - .unwrap() - .pop_front() - .ok_or_else(|| anyhow!("fixture newspaper model exhausted"))?; - Ok(response) - } - - fn provider(&self) -> &'static str { - "newspaper-fixture" - } - } - - fn campaign_with_news() -> Campaign { - let mut campaign = crate::kernel::tests::campaign(); - campaign.revision = 3; - let summary = "The Thorn Court admits its royal seal was pawned to pay a dragon's gambling debt, then dismisses the treasurer who carried the confession into open court."; - campaign.events.push(Event { - id: "event:seal-scandal".into(), - at: campaign.world_time, - kind: "institution_action".into(), - summary: summary.into(), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec!["room".into()], - public_channels: vec!["court broadsheet".into()], - }); - campaign.news.push(NewsIssue { - id: "news:seal-scandal".into(), - at: campaign.world_time, - channel: "court broadsheet".into(), - headline: crate::domain::committed_news_headline(summary), - event_ids: vec!["event:seal-scandal".into()], - reliability: "committed public channel".into(), - }); - campaign - } - - fn campaign_with_two_news() -> Campaign { - let mut campaign = campaign_with_news(); - campaign.locations.insert( - "yard".into(), - crate::domain::Location { - id: "yard".into(), - name: "Yard".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - ); - let summary = "The palace bell keeper announces that the west gate will close at moonrise while masons replace its cracked hinge."; - campaign.events.push(Event { - id: "event:west-gate".into(), - at: campaign.world_time, - kind: "institution_action".into(), - summary: summary.into(), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec!["yard".into()], - public_channels: vec!["court broadsheet".into()], - }); - campaign.news.push(NewsIssue { - id: "news:west-gate".into(), - at: campaign.world_time, - channel: "court broadsheet".into(), - headline: crate::domain::committed_news_headline(summary), - event_ids: vec!["event:west-gate".into()], - reliability: "committed public channel".into(), - }); - campaign - } - - fn campaign_with_archive_news() -> Campaign { - let mut campaign = crate::kernel::tests::campaign(); - campaign.revision = 45; - for index in 0..45 { - let at = campaign.world_time + chrono::Duration::minutes(index); - let summary = if index == 0 { - "The oldest public dossier records the speaking child, severed delegation hands, failed grain pumps, a legion refusal, and occupied toll bridges." - .to_owned() - } else { - format!( - "Public aftermath dossier {index} records one distinct administrative response." - ) - }; - let event_id = format!("event:archive:{index:02}"); - campaign.events.push(Event { - id: event_id.clone(), - at, - kind: "public_notice".into(), - summary: summary.clone(), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec!["room".into()], - public_channels: vec!["court broadsheet".into()], - }); - campaign.news.push(NewsIssue { - id: format!("news:archive:{index:02}"), - at, - channel: "court broadsheet".into(), - headline: crate::domain::committed_news_headline(&summary), - event_ids: vec![event_id], - reliability: "committed public channel".into(), - }); - } - campaign - } - - fn campaign_with_typed_and_duplicate_news() -> Campaign { - let mut campaign = campaign_with_news(); - let duplicate = campaign.events.last().unwrap().clone(); - campaign.events.push(Event { - id: "strategic:3:activity-outcome:relation-delta".into(), - at: campaign.world_time, - kind: "strategic_activity_outcome".into(), - summary: - "An action by the court strains the command tie between the Crown and its auditors." - .into(), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec!["room".into()], - public_channels: vec!["court broadsheet".into()], - }); - campaign.news.push(NewsIssue { - id: "news:relation-delta".into(), - at: campaign.world_time, - channel: "court broadsheet".into(), - headline: "Relation delta".into(), - event_ids: vec!["strategic:3:activity-outcome:relation-delta".into()], - reliability: "committed public channel".into(), - }); - campaign.events.push(Event { - id: "strategic:3:gestalt:auditors".into(), - at: campaign.world_time, - kind: "gestalt_action".into(), - summary: - "The auditors take up a new public demand: replace crown tallies with an elected grain compact." - .into(), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec!["room".into()], - public_channels: vec!["court broadsheet".into()], - }); - campaign.news.push(NewsIssue { - id: "news:pressure-transition".into(), - at: campaign.world_time, - channel: "court broadsheet".into(), - headline: "Pressure transition".into(), - event_ids: vec!["strategic:3:gestalt:auditors".into()], - reliability: "committed public channel".into(), - }); - campaign.events.push(Event { - id: "event:seal-scandal-duplicate".into(), - ..duplicate - }); - campaign.news.push(NewsIssue { - id: "news:seal-scandal-duplicate".into(), - at: campaign.world_time, - channel: "court broadsheet".into(), - headline: "Duplicate desk notice".into(), - event_ids: vec!["event:seal-scandal-duplicate".into()], - reliability: "committed public channel".into(), - }); - campaign - } - - const QUERY_ALL_RECORDS: &str = r#"{"command":{"tool":"query_public_records","terms":[],"match_terms":"all","entity_names":[],"assertion_statuses":[],"channels":[],"order":"newest","cursor":null,"limit":24}}"#; - const QUERY_FOUNDING_CRISIS: &str = r#"{"command":{"tool":"query_public_records","terms":["speaking child","severed delegation hands","failed grain pumps"],"match_terms":"any","entity_names":[],"assertion_statuses":[],"channels":[],"order":"oldest","cursor":null,"limit":24}}"#; - const ONE_STORY_AGENDA: &str = r#"{"command":{"tool":"propose_agenda","issue_shape":"special_issue","issue_shape_rationale":"The missing royal seal reorganizes public trust in court custody.","dominant_throughline":"The court made its private gambling debt a public crisis of custody and punished the official who exposed it.","reader_stake":"Readers must decide whether dismissal protects the seal or merely the court from its own confession.","story_pitches":[{"lead":true,"section":"Front Page","journalist_id":"aven-tarl","narrative_function":"lead_chronology","context_role":"owns_issue_chronology","assignment_reason":"Aven's court beat and appetite for status reversal fit the scandal's central chronology.","citations":["news:seal-scandal"],"focus_citation":"news:seal-scandal","narrative_claim":"The pawned royal seal and the treasurer's dismissal are one scandal.","tension":"The court admits the loss while directing the immediate consequence at the bearer of that admission.","public_question":"Who is being held accountable for the missing seal?","conflict_axis":null}]}}"#; - const TWO_STORY_AGENDA: &str = r#"{"command":{"tool":"propose_agenda","issue_shape":"special_issue","issue_shape_rationale":"Failures of custody at court and gate reorganize public access and confidence.","dominant_throughline":"Court custody fails at both the royal seal and the western gate.","reader_stake":"Readers depend on institutions that announce damage only after access or authority has already been compromised.","story_pitches":[{"lead":true,"section":"Front Page","journalist_id":"aven-tarl","narrative_function":"lead_chronology","context_role":"owns_issue_chronology","assignment_reason":"Aven owns the court chronology and its status reversal.","citations":["news:seal-scandal"],"focus_citation":"news:seal-scandal","narrative_claim":"The pawned seal and dismissal are the court's crisis of custody.","tension":"The confession exposes the loss while the treasurer absorbs the immediate institutional consequence.","public_question":"Who is being held accountable for the missing seal?","conflict_axis":null},{"lead":false,"section":"Dispatches","journalist_id":"lysa-fen","narrative_function":"consequence","context_role":"assumes_issue_chronology","assignment_reason":"Lysa's border beat tests how the custody crisis changes movement at the gate.","citations":["news:west-gate"],"focus_citation":"news:west-gate","narrative_claim":"The gate closure is a practical echo of neglected custody.","tension":"A cracked hinge will close a route at moonrise while travellers wait for a reopening time.","public_question":"How long will the western route remain closed?","conflict_axis":null}]}}"#; - const ACCEPTED_STORY_ACTION: &str = r#"{"tool":"file_story","headline":"Court Sells the Crown's Seal, Then the Treasurer","deck":"A gambling debt reaches the throne room and leaves one official carrying the blame.","dateline":"Room","paragraphs":["The Thorn Court has admitted that its royal seal was pawned to cover a dragon's gambling debt, a confession that turns private embarrassment into a public question of custody.","The treasurer who delivered that admission in open court was dismissed soon afterward. The court has explained the firing; it has not made the seal any less pawned."]}"#; - const MALFORMED_LYSA_STORY_ACTION: &str = r#"{"tool":"file_story","headline":"Gate Trouble","deck":"The western route will close at moonrise.","dateline":"Yard","paragraphs":["Too short.","Still short."]}"#; - const ACCEPTED_LYSA_STORY_ACTION: &str = r#"{"tool":"file_story","headline":"West Gate to Close at Moonrise","deck":"Masons will replace a cracked hinge after the palace bell keeper's warning.","dateline":"Yard","paragraphs":["Officials warn the west gate is unsafe, and the palace bell keeper says it will close at moonrise while masons replace its cracked hinge.","Travellers using the gate have been told when it will close, though no reopening hour was included in the announcement."]}"#; - const ACCEPTED_PAGE: &str = r#"{"articles":[{"section":"Front Page","headline":"Court Sells the Crown's Seal, Then the Treasurer","deck":"A gambling debt reaches the throne room and leaves one official carrying the blame.","byline":"Aven Tarl","dateline":"Room","citations":["news:seal-scandal"],"paragraphs":["The Thorn Court has admitted that its royal seal was pawned to cover a dragon's gambling debt, a confession that turns private embarrassment into a public question of custody.","The treasurer who delivered that admission in open court was dismissed soon afterward. The court has explained the firing; it has not made the seal any less pawned."]}]}"#; - const TWO_ARTICLE_PAGE: &str = r#"{"articles":[{"section":"Front Page","headline":"Court Sells the Crown's Seal, Then the Treasurer","deck":"A gambling debt reaches the throne room and leaves one official carrying the blame.","byline":"Aven Tarl","dateline":"Room","citations":["news:seal-scandal"],"paragraphs":["The Thorn Court has admitted that its royal seal was pawned to cover a dragon's gambling debt, a confession that turns private embarrassment into a public question of custody.","The treasurer who delivered that admission in open court was dismissed soon afterward. The court has explained the firing; it has not made the seal any less pawned."]},{"section":"Dispatches","headline":"West Gate to Close at Moonrise","deck":"Masons will replace a cracked hinge after the palace bell keeper's warning.","byline":"Lysa Fen","dateline":"Yard","citations":["news:west-gate"],"paragraphs":["Officials warn the west gate is unsafe, and the palace bell keeper says it will close at moonrise while masons replace its cracked hinge.","Travellers using the gate have been told when it will close, though no reopening hour was included in the announcement."]}]}"#; - const UNCHANGED_NIGHT_CLOSE: &str = - r#"{"tool":"submit_close","addressed_query_indices":[],"rewrites":[]}"#; - const QUERY_DECK_CLOSE: &str = r#"{"tool":"submit_close","addressed_query_indices":[0],"rewrites":[{"article_index":0,"headline":"Court Sells the Crown's Seal, Then the Treasurer","deck":"The court admits the pawned seal and dismisses the official who carried the confession.","dateline":"Room","paragraphs":["The Thorn Court has admitted that its royal seal was pawned to cover a dragon's gambling debt, a confession that turns private embarrassment into a public question of custody.","The treasurer who delivered that admission in open court was dismissed soon afterward. The court has explained the firing; it has not made the seal any less pawned."]}]}"#; - const ACCEPTING_COPY_DESK: &str = r#"{"assessment":"The copy is fully supported by its cited public source and reads as attributed court reporting.","queries":[]}"#; - - #[test] - fn copy_desk_schema_owns_the_complete_finding_category_set() { - let schema = serde_json::to_string(&schema_for!(WorldNewspaperCopyDeskReport)).unwrap(); - assert!(schema.contains("\"queries\"")); - assert!(!schema.contains("\"accepted\"")); - for category in [ - "unsupported_fact", - "unearned_attribution", - "procedural_leakage", - "mechanical_copy", - ] { - assert!(schema.contains(category)); - } - } - - #[test] - fn copy_desk_may_lodge_distinct_objections_to_one_exact_phrase() { - let draft: EditorialPageDraft = serde_json::from_str(ACCEPTED_PAGE).unwrap(); - let phrase = - "A gambling debt reaches the throne room and leaves one official carrying the blame."; - let report = WorldNewspaperCopyDeskReport { - assessment: "The deck has both a factual and a copy-level defect.".into(), - queries: vec![ - WorldNewspaperGroundingFinding { - article_index: 0, - category: WorldNewspaperGroundingCategory::UnsupportedFact, - claim_or_phrase: phrase.into(), - reason: "The cited record does not locate the debt in the throne room.".into(), - }, - WorldNewspaperGroundingFinding { - article_index: 0, - category: WorldNewspaperGroundingCategory::MechanicalCopy, - claim_or_phrase: phrase.into(), - reason: "The deck states blame abstractly instead of naming the court action." - .into(), - }, - ], - }; - - validate_copy_desk_report(&draft, &report).unwrap(); - } - - #[test] - fn narrative_workbench_owns_lead_and_allows_shared_foundational_records() { - let records = public_news_records(&campaign_with_two_news()).unwrap(); - let invalid = WorldNewspaperEditorialAgenda { - issue_shape: WorldNewspaperIssueShape::SpecialIssue, - issue_shape_rationale: "Both failures reorganize public trust in custody.".into(), - dominant_throughline: "Two failures of court custody.".into(), - reader_stake: "Readers depend on both institutions.".into(), - story_pitches: vec![ - WorldNewspaperStoryPitch { - lead: false, - section: "Front Page".into(), - journalist_id: "aven-tarl".into(), - narrative_function: WorldNewspaperNarrativeFunction::LeadChronology, - context_role: WorldNewspaperContextRole::OwnsIssueChronology, - assignment_reason: "Aven owns the court chronology.".into(), - citations: vec!["news:seal-scandal".into()], - focus_citation: "news:seal-scandal".into(), - narrative_claim: "The pawned seal opens the custody crisis.".into(), - tension: "Admission and dismissal point in different directions.".into(), - public_question: "Who answers for the seal?".into(), - conflict_axis: None, - }, - WorldNewspaperStoryPitch { - lead: true, - section: "Dispatches".into(), - journalist_id: "lysa-fen".into(), - narrative_function: WorldNewspaperNarrativeFunction::Consequence, - context_role: WorldNewspaperContextRole::AssumesIssueChronology, - assignment_reason: "Lysa tests the consequence at the gate.".into(), - citations: vec!["news:seal-scandal".into()], - focus_citation: "news:seal-scandal".into(), - narrative_claim: "The gate repeats the pattern.".into(), - tension: "Access closes while repair begins.".into(), - public_question: "When will the route reopen?".into(), - conflict_axis: None, - }, - ], - }; - - assert!( - validate_editorial_agenda(&records, &canopy_ledger_newsroom(), &invalid, 4) - .unwrap_err() - .to_string() - .contains("exactly its first pitch as lead") - ); - - let agenda: NarrativeSelectionAction = serde_json::from_str(TWO_STORY_AGENDA).unwrap(); - let NarrativeSelectionCommand::ProposeAgenda { - issue_shape, - issue_shape_rationale, - dominant_throughline, - reader_stake, - story_pitches, - } = agenda.command - else { - panic!("fixture must submit an agenda") - }; - let admitted = WorldNewspaperEditorialAgenda { - issue_shape, - issue_shape_rationale, - dominant_throughline, - reader_stake, - story_pitches, - }; - validate_editorial_agenda(&records, &canopy_ledger_newsroom(), &admitted, 4).unwrap(); - let mut two_chronologies = admitted.clone(); - two_chronologies.story_pitches[1].context_role = - WorldNewspaperContextRole::OwnsIssueChronology; - assert!( - validate_editorial_agenda(&records, &canopy_ledger_newsroom(), &two_chronologies, 4,) - .unwrap_err() - .to_string() - .contains("only its lead ownership of the shared chronology") - ); - let mut general = admitted.clone(); - general.issue_shape = WorldNewspaperIssueShape::GeneralIssue; - general.issue_shape_rationale = - "The court scandal and gate repair remain independent public concerns.".into(); - general.story_pitches[0].narrative_function = - WorldNewspaperNarrativeFunction::IndependentBeat; - general.story_pitches[0].context_role = WorldNewspaperContextRole::SelfContained; - general.story_pitches[1].narrative_function = - WorldNewspaperNarrativeFunction::IndependentBeat; - general.story_pitches[1].context_role = WorldNewspaperContextRole::SelfContained; - validate_editorial_agenda(&records, &canopy_ledger_newsroom(), &general, 4).unwrap(); - general.story_pitches[1].context_role = WorldNewspaperContextRole::AssumesIssueChronology; - assert!( - validate_editorial_agenda(&records, &canopy_ledger_newsroom(), &general, 4) - .unwrap_err() - .to_string() - .contains("general-issue stories must own only their independent context") - ); - let mut duplicate = admitted.clone(); - duplicate.story_pitches[1] - .citations - .push("news:seal-scandal".into()); - validate_editorial_agenda(&records, &canopy_ledger_newsroom(), &duplicate, 4).unwrap(); - let mut repeated_within_pitch = admitted.clone(); - repeated_within_pitch.story_pitches[0] - .citations - .push("news:seal-scandal".into()); - assert!( - validate_editorial_agenda( - &records, - &canopy_ledger_newsroom(), - &repeated_within_pitch, - 4, - ) - .unwrap_err() - .to_string() - .contains("repeats a public record ID") - ); - - let mut widened: EditorialPageDraft = serde_json::from_str(ACCEPTED_PAGE).unwrap(); - widened.articles[0].citations = vec!["news:west-gate".into()]; - assert!( - validate_editorial_alignment( - &widened, - &canopy_ledger_newsroom(), - &WorldNewspaperEditorialAgenda { - issue_shape: admitted.issue_shape, - issue_shape_rationale: admitted.issue_shape_rationale.clone(), - dominant_throughline: admitted.dominant_throughline.clone(), - reader_stake: admitted.reader_stake.clone(), - story_pitches: vec![admitted.story_pitches[0].clone()], - }, - ) - .unwrap_err() - .to_string() - .contains("admitted citation grouping") - ); - } - - #[tokio::test] - async fn narrative_workbench_queries_foundational_context_by_stable_record_id() { - let records = public_news_records(&campaign_with_archive_news()).unwrap(); - let newsroom = canopy_ledger_newsroom(); - assert_eq!(records.len(), 45); - assert!( - records - .iter() - .any(|record| record.facts[0].account.contains("speaking child")) - ); - let mut tool = NarrativeSelectionWorkbench { - records: &records, - newsroom: &newsroom, - max_articles: 3, - visible_record_ids: BTreeSet::new(), - completed_queries: BTreeSet::new(), - pending_agenda: None, - }; - let initial_schema = tool.action_schema().unwrap().to_string(); - assert!(initial_schema.contains("propose_agenda")); - assert!(initial_schema.contains("commit_agenda")); - assert!(initial_schema.contains("fetch_public_records")); - - let retrieval = tool - .invoke( - NarrativeSelectionAction { - command: NarrativeSelectionCommand::QueryPublicRecords { - terms: vec!["speaking child".into()], - match_terms: PublicRecordTermMatch::All, - entity_names: Vec::new(), - assertion_statuses: Vec::new(), - channels: Vec::new(), - order: PublicRecordOrder::Oldest, - cursor: None, - limit: 24, - }, - }, - &ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }, - ) - .await; - let ModelAgentToolOutcome::Continue { observation, .. } = retrieval else { - panic!("public-record query must continue the same agent run") - }; - let NarrativeSelectionFinding::QueryResult { - records: found, - next_cursor, - } = observation - else { - panic!("query must return exact public records") - }; - assert_eq!(found.len(), 1); - assert_eq!(found[0].record_id, "news:archive:00"); - assert!(found[0].facts[0].account.contains("speaking child")); - assert!(next_cursor.is_none()); - assert_eq!(tool.action_schema().unwrap().to_string(), initial_schema); - let bounded_context = serde_json::to_string(&tool.context()).unwrap(); - assert!(bounded_context.contains("news:archive:00")); - assert!(!bounded_context.contains("\"facts\"")); - assert!(!bounded_context.contains("\"assertion_status\"")); - - let exact_fetch = tool.fetch_records(vec!["news:archive:00".into()]).unwrap(); - assert!(matches!( - exact_fetch, - NarrativeSelectionFinding::QueryResult { records, next_cursor } - if records.len() == 1 - && records[0].facts[0].account.contains("speaking child") - && next_cursor.is_none() - )); - - let ModelAgentToolOutcome::Rejected { finding, .. } = tool - .invoke( - NarrativeSelectionAction { - command: NarrativeSelectionCommand::CommitAgenda { - candidate_digest: format!("sha256:{}", "0".repeat(64)), - }, - }, - &ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }, - ) - .await - else { - panic!("an unreviewed agenda must not be committable") - }; - assert!(matches!( - finding, - NarrativeSelectionFinding::AgendaRejected { reason } - if reason.contains("requires one reviewed proposal") - )); - - let action = NarrativeSelectionAction { - command: NarrativeSelectionCommand::ProposeAgenda { - issue_shape: WorldNewspaperIssueShape::SpecialIssue, - issue_shape_rationale: "The founding rupture still organizes its aftermath.".into(), - dominant_throughline: "The original crisis survived its administrative aftermath." - .into(), - reader_stake: "Readers still bear the consequences of the founding rupture.".into(), - story_pitches: vec![WorldNewspaperStoryPitch { - lead: true, - section: "Front Page".into(), - journalist_id: "mera-quill".into(), - narrative_function: WorldNewspaperNarrativeFunction::LeadChronology, - context_role: WorldNewspaperContextRole::OwnsIssueChronology, - assignment_reason: "Mera keeps the lived cost ahead of the paperwork.".into(), - citations: vec!["news:archive:00".into()], - focus_citation: "news:archive:00".into(), - narrative_claim: "The oldest dossier is the fact later notices avoid.".into(), - tension: "Institutions administer consequences without resolving the cause." - .into(), - public_question: "Who benefits when the founding rupture leaves the page?" - .into(), - conflict_axis: None, - }], - }, - }; - let ModelAgentToolOutcome::Continue { observation, .. } = tool - .invoke( - action, - &ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }, - ) - .await - else { - panic!("queried foundational record must enter editorial review") - }; - let NarrativeSelectionFinding::AgendaProposed { - candidate_digest, - front_page, - below_fold, - .. - } = observation - else { - panic!("proposal must return a front-page proof") - }; - assert_eq!(front_page.focus_record.record_id, "news:archive:00"); - assert!(below_fold.is_empty()); - assert!( - tool.action_schema() - .unwrap() - .to_string() - .contains("commit_agenda") - ); - - tool.fetch_records(vec!["news:archive:00".into()]).unwrap(); - let ModelAgentToolOutcome::Rejected { finding, .. } = tool - .invoke( - NarrativeSelectionAction { - command: NarrativeSelectionCommand::CommitAgenda { - candidate_digest: candidate_digest.clone(), - }, - }, - &ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }, - ) - .await - else { - panic!("new research must retire the previously reviewed agenda") - }; - assert!(matches!( - finding, - NarrativeSelectionFinding::AgendaRejected { reason } - if reason.contains("requires one reviewed proposal") - )); - - let revised_action = NarrativeSelectionAction { - command: NarrativeSelectionCommand::ProposeAgenda { - issue_shape: WorldNewspaperIssueShape::SpecialIssue, - issue_shape_rationale: "The founding rupture still organizes its aftermath.".into(), - dominant_throughline: - "The founding rupture still governs the administrative aftermath.".into(), - reader_stake: "Readers still bear the consequences of the founding rupture.".into(), - story_pitches: vec![WorldNewspaperStoryPitch { - lead: true, - section: "Front Page".into(), - journalist_id: "mera-quill".into(), - narrative_function: WorldNewspaperNarrativeFunction::LeadChronology, - context_role: WorldNewspaperContextRole::OwnsIssueChronology, - assignment_reason: "Mera keeps the lived cost ahead of the paperwork.".into(), - citations: vec!["news:archive:00".into()], - focus_citation: "news:archive:00".into(), - narrative_claim: - "The original crisis remains more consequential than its paperwork.".into(), - tension: "Institutions administer consequences without resolving the cause." - .into(), - public_question: "Who benefits when the founding rupture leaves the page?" - .into(), - conflict_axis: None, - }], - }, - }; - let ModelAgentToolOutcome::Continue { observation, .. } = tool - .invoke( - revised_action, - &ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }, - ) - .await - else { - panic!("a revised agenda must receive a new editorial review") - }; - let NarrativeSelectionFinding::AgendaProposed { - candidate_digest: revised_candidate_digest, - .. - } = observation - else { - panic!("revised proposal must return a front-page proof") - }; - assert_ne!(candidate_digest, revised_candidate_digest); - let ModelAgentToolOutcome::Rejected { finding, .. } = tool - .invoke( - NarrativeSelectionAction { - command: NarrativeSelectionCommand::CommitAgenda { - candidate_digest: candidate_digest.clone(), - }, - }, - &ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }, - ) - .await - else { - panic!("a superseded agenda digest must not be committable") - }; - assert!(matches!( - finding, - NarrativeSelectionFinding::AgendaRejected { reason } - if reason.contains("stale candidate") - )); - let ModelAgentToolOutcome::Accepted { output: agenda, .. } = tool - .invoke( - NarrativeSelectionAction { - command: NarrativeSelectionCommand::CommitAgenda { - candidate_digest: revised_candidate_digest, - }, - }, - &ModelAgentToolContext { - source_receipt_ids: Vec::new(), - current_model_receipt: None, - }, - ) - .await - else { - panic!("reviewed proposal must be committable") - }; - let editor_desk = source_json_for_agenda(&records, Some(&agenda)).unwrap(); - assert!(editor_desk.contains("\"record_id\": \"news:archive:00\"")); - assert!(!editor_desk.contains("news:archive:44")); - } - - #[test] - fn narrative_workbench_pages_the_complete_ledger_from_an_inspected_cursor() { - let records = public_news_records(&campaign_with_archive_news()).unwrap(); - let newsroom = canopy_ledger_newsroom(); - let mut tool = NarrativeSelectionWorkbench { - records: &records, - newsroom: &newsroom, - max_articles: 3, - visible_record_ids: BTreeSet::new(), - completed_queries: BTreeSet::new(), - pending_agenda: None, - }; - let query = |cursor| PublicRecordQuery { - terms: Vec::new(), - match_terms: PublicRecordTermMatch::All, - entity_names: Vec::new(), - assertion_statuses: Vec::new(), - channels: Vec::new(), - order: PublicRecordOrder::Oldest, - cursor, - limit: 24, - }; - - assert!(tool.query(query(Some("news:archive:24".into()))).is_err()); - let NarrativeSelectionFinding::QueryResult { - records: first_page, - next_cursor, - } = tool.query(query(None)).unwrap() - else { - panic!("first query must return a public-record page") - }; - assert_eq!(first_page.len(), 24); - assert_eq!(first_page[0].record_id, "news:archive:00"); - assert_eq!(first_page[23].record_id, "news:archive:23"); - assert_eq!(next_cursor.as_deref(), Some("news:archive:23")); - - let NarrativeSelectionFinding::QueryResult { - records: second_page, - next_cursor, - } = tool.query(query(next_cursor)).unwrap() - else { - panic!("second query must return a public-record page") - }; - assert_eq!(second_page.len(), 21); - assert_eq!(second_page[0].record_id, "news:archive:24"); - assert_eq!(second_page[20].record_id, "news:archive:44"); - assert!(next_cursor.is_none()); - } - - #[tokio::test] - async fn narrative_agent_queries_and_reviews_before_committing_an_agenda() { - let prepared = prepare_newspaper( - &campaign_with_archive_news(), - "The Canopy Ledger", - "Independent and pointed.", - &canopy_ledger_newsroom(), - 3, - ) - .unwrap(); - let model = ScriptedNewspaperModel::new([ - QUERY_FOUNDING_CRISIS, - r#"{"command":{"tool":"propose_agenda","issue_shape":"special_issue","issue_shape_rationale":"The founding rupture still organizes its administrative aftermath.","dominant_throughline":"The founding crisis survived its administrative aftermath.","reader_stake":"Readers still bear the consequences while institutions manage the paperwork.","story_pitches":[{"lead":true,"section":"Front Page","journalist_id":"mera-quill","narrative_function":"lead_chronology","context_role":"owns_issue_chronology","assignment_reason":"Mera's witness-first beat keeps the original lived rupture ahead of its paperwork.","citations":["news:archive:00"],"focus_citation":"news:archive:00","narrative_claim":"The original public record is the fact later notices cannot domesticate.","tension":"Administrative responses multiply while the founding rupture remains unresolved.","public_question":"Who benefits when the cause leaves the front page?","conflict_axis":null}]}}"#, - ]); - - let run = select_editorial_agenda(&model, &prepared, 3).await.unwrap(); - - assert_eq!(run.receipts.len(), 3); - assert_eq!(run.output.story_pitches.len(), 1); - assert_eq!(run.output.story_pitches[0].citations, ["news:archive:00"]); - let requests = model.requests(); - assert_eq!(requests.len(), 3); - assert!(requests[1].lived_stream.contains("news:archive:00")); - } - - #[tokio::test] - async fn assignment_editor_keeps_a_stable_prefix_without_replaying_old_record_bodies() { - let prepared = prepare_newspaper( - &campaign_with_two_news(), - "The Canopy Ledger", - "Independent and pointed.", - &canopy_ledger_newsroom(), - 3, - ) - .unwrap(); - let model = ScriptedNewspaperModel::new([QUERY_ALL_RECORDS, ONE_STORY_AGENDA]); - - select_editorial_agenda(&model, &prepared, 3).await.unwrap(); - - let requests = model.requests(); - assert_eq!(requests.len(), 3); - let stable_prefix = &requests[0].lived_stream; - assert!(stable_prefix.contains("STAFF BOOK")); - assert!(stable_prefix.contains("AGENT STEP: 1")); - assert!(requests[1..].iter().all(|request| { - request - .lived_stream - .starts_with(&format!("{stable_prefix}\n\nUSER:\n")) - })); - assert!(requests[1].lived_stream.contains("cracked hinge")); - assert!(requests[2].lived_stream.contains("news:west-gate")); - assert!(!requests[2].lived_stream.contains("cracked hinge")); - } - - #[tokio::test] - async fn assignment_editor_receives_a_bounded_period_directory_before_querying() { - let mut campaign = campaign_with_two_news(); - campaign.events[0].kind = "strategic_activity_outcome".into(); - campaign.news[0].at -= chrono::Duration::hours(12); - campaign.events[0].at = campaign.news[0].at; - let older_headline = campaign.news[0].headline.clone(); - let newer_headline = campaign.news[1].headline.clone(); - campaign.events[1].kind = "strategic_activity_outcome".into(); - let prepared = prepare_newspaper( - &campaign, - "The Canopy Ledger", - "Independent and pointed.", - &canopy_ledger_newsroom(), - 3, - ) - .unwrap(); - let model = ScriptedNewspaperModel::new([QUERY_ALL_RECORDS, ONE_STORY_AGENDA]); - - select_editorial_agenda(&model, &prepared, 3).await.unwrap(); - - let first_request = &model.requests()[0].lived_stream; - assert!(first_request.contains("LEDGER PERIOD DIRECTORY")); - assert!(first_request.contains(&older_headline)); - assert!(first_request.contains(&newer_headline)); - assert!(!first_request.contains("news:seal-scandal")); - assert!(!first_request.contains("news:west-gate")); - } - - #[test] - fn period_directory_preserves_canonical_ledger_order_instead_of_lexical_headline_order() { - let mut campaign = campaign_with_two_news(); - for event in &mut campaign.events { - event.kind = "strategic_activity_outcome".into(); - } - campaign.news[0].headline = "Zulu: the first admitted change".into(); - campaign.news[1].headline = "Alpha: the later lexical trap".into(); - let records = public_news_records(&campaign).unwrap(); - let directory = editorial_period_directory(&records); - assert_eq!( - directory[0].completed_change_headlines, - [ - "Zulu: the first admitted change", - "Alpha: the later lexical trap" - ] - ); - } - - #[test] - fn narrative_workbench_has_no_source_count_hole_and_reads_legacy_agendas() { - let records = public_news_records(&campaign_with_archive_news()).unwrap(); - let pitch = WorldNewspaperStoryPitch { - lead: true, - section: "Front Page".into(), - journalist_id: "aven-tarl".into(), - narrative_function: WorldNewspaperNarrativeFunction::LeadChronology, - context_role: WorldNewspaperContextRole::OwnsIssueChronology, - assignment_reason: "Aven follows custody and status reversal.".into(), - citations: (0..8) - .map(|index| format!("news:archive:{index:02}")) - .collect(), - focus_citation: "news:archive:00".into(), - narrative_claim: "One sharp custody failure links the selected record.".into(), - tension: "Public consequence runs ahead of public accountability.".into(), - public_question: "Who answers for the admitted failure?".into(), - conflict_axis: None, - }; - let agenda = WorldNewspaperEditorialAgenda { - issue_shape: WorldNewspaperIssueShape::SpecialIssue, - issue_shape_rationale: "The custody failure organizes the issue.".into(), - dominant_throughline: "Custody failed in public.".into(), - reader_stake: "Readers bear the consequences of that failure.".into(), - story_pitches: vec![pitch], - }; - validate_editorial_agenda(&records, &canopy_ledger_newsroom(), &agenda, 2).unwrap(); - - let mut unfocused = agenda.clone(); - unfocused.story_pitches[0].citations.truncate(4); - unfocused.story_pitches[0].focus_citation = "news:archive:07".into(); - assert!( - validate_editorial_agenda(&records, &canopy_ledger_newsroom(), &unfocused, 2) - .unwrap_err() - .to_string() - .contains("focus record is not in its selected record set") - ); - - let legacy: WorldNewspaperStoryPitch = serde_json::from_str( - r#"{"lead":true,"citations":["news:seal-scandal"],"angle":"A legacy framing field.","tension":"A live tension.","public_question":"What follows?"}"#, - ) - .unwrap(); - assert_eq!(legacy.focus_citation, ""); - assert_eq!(legacy.narrative_claim, "A legacy framing field."); - } - - #[test] - fn adversarial_assignments_bind_two_named_parties_to_selected_records() { - let mut campaign = campaign_with_two_news(); - campaign.institutions.insert( - "court".into(), - crate::domain::InstitutionState { - id: "court".into(), - name: "Thorn Court".into(), - resources: vec![], - goals: vec![], - posture: "defending custody".into(), - }, - ); - campaign.institutions.insert( - "wardens".into(), - crate::domain::InstitutionState { - id: "wardens".into(), - name: "West Gate Wardens".into(), - resources: vec![], - goals: vec![], - posture: "closing the route".into(), - }, - ); - campaign.events[0].institution_ids = vec!["court".into()]; - campaign.events[1].institution_ids = vec!["wardens".into()]; - campaign.events[1].summary = "West Gate Wardens announce that the west gate will close at moonrise while masons replace its cracked hinge.".into(); - let records = public_news_records(&campaign).unwrap(); - let pitch = WorldNewspaperStoryPitch { - lead: true, - section: "Front Page".into(), - journalist_id: "aven-tarl".into(), - narrative_function: WorldNewspaperNarrativeFunction::Opposition, - context_role: WorldNewspaperContextRole::SelfContained, - assignment_reason: "Aven follows the institutions contesting public access.".into(), - citations: vec!["news:seal-scandal".into(), "news:west-gate".into()], - focus_citation: "news:seal-scandal".into(), - narrative_claim: "Two authorities defend incompatible forms of custody.".into(), - tension: "Court custody and route closure collide in public.".into(), - public_question: "Which authority bears the consequence?".into(), - conflict_axis: Some(WorldNewspaperConflictAxis { - first_party: "Thorn Court".into(), - first_party_citation: "news:seal-scandal".into(), - first_party_move: "The court admits the pawned seal and dismisses its treasurer." - .into(), - opposing_party: "West Gate Wardens".into(), - opposing_party_citation: "news:west-gate".into(), - opposing_party_move: "The wardens announce the route closure.".into(), - conflict: "They impose incompatible answers to failed custody.".into(), - }), - }; - let agenda = WorldNewspaperEditorialAgenda { - issue_shape: WorldNewspaperIssueShape::GeneralIssue, - issue_shape_rationale: "One custody rupture reorganizes court and gate.".into(), - dominant_throughline: "Custody has split into rival public authorities.".into(), - reader_stake: "Readers need to know whose closure governs movement.".into(), - story_pitches: vec![pitch], - }; - validate_editorial_agenda(&records, &canopy_ledger_newsroom(), &agenda, 2).unwrap(); - - let mut passive_recipient = agenda.clone(); - passive_recipient.story_pitches[0] - .conflict_axis - .as_mut() - .unwrap() - .opposing_party_citation = "news:seal-scandal".into(); - assert!( - validate_editorial_agenda(&records, &canopy_ledger_newsroom(), &passive_recipient, 2) - .unwrap_err() - .to_string() - .contains("same public move") - ); - - let mut abstract_opponent = agenda; - abstract_opponent.story_pitches[0] - .conflict_axis - .as_mut() - .unwrap() - .opposing_party = "official authority".into(); - assert!( - validate_editorial_agenda(&records, &canopy_ledger_newsroom(), &abstract_opponent, 2) - .unwrap_err() - .to_string() - .contains("opposing party is not named") - ); - } - - #[test] - fn journalist_action_schema_is_stable_while_validation_owns_exact_datelines() { - let records = public_news_records(&campaign_with_two_news()).unwrap(); - let lead_pitch = WorldNewspaperStoryPitch { - lead: true, - section: "Front Page".into(), - journalist_id: "aven-tarl".into(), - narrative_function: WorldNewspaperNarrativeFunction::LeadChronology, - context_role: WorldNewspaperContextRole::OwnsIssueChronology, - assignment_reason: "Aven follows court custody.".into(), - citations: vec!["news:seal-scandal".into()], - focus_citation: "news:seal-scandal".into(), - narrative_claim: "Court custody failed.".into(), - tension: "Admission collides with accountability.".into(), - public_question: "Who answers?".into(), - conflict_axis: None, - }; - let lead = JournalistWorkbench { - records: &records, - article_index: 0, - byline: "Aven Tarl", - issue_shape: WorldNewspaperIssueShape::SpecialIssue, - issue_shape_rationale: "One crisis organizes the issue.", - dominant_throughline: "Court custody failed.", - reader_stake: "Readers depend on the seal.", - pitch: &lead_pitch, - }; - let lead_schema = lead.action_schema().unwrap(); - assert_eq!(lead_schema["properties"]["dateline"]["maxLength"], 100); - assert!(lead_schema["properties"]["dateline"].get("enum").is_none()); - assert_eq!( - lead.assignment_snapshot()["allowed_datelines"], - serde_json::json!(["Room"]) - ); - - let dispatch_pitch = WorldNewspaperStoryPitch { - lead: false, - section: "Dispatches".into(), - journalist_id: "lysa-fen".into(), - narrative_function: WorldNewspaperNarrativeFunction::Consequence, - context_role: WorldNewspaperContextRole::AssumesIssueChronology, - assignment_reason: "Lysa follows access consequences.".into(), - citations: vec!["news:west-gate".into()], - focus_citation: "news:west-gate".into(), - narrative_claim: "The gate is the practical consequence.".into(), - tension: "Repair closes a route.".into(), - public_question: "When does it reopen?".into(), - conflict_axis: None, - }; - let dispatch = JournalistWorkbench { - records: &records, - article_index: 1, - byline: "Lysa Fen", - issue_shape: WorldNewspaperIssueShape::SpecialIssue, - issue_shape_rationale: "One crisis organizes the issue.", - dominant_throughline: "Court custody failed.", - reader_stake: "Readers depend on access.", - pitch: &dispatch_pitch, - }; - assert_eq!(dispatch.action_schema().unwrap(), lead_schema); - assert_eq!( - dispatch.assignment_snapshot()["allowed_datelines"], - serde_json::json!(["Yard"]) - ); - } - - #[test] - fn night_editor_close_owns_complete_query_disposition_and_frozen_fields() { - let draft: EditorialPageDraft = serde_json::from_str(TWO_ARTICLE_PAGE).unwrap(); - let report = WorldNewspaperCopyDeskReport { - assessment: "The lead deck contains two unsupported implications.".into(), - queries: vec![ - WorldNewspaperGroundingFinding { - article_index: 0, - category: WorldNewspaperGroundingCategory::UnsupportedFact, - claim_or_phrase: "A gambling debt reaches the throne room".into(), - reason: "The source does not establish that location.".into(), - }, - WorldNewspaperGroundingFinding { - article_index: 0, - category: WorldNewspaperGroundingCategory::UnsupportedFact, - claim_or_phrase: "one official carrying the blame".into(), - reason: "The source establishes dismissal, not blame allocation.".into(), - }, - ], - }; - let records = public_news_records(&campaign_with_two_news()).unwrap(); - let action: NarrativeSelectionAction = serde_json::from_str(TWO_STORY_AGENDA).unwrap(); - let NarrativeSelectionCommand::ProposeAgenda { - issue_shape, - issue_shape_rationale, - dominant_throughline, - reader_stake, - story_pitches, - } = action.command - else { - panic!("fixture must propose an agenda") - }; - let agenda = WorldNewspaperEditorialAgenda { - issue_shape, - issue_shape_rationale, - dominant_throughline, - reader_stake, - story_pitches, - }; - let night_sources = source_json_for_copy_queries(&records, &agenda, &report).unwrap(); - assert!(night_sources.contains("news:seal-scandal")); - assert!(!night_sources.contains("news:west-gate")); - let schema = NightEditorCloseWorkbench { - records: &records, - max_articles: 2, - draft: draft.clone(), - copy_desk: report.clone(), - } - .action_schema() - .unwrap(); - assert_eq!(schema["properties"]["rewrites"]["minItems"], 0); - assert_eq!(schema["properties"]["rewrites"]["maxItems"], 2); - assert_eq!( - schema["properties"]["rewrites"]["items"]["properties"]["article_index"]["enum"], - serde_json::json!([0, 1]) - ); - let stable_schema = NightEditorCloseWorkbench { - records: &records, - max_articles: 2, - draft: draft.clone(), - copy_desk: WorldNewspaperCopyDeskReport { - assessment: "No queries.".into(), - queries: Vec::new(), - }, - } - .action_schema() - .unwrap(); - assert_eq!(schema, stable_schema); - let closed = apply_night_editor_close( - &draft, - &report, - NightEditorCloseAction::SubmitClose { - addressed_query_indices: vec![0, 1], - rewrites: vec![NightEditorArticleClose { - article_index: 0, - headline: "Pawned Seal, Dismissed Messenger".into(), - deck: "The court admitted one loss and imposed another.".into(), - dateline: "Room".into(), - paragraphs: vec![ - "The Thorn Court admitted that its royal seal was pawned to cover a dragon's gambling debt.".into(), - "The treasurer carried that admission into open court and was dismissed soon afterward. Readers may decide which act embarrassed the court more.".into(), - ], - }], - }, - ) - .unwrap(); - - assert_eq!(closed.addressed_query_indices, [0, 1]); - assert_eq!(closed.changed_article_indices, [0]); - assert_eq!(closed.draft.articles[0].section, draft.articles[0].section); - assert_eq!(closed.draft.articles[0].byline, draft.articles[0].byline); - assert_eq!( - closed.draft.articles[0].citations, - draft.articles[0].citations - ); - assert_eq!(closed.draft.articles[1].section, draft.articles[1].section); - assert_eq!(closed.draft.articles[1].byline, draft.articles[1].byline); - assert_eq!( - closed.draft.articles[1].citations, - draft.articles[1].citations - ); - assert_eq!( - closed.draft.articles[1].headline, - draft.articles[1].headline - ); - - let missed = apply_night_editor_close( - &draft, - &report, - NightEditorCloseAction::SubmitClose { - addressed_query_indices: vec![0], - rewrites: Vec::new(), - }, - ) - .unwrap_err(); - assert!(missed.to_string().contains("every copy-desk query")); - } - - #[tokio::test] - async fn newspaper_is_editorial_copy_with_separate_provenance() { - let campaign = campaign_with_news(); - let model = ScriptedNewspaperModel::new([ - QUERY_ALL_RECORDS, - ONE_STORY_AGENDA, - ACCEPTED_STORY_ACTION, - ACCEPTING_COPY_DESK, - UNCHANGED_NIGHT_CLOSE, - ]); - let composition = compose_world_newspaper( - &model, - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - 4, - ) - .await - .unwrap(); - let page = render_world_newspaper_markdown(&composition.issue); - let audit = render_world_newspaper_audit_markdown(&composition.issue); - - assert_eq!( - composition.issue.schema, - "ghostlight.world_newspaper_issue.v3" - ); - assert_eq!( - composition.issue.articles[0].event_ids(), - ["event:seal-scandal"] - ); - assert_eq!( - composition.issue.articles[0].source_news_ids(), - ["news:seal-scandal"] - ); - assert_eq!(composition.issue.edition_label, EDITION_LABEL); - assert_eq!( - composition - .issue - .editorial_agenda - .as_ref() - .unwrap() - .story_pitches[0] - .journalist_id, - "aven-tarl" - ); - assert_eq!(composition.issue.articles[0].byline, "Aven Tarl"); - assert!(page.contains("Court Sells the Crown's Seal")); - assert!(page.contains("*Current Edition*")); - assert!(page.contains("The court has explained the firing")); - assert!(!page.contains("World revision")); - assert!(!page.contains("event:seal-scandal")); - assert!(!page.contains("committed public channel")); - assert!(audit.contains("event:seal-scandal")); - assert!(audit.contains("Source world revision: 3")); - assert!(audit.contains("Editorial agenda")); - assert!(audit.contains("court made its private gambling debt")); - assert!(audit.contains("Exact committed account: The Thorn Court admits")); - assert!(audit.contains("Source time:")); - assert!( - audit.contains("Assertion status: course_committed_embedded_actions_not_completed") - ); - assert!(audit.contains("Named people: None asserted")); - let mut boundary_issue = composition.issue.clone(); - boundary_issue.articles[0].sources[0].source_times.clear(); - assert!(!render_world_newspaper_audit_markdown(&boundary_issue).contains("Source time:")); - assert!( - serde_json::to_value(&boundary_issue).unwrap()["articles"][0]["sources"][0] - .get("source_times") - .is_none() - ); - boundary_issue.articles[0].sources[0].facts[0].account = - "x".repeat(MAX_PUBLIC_EVENT_SUMMARY_CHARS); - assert!( - render_world_newspaper_audit_markdown(&boundary_issue) - .contains("audit shows the complete stored account and asserts nothing beyond it") - ); - assert_eq!(composition.model_receipts.len(), 6); - assert!(composition.copy_desk.queries.is_empty()); - assert!(composition.press_close.night_editor_action_applied); - assert!(composition.press_close.changed_article_indices.is_empty()); - let requests = model.requests(); - assert_eq!( - requests[0].stage, - "newspaper_narrative_selection_agent_action" - ); - assert_eq!(requests[0].model, MODEL_CAPABLE); - assert_eq!( - requests[1].stage, - "newspaper_narrative_selection_agent_action" - ); - assert_eq!( - requests[2].stage, - "newspaper_narrative_selection_agent_action" - ); - assert_eq!(requests[3].stage, "newspaper_journalist_agent_action"); - assert_eq!(requests[4].stage, "newspaper_copy_desk"); - assert_eq!( - requests[5].stage, - "newspaper_night_editor_close_agent_action" - ); - assert!(requests[3].lived_stream.contains("CURRENT WORKBENCH STATE")); - assert!(requests[0].lived_stream.contains("Veyra Kest")); - assert!(requests[0].lived_stream.contains("Mera Quill")); - assert!(requests[3].lived_stream.contains("Aven Tarl")); - assert!(!requests[3].lived_stream.contains("Mera Quill")); - assert!(requests[4].lived_stream.contains("Dalen Marr")); - assert!(requests[5].lived_stream.contains("Meret Sorn")); - assert!(!requests[5].lived_stream.contains("recover drama")); - let stable_selector_prefix = requests[0] - .lived_stream - .split("\n\nUSER:\nAGENT STEP") - .next() - .unwrap(); - assert!(requests[1].lived_stream.starts_with(stable_selector_prefix)); - assert!(requests[2].lived_stream.starts_with(stable_selector_prefix)); - assert!( - !requests[2] - .lived_stream - .starts_with(&requests[1].lived_stream) - ); - assert_eq!(requests[0].output_schema, requests[1].output_schema); - assert_eq!(requests[1].output_schema, requests[2].output_schema); - assert!( - requests[3] - .source_receipt_ids - .contains(&composition.model_receipts[0].storage_key().to_owned()) - ); - assert!(requests[1].lived_stream.contains("news:seal-scandal")); - assert!(requests[1].lived_stream.contains("event:seal-scandal")); - assert!(requests[1].lived_stream.contains("\"channel\"")); - assert!(requests[1].lived_stream.contains("\"reliability\"")); - assert!(!requests[1].lived_stream.contains("institution_action")); - assert!(!requests[1].lived_stream.contains("actor_ids")); - assert!(!requests[1].lived_stream.contains("institution_ids")); - assert!( - !serde_json::to_string(requests[0].output_schema.as_ref().unwrap()) - .unwrap() - .contains("edition_label") - ); - } - - #[test] - fn public_record_projection_preserves_canonical_records_without_packet_authority() { - let campaign = campaign_with_typed_and_duplicate_news(); - let records = public_news_records(&campaign).unwrap(); - let desk = serde_json::to_string_pretty(&records).unwrap(); - let original = records - .iter() - .find(|record| record.record_id == "news:seal-scandal") - .unwrap(); - - assert_eq!(records.len(), 4); - assert_eq!(desk.matches("royal seal was pawned").count(), 3); - assert_eq!(original.facts[0].event_ids, ["event:seal-scandal"]); - assert!(desk.contains("strains the command tie")); - assert!(desk.contains("take up a new public demand")); - assert!(desk.contains("course_committed_embedded_actions_not_completed")); - assert!(desk.contains("material_change_committed")); - assert!(desk.contains("public_declaration")); - assert!(!desk.contains("strategic_activity_outcome")); - assert!(desk.contains("event:seal-scandal")); - assert!(desk.contains("news:seal-scandal")); - assert!(desk.contains("channel")); - assert!(desk.contains("reliability")); - assert!(desk.contains("\"at\"")); - assert!(!desk.contains("actor_ids")); - assert!(!desk.contains("institution_ids")); - - let mut draft: EditorialPageDraft = serde_json::from_str(ACCEPTED_PAGE).unwrap(); - draft.articles[0].citations = vec![original.record_id.clone()]; - let issue = lower_editorial_page( - &campaign, - "The Underdeep Clarion".into(), - &records, - None, - draft, - &[], - ) - .unwrap(); - assert_eq!(issue.articles[0].source_news_ids(), ["news:seal-scandal"]); - assert_eq!(issue.articles[0].event_ids(), ["event:seal-scandal"]); - } - - #[test] - fn public_records_do_not_promote_involved_metadata_to_asserted_names_or_datelines() { - let mut campaign = campaign_with_two_news(); - let mut ann = campaign.actors["player"].clone(); - ann.id = "ann".into(); - ann.name = "Ann".into(); - campaign.actors.insert(ann.id.clone(), ann); - campaign.locations.insert( - "hall".into(), - crate::domain::Location { - id: "hall".into(), - name: "Hall".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - ); - campaign.institutions.insert( - "unmentioned-regency".into(), - crate::domain::InstitutionState { - id: "unmentioned-regency".into(), - name: "Mossglass Regency".into(), - resources: vec![], - goals: vec![], - posture: "watching".into(), - }, - ); - let event = campaign - .events - .iter_mut() - .find(|event| event.id == "event:seal-scandal") - .unwrap(); - event.summary = "The Thorn Court announces that every officer shall answer.".into(); - event.actor_ids = vec!["ann".into()]; - event.institution_ids = vec!["unmentioned-regency".into()]; - event.location_ids = vec!["hall".into(), "yard".into()]; - - let records = public_news_records(&campaign).unwrap(); - let record = records - .iter() - .find(|record| record.record_id == "news:seal-scandal") - .unwrap(); - assert!(record.facts[0].named_people.is_empty()); - assert!(record.facts[0].institutions.is_empty()); - assert!(record.facts[0].places.is_empty()); - } - - #[test] - fn public_records_name_people_without_inventing_identity_attributes() { - let mut campaign = campaign_with_news(); - let mut ann = campaign.actors["player"].clone(); - ann.id = "ann".into(); - ann.name = "Ann Vey".into(); - campaign.actors.insert(ann.id.clone(), ann); - let event = campaign - .events - .iter_mut() - .find(|event| event.id == "event:seal-scandal") - .unwrap(); - event.summary = "Ann Vey publicly contests the Thorn Court's seal account.".into(); - event.actor_ids = vec!["ann".into()]; - - let records = public_news_records(&campaign).unwrap(); - let named = &records[0].facts[0].named_people; - assert_eq!(named.len(), 1); - assert_eq!(named[0].name, "Ann Vey"); - assert!(named[0].supported_identity_attributes.is_empty()); - let desk = serde_json::to_string(&records).unwrap(); - assert!(desk.contains("supported_identity_attributes")); - } - - #[tokio::test] - async fn newspaper_rejects_a_headline_without_a_committed_event_before_inference() { - let mut campaign = campaign_with_news(); - campaign.news[0].event_ids = vec!["event:missing".into()]; - let model = ScriptedNewspaperModel::new([]); - let error = compose_world_newspaper( - &model, - &campaign, - "The Clarion", - "A sober regional paper.", - 4, - ) - .await - .unwrap_err(); - assert!(error.to_string().contains("unknown event")); - } - - #[tokio::test] - async fn newspaper_rejects_ambiguous_public_record_ids_before_inference() { - let mut campaign = campaign_with_two_news(); - campaign.news[1].id = campaign.news[0].id.clone(); - let model = ScriptedNewspaperModel::new([]); - let error = compose_world_newspaper( - &model, - &campaign, - "The Clarion", - "A sober regional paper.", - 4, - ) - .await - .unwrap_err(); - assert!(error.to_string().contains("repeats record ID")); - assert!(model.requests().is_empty()); - } - - #[tokio::test] - async fn copy_desk_queries_feed_one_night_close_without_rereview() { - const REJECTED: &str = r#"{"assessment":"The deck overstates where the admitted debt reached.","queries":[{"article_index":0,"category":"unsupported_fact","claim_or_phrase":"A gambling debt reaches the throne room and leaves one official carrying the blame.","reason":"The cited source records the pawned seal and dismissal but does not locate the debt in the throne room."}]}"#; - let campaign = campaign_with_news(); - let model = ScriptedNewspaperModel::new([ - QUERY_ALL_RECORDS, - ONE_STORY_AGENDA, - ACCEPTED_STORY_ACTION, - REJECTED, - QUERY_DECK_CLOSE, - ]); - let composition = compose_world_newspaper( - &model, - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - 4, - ) - .await - .unwrap(); - - assert_eq!(composition.copy_desk.queries.len(), 1); - assert!(composition.press_close.night_editor_action_applied); - assert_eq!(composition.press_close.addressed_query_indices, [0]); - assert_eq!(composition.press_close.changed_article_indices, [0]); - assert_eq!( - composition.issue.articles[0].deck, - "The court admits the pawned seal and dismisses the official who carried the confession." - ); - let requests = model.requests(); - assert_eq!(requests.len(), 6); - assert_eq!( - requests - .iter() - .filter(|request| request.stage == "newspaper_copy_desk") - .count(), - 1 - ); - assert_eq!( - requests - .iter() - .filter(|request| { request.stage == "newspaper_night_editor_close_agent_action" }) - .count(), - 1 - ); - assert!(requests.iter().all(|request| { - request.stage != "newspaper_night_editor" - && request.stage != "newspaper_rewrite_desk_agent_action" - })); - assert!(composition.model_receipts[..5].iter().all(|receipt| { - requests[5] - .source_receipt_ids - .contains(&receipt.storage_key().to_owned()) - })); - } - - #[tokio::test] - async fn rejected_night_close_prints_the_checkpointed_page_at_deadline() { - const REJECTED: &str = r#"{"assessment":"The deck overstates where the admitted debt reached.","queries":[{"article_index":0,"category":"unsupported_fact","claim_or_phrase":"A gambling debt reaches the throne room and leaves one official carrying the blame.","reason":"The cited source records the pawned seal and dismissal but does not locate the debt in the throne room."}]}"#; - const INVALID_CLOSE: &str = r#"{"tool":"submit_close","addressed_query_indices":[0],"rewrites":[{"article_index":0,"headline":"Court Sells the Crown's Seal, Then the Treasurer","deck":"A gambling debt reaches the throne room and leaves one official carrying the blame.","dateline":"Elsewhere","paragraphs":["The Thorn Court has admitted that its royal seal was pawned to cover a dragon's gambling debt, a confession that turns private embarrassment into a public question of custody.","The treasurer who delivered that admission in open court was dismissed soon afterward. The court has explained the firing; it has not made the seal any less pawned."]}]}"#; - let model = ScriptedNewspaperModel::new([ - QUERY_ALL_RECORDS, - ONE_STORY_AGENDA, - ACCEPTED_STORY_ACTION, - REJECTED, - INVALID_CLOSE, - ]); - let composition = compose_world_newspaper( - &model, - &campaign_with_news(), - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - 4, - ) - .await - .unwrap(); - - assert!(!composition.press_close.night_editor_action_applied); - assert!(composition.press_close.addressed_query_indices.is_empty()); - assert_eq!( - composition.issue.articles[0].deck, - "A gambling debt reaches the throne room and leaves one official carrying the blame." - ); - assert_eq!( - composition - .model_receipts - .iter() - .filter(|receipt| receipt.stage == "newspaper_copy_desk") - .count(), - 1 - ); - assert_eq!( - composition - .model_receipts - .iter() - .filter(|receipt| { receipt.stage == "newspaper_night_editor_close_agent_action" }) - .count(), - 1 - ); - assert_eq!( - composition.model_receipts.last().unwrap().validation_result, - "semantic_invalid" - ); - } - - #[tokio::test] - async fn close_checkpoint_resumes_without_replaying_reporter_or_copy_desk() { - const REJECTED: &str = r#"{"assessment":"The deck overstates where the admitted debt reached.","queries":[{"article_index":0,"category":"unsupported_fact","claim_or_phrase":"A gambling debt reaches the throne room and leaves one official carrying the blame.","reason":"The cited source records the pawned seal and dismissal but does not locate the debt in the throne room."}]}"#; - let campaign = campaign_with_news(); - let directory = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(directory.path().join("campaign.cc")).unwrap(); - let first_model = ScriptedNewspaperModel::new([ - QUERY_ALL_RECORDS, - ONE_STORY_AGENDA, - ACCEPTED_STORY_ACTION, - REJECTED, - ]); - let error = advance_world_newspaper( - &first_model, - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - &canopy_ledger_newsroom(), - 4, - &store, - ) - .await - .unwrap_err(); - assert!( - error - .to_string() - .contains("fixture newspaper model exhausted") - ); - assert_eq!( - store - .keys("world_newspaper_close_checkpoint.v1") - .unwrap() - .len(), - 1 - ); - - let resume_model = ScriptedNewspaperModel::new([QUERY_DECK_CLOSE]); - let accepted = advance_world_newspaper( - &resume_model, - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - &canopy_ledger_newsroom(), - 4, - &store, - ) - .await - .unwrap(); - let requests = resume_model.requests(); - assert_eq!(requests.len(), 1); - assert_eq!( - requests[0].stage, - "newspaper_night_editor_close_agent_action" - ); - assert_eq!(accepted.model_receipts.len(), 6); - - let idempotent_model = ScriptedNewspaperModel::new([]); - let repeated = advance_world_newspaper( - &idempotent_model, - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - &canopy_ledger_newsroom(), - 4, - &store, - ) - .await - .unwrap(); - assert_eq!(repeated, accepted); - assert!(idempotent_model.requests().is_empty()); - - let prepared = prepare_newspaper( - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - &canopy_ledger_newsroom(), - 4, - ) - .unwrap(); - let (_, mut persisted) = store - .load::( - "world_newspaper_composition.v3", - &prepared.publication_task_binding, - ) - .unwrap() - .unwrap(); - persisted.composition.issue.articles[0].deck = "Tampered after press close.".into(); - assert!( - validate_persisted_composition(&store, &campaign, &prepared, 4, &persisted) - .unwrap_err() - .to_string() - .contains("press witness") - ); - } - - #[tokio::test] - async fn production_checkpoints_resume_at_the_failed_reporter() { - let campaign = campaign_with_two_news(); - let directory = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(directory.path().join("campaign.cc")).unwrap(); - let first_model = ScriptedNewspaperModel::new([ - QUERY_ALL_RECORDS, - TWO_STORY_AGENDA, - ACCEPTED_STORY_ACTION, - MALFORMED_LYSA_STORY_ACTION, - MALFORMED_LYSA_STORY_ACTION, - ]); - let error = advance_world_newspaper( - &first_model, - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - &canopy_ledger_newsroom(), - 4, - &store, - ) - .await - .unwrap_err(); - assert!(error.to_string().contains("malformed paragraph")); - assert_eq!( - store - .keys("world_newspaper_production_checkpoint.v1") - .unwrap() - .len(), - 2, - "the admitted agenda and Aven's accepted filing must survive Lysa's failure" - ); - let mut filed_checkpoint = store - .load_all::( - "world_newspaper_production_checkpoint.v1", - ) - .unwrap() - .into_iter() - .find(|checkpoint| { - matches!( - &checkpoint.content, - WorldNewspaperProductionContent::FiledArticle { .. } - ) - }) - .unwrap(); - let filed_receipts = load_model_receipts( - &store, - &filed_checkpoint.model_receipt_ids, - "tamper fixture", - ) - .unwrap(); - if let WorldNewspaperProductionContent::FiledArticle { article, .. } = - &mut filed_checkpoint.content - { - article.deck = "Tampered after filing.".into(); - } - assert!( - validate_production_receipts( - &filed_checkpoint, - &filed_receipts, - "newspaper_journalist_agent_action", - &filed_receipts[0].snapshot_binding, - ) - .unwrap_err() - .to_string() - .contains("receipt binding") - ); - - let resume_model = ScriptedNewspaperModel::new([ - ACCEPTED_LYSA_STORY_ACTION, - ACCEPTING_COPY_DESK, - UNCHANGED_NIGHT_CLOSE, - ]); - let composition = advance_world_newspaper( - &resume_model, - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - &canopy_ledger_newsroom(), - 4, - &store, - ) - .await - .unwrap(); - let requests = resume_model.requests(); - assert_eq!(requests.len(), 3); - assert_eq!(requests[0].stage, "newspaper_journalist_agent_action"); - assert!(requests[0].lived_stream.contains("Lysa Fen")); - assert!(!requests[0].lived_stream.contains("Aven Tarl")); - assert_eq!(requests[1].stage, "newspaper_copy_desk"); - assert_eq!( - requests[2].stage, - "newspaper_night_editor_close_agent_action" - ); - assert_eq!(composition.issue.articles.len(), 2); - assert_eq!( - store - .keys("world_newspaper_production_checkpoint.v1") - .unwrap() - .len(), - 3 - ); - } - - #[tokio::test] - async fn legacy_close_checkpoint_decodes_as_inert_history() { - let campaign = campaign_with_news(); - let source_directory = tempfile::tempdir().unwrap(); - let source_store = - CampaignStore::open(source_directory.path().join("campaign.cc")).unwrap(); - let interrupted = ScriptedNewspaperModel::new([ - QUERY_ALL_RECORDS, - ONE_STORY_AGENDA, - ACCEPTED_STORY_ACTION, - ACCEPTING_COPY_DESK, - ]); - advance_world_newspaper( - &interrupted, - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - &canopy_ledger_newsroom(), - 4, - &source_store, - ) - .await - .unwrap_err(); - let mut legacy = source_store - .load_all::("world_newspaper_close_checkpoint.v1") - .unwrap() - .into_iter() - .next() - .unwrap(); - legacy.id = "newspaper-close:legacy-v7".into(); - legacy.origin = WorldNewspaperCloseOrigin::LegacyV7Checkpoint; - legacy.source_checkpoint_id = Some("historical-v7-tip".into()); - - let target_directory = tempfile::tempdir().unwrap(); - let target_store = - CampaignStore::open(target_directory.path().join("campaign.cc")).unwrap(); - target_store - .insert( - "world_newspaper_close_checkpoint.v1", - "ghostlight.world_newspaper_close_checkpoint.v1", - &legacy.id, - &legacy, - ) - .unwrap(); - - let model = ScriptedNewspaperModel::new([ - QUERY_ALL_RECORDS, - ONE_STORY_AGENDA, - ACCEPTED_STORY_ACTION, - ACCEPTING_COPY_DESK, - UNCHANGED_NIGHT_CLOSE, - ]); - let composition = advance_world_newspaper( - &model, - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - &canopy_ledger_newsroom(), - 4, - &target_store, - ) - .await - .unwrap(); - - assert_eq!(model.requests().len(), 6); - assert_eq!(composition.issue.articles.len(), 1); - assert_eq!( - target_store - .keys("world_newspaper_close_checkpoint.v1") - .unwrap() - .len(), - 2 - ); - } - - #[tokio::test] - async fn reader_projection_escapes_model_and_consumer_markdown() { - const MARKDOWN_PAGE: &str = r#"{"tool":"file_story","headline":"[Court](https://headline.invalid) Faces ","deck":"The *royal* debt now reaches every keeper of the seal.","dateline":"Room","paragraphs":["- The Thorn Court admitted the royal seal was pawned to cover a dragon's gambling debt; cannot make the confession ~~prettier~~.","1. The dismissed treasurer leaves readers with a [public record](https://copy.invalid) and the court with a seal that remains pawned."]}"#; - let campaign = campaign_with_news(); - let model = ScriptedNewspaperModel::new([ - QUERY_ALL_RECORDS, - ONE_STORY_AGENDA, - MARKDOWN_PAGE, - ACCEPTING_COPY_DESK, - UNCHANGED_NIGHT_CLOSE, - ]); - let composition = compose_world_newspaper( - &model, - &campaign, - "[The Clarion](https://masthead.invalid)", - "A skeptical court broadsheet with dry restraint.", - 4, - ) - .await - .unwrap(); - let page = render_world_newspaper_markdown(&composition.issue); - let audit = render_world_newspaper_audit_markdown(&composition.issue); - - assert!(!page.contains("[The Clarion](https://masthead.invalid)")); - assert!(!page.contains("[Court](https://headline.invalid)")); - assert!(!page.contains("")); - assert!(!page.contains("\n- The Thorn Court")); - assert!(!page.contains("\n1. The dismissed treasurer")); - assert!(!page.contains("~~prettier~~")); - assert!(page.contains("\\[The Clarion\\](https://masthead.invalid)")); - assert!(page.contains("<img src=x>")); - assert!(page.contains("\\- The Thorn Court")); - assert!(page.contains("1\\. The dismissed treasurer")); - assert!(page.contains("*Current Edition*")); - assert!(!page.contains("edition.invalid")); - assert!(!audit.contains("[The Clarion](https://masthead.invalid)")); - assert!(!audit.contains("[Court](https://headline.invalid)")); - } - - #[test] - fn lead_dateline_must_belong_to_its_cited_source() { - let campaign = campaign_with_two_news(); - let records = public_news_records(&campaign).unwrap(); - let mut draft: EditorialPageDraft = serde_json::from_str(ACCEPTED_PAGE).unwrap(); - draft.articles[0].dateline.clear(); - let missing = validate_editorial_draft(&records, &draft, 4).unwrap_err(); - assert!(missing.to_string().contains("lead article must use")); - - draft.articles[0].dateline = "Yard".into(); - let unsupported = validate_editorial_draft(&records, &draft, 4).unwrap_err(); - assert!(unsupported.to_string().contains("misattributed a dateline")); - - draft.articles[0].dateline = "Room".into(); - draft.articles[0].citations.push("news:seal-scandal".into()); - let duplicate = validate_editorial_draft(&records, &draft, 4).unwrap_err(); - assert!(duplicate.to_string().contains("repeats a public record ID")); - } - - #[tokio::test] - async fn article_identity_covers_the_published_copy() { - const ALTERNATE_PAGE: &str = r#"{"tool":"file_story","headline":"Court Sells the Crown's Seal, Then the Treasurer","deck":"The same scandal leaves the throne defending both its custody and its judgment.","dateline":"Room","paragraphs":["The Thorn Court has admitted that its royal seal was pawned to cover a dragon's gambling debt, a confession that turns private embarrassment into a public question of custody.","The treasurer who delivered that admission in open court was dismissed soon afterward. The court has explained the firing; it has not made the seal any less pawned."]}"#; - let campaign = campaign_with_news(); - let first = compose_world_newspaper( - &ScriptedNewspaperModel::new([ - QUERY_ALL_RECORDS, - ONE_STORY_AGENDA, - ACCEPTED_STORY_ACTION, - ACCEPTING_COPY_DESK, - UNCHANGED_NIGHT_CLOSE, - ]), - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - 4, - ) - .await - .unwrap(); - let second = compose_world_newspaper( - &ScriptedNewspaperModel::new([ - QUERY_ALL_RECORDS, - ONE_STORY_AGENDA, - ALTERNATE_PAGE, - ACCEPTING_COPY_DESK, - UNCHANGED_NIGHT_CLOSE, - ]), - &campaign, - "The Underdeep Clarion", - "A skeptical court broadsheet with dry restraint.", - 4, - ) - .await - .unwrap(); - - assert_ne!(first.issue.articles[0].id, second.issue.articles[0].id); - } -} diff --git a/crates/ghostlight-dungeon/src/outcome.rs b/crates/ghostlight-dungeon/src/outcome.rs deleted file mode 100644 index 336667e..0000000 --- a/crates/ghostlight-dungeon/src/outcome.rs +++ /dev/null @@ -1,4387 +0,0 @@ -use crate::{ - domain::{ - Campaign, CausalFollowThroughAssignment, CellActionProposal, - MAX_PUBLIC_EVENT_SUMMARY_CHARS, StrategicActivityKind, StrategicActivityOutcome, - StrategicCellEffect, StrategicOutcomeBand, StrategicOutcomeEffect, StrategicTickPlan, - }, - model::{ - MODEL_BALANCED, MODEL_FAST, ModelPort, ModelStageOutput, ModelStageReceipt, - ModelStageRequest, run_validated_stage, - }, - resolution::{cell_action_digest, effective_member_knowledge, subject_state_references}, -}; -use anyhow::{Result, anyhow}; -use schemars::{JsonSchema, schema_for}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::{ - collections::{BTreeMap, BTreeSet}, - sync::Arc, -}; -use tokio::{sync::Semaphore, task::JoinSet}; - -const OUTCOME_PROPOSAL_OUTPUT_CONTRACT: &str = r#"The top-level object has exactly one field named outcomes—never action_resolutions, results, or resolutions. outcomes is an array with one item per supplied action_digest. Every item requires action_digest, band (success, mixed, or failure), effect_kind, and supporting_state_references. Fields are conditionally required, not optional suggestions: no_material_change requires reason; resource_created and resource_consumed require owner_subject_id and resource; resource_transferred requires owner_subject_id, other_subject_id, and resource; gestalt_pressure requires owner_subject_id plus both pressure arrays; agency_relation_shift requires relation_id and strength_delta; member_memory requires member_id and memory; member_obligation requires member_id and obligation; member_relationship requires member_id, other_subject_id, and relationship_description; knowledge_learned requires owner_subject_id and fact_id; knowledge_communicated requires owner_subject_id, recipient_subject_ids, and fact_id. Every scalar field not named for the chosen effect_kind is omitted or null; irrelevant arrays are omitted, null, or empty and normalize to empty before semantic binding. A non-neutral irrelevant field is invalid. For gestalt_pressure, pressure_additions and pressure_resolutions must be arrays of plain strings, never null or objects. For knowledge_communicated, recipient_subject_ids is an array of exact supplied recipients, never null. no_material_change uses an empty supporting_state_references array; every material effect cites the smallest causally decisive set of one to eight values copied literally and only from that action's allowed_state_references. A source_subject_id, target_subject_id, target_state subject_id, member_state_owner_id, owner_subject_id, other_subject_id, member_id, relation_id, fact_id, or recipient_subject_id is not a supporting state reference unless that exact string also appears in allowed_state_references. For member_relationship and knowledge_communicated, the target field already identifies the target; do not repeat it as provenance. Do not emit summary; Ghostlight derives it from the validated typed effect. When resource_created is admissible and concrete capability-backed making or repair establishes a durable result, owner_subject_id copies one exact resource_creation_owner_ids value: use the source for portable stock or equipment it retains, and use an exact activity location for a durable installed, placed, or repaired feature there. The resource field names the resulting object, stock, repair, or usable arrangement. It never restates an action or an unnamed recipient's response. Example no-op shape: {"outcomes":[{"action_digest":"sha256:","band":"mixed","effect_kind":"no_material_change","supporting_state_references":[],"reason":"No durable state changed."}]}"#; -const OUTCOME_VERIFIER_OUTPUT_CONTRACT: &str = r#"The top-level object has exactly one field named verdicts—never verifications, outcomes, results, or resolutions. verdicts is an array with one item per supplied action_digest. Every item has exactly action_digest, result, and repair_guidance. Example: {"verdicts":[{"action_digest":"sha256:","result":"match","repair_guidance":null}]}"#; - -#[derive(Clone, Debug, Serialize)] -struct OutcomeContext { - world_revision: u64, - resolution_epoch: u64, - actions: Vec, -} - -#[derive(Clone, Debug, Serialize)] -struct ActionOutcomeContext { - action_digest: String, - source_subject_id: String, - source_name: String, - intent: String, - intended_effect: String, - causal_anchors: Vec, - activities: Vec, - target_subject_ids: Vec, - location_ids: Vec, - source_state: serde_json::Value, - target_state: Vec, - active_relations: Vec, - pressure_owners: Vec, - resource_owner_id: String, - resource_creation_owner_ids: Vec, - resource_recipient_ids: Vec, - discoverable_facts: Vec, - communicable_facts: Vec, - member_state_owner_id: Option, - admissible_effect_kinds: Vec, - allowed_state_references: Vec, -} - -#[derive(Clone, Debug, Serialize)] -struct CausalAnchorOutcomeContext { - anchor_reference: String, - committed_account: String, -} - -#[derive(Clone, Debug, Serialize)] -struct PressureOwnerContext { - owner_subject_id: String, - current_pressures: Vec, -} - -#[derive(Clone, Debug, Serialize)] -struct CommunicableFactContext { - fact_id: String, - statement: String, - recipient_subject_ids: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(deny_unknown_fields)] -struct OutcomeProposalBundle { - outcomes: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum OutcomeEffectKind { - NoMaterialChange, - ResourceCreated, - ResourceConsumed, - ResourceTransferred, - GestaltPressure, - AgencyRelationShift, - MemberMemory, - MemberObligation, - MemberRelationship, - KnowledgeLearned, - KnowledgeCommunicated, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(deny_unknown_fields)] -struct OutcomeProposal { - action_digest: String, - band: StrategicOutcomeBand, - effect_kind: OutcomeEffectKind, - #[serde(default)] - supporting_state_references: Vec, - #[serde(default)] - owner_subject_id: Option, - #[serde(default)] - other_subject_id: Option, - #[serde(default)] - relation_id: Option, - #[serde(default)] - strength_delta: Option, - #[serde(default)] - resource: Option, - #[serde(default, deserialize_with = "null_as_empty_vec")] - pressure_additions: Vec, - #[serde(default, deserialize_with = "null_as_empty_vec")] - pressure_resolutions: Vec, - #[serde(default)] - member_id: Option, - #[serde(default)] - memory: Option, - #[serde(default)] - obligation: Option, - #[serde(default)] - relationship_description: Option, - #[serde(default)] - fact_id: Option, - #[serde(default, deserialize_with = "null_as_empty_vec")] - recipient_subject_ids: Vec, - #[serde(default)] - reason: Option, -} - -fn null_as_empty_vec<'de, D>(deserializer: D) -> std::result::Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - Ok(Option::>::deserialize(deserializer)?.unwrap_or_default()) -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(deny_unknown_fields)] -struct OutcomeVerifierBundle { - verdicts: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum OutcomeVerifierResult { - Match, - Mismatch, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -#[serde(deny_unknown_fields)] -struct OutcomeVerifierVerdict { - action_digest: String, - result: OutcomeVerifierResult, - #[serde(default)] - repair_guidance: Option, -} - -#[derive(Clone, Debug)] -pub struct StrategicOutcomeResolutionFailure { - pub action_errors: Vec, - pub stage_receipts: Vec, -} - -impl std::fmt::Display for StrategicOutcomeResolutionFailure { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - formatter, - "strategic outcome resolution rejected after {} action failure(s): {}", - self.action_errors.len(), - self.action_errors.join("; ") - ) - } -} - -impl std::error::Error for StrategicOutcomeResolutionFailure {} - -enum OutcomeCandidateEvaluation { - Accepted { - outcomes: Vec, - verifier: Option, - }, - Rejected { - finding: String, - verifier: Option, - }, -} - -pub async fn resolve_activity_outcomes( - model: Arc, - campaign: &Campaign, - proposals: &[CellActionProposal], -) -> Result<(Vec, Vec)> { - resolve_activity_outcomes_with_causal_assignments(model, campaign, proposals, &[]).await -} - -pub async fn resolve_activity_outcomes_with_causal_assignments( - model: Arc, - campaign: &Campaign, - proposals: &[CellActionProposal], - causal_assignments: &[CausalFollowThroughAssignment], -) -> Result<(Vec, Vec)> { - if proposals.is_empty() { - return Ok((Vec::new(), Vec::new())); - } - let parallelism = usize::from(campaign.resolution_policy.provider_parallelism.max(1)); - let permits = Arc::new(Semaphore::new(parallelism)); - let campaign = Arc::new(campaign.clone()); - let mut tasks = JoinSet::new(); - for (index, proposal) in proposals.iter().cloned().enumerate() { - let causal_anchors = - causal_anchor_contexts(campaign.as_ref(), &proposal, causal_assignments)?; - let model = model.clone(); - let campaign = campaign.clone(); - let permits = permits.clone(); - tasks.spawn(async move { - let _permit = permits - .acquire_owned() - .await - .map_err(|_| anyhow!("strategic outcome concurrency gate closed"))?; - let resolved = - resolve_activity_outcome(model.as_ref(), &campaign, &proposal, causal_anchors) - .await?; - Ok::<_, anyhow::Error>((index, resolved)) - }); - } - let mut ordered = BTreeMap::new(); - let mut action_errors = Vec::new(); - let mut rejected_stage_receipts = Vec::new(); - while let Some(task) = tasks.join_next().await { - match task { - Ok(Ok((index, resolved))) => { - if ordered.insert(index, resolved).is_some() { - action_errors.push("strategic outcome worker returned a duplicate slot".into()); - } - } - Ok(Err(error)) => { - if let Some(failure) = error.downcast_ref::() { - action_errors.extend(failure.action_errors.clone()); - rejected_stage_receipts.extend(failure.stage_receipts.clone()); - } else { - action_errors.push(error.to_string()); - } - } - Err(error) => { - action_errors.push(format!("strategic outcome worker failed: {error}")); - } - } - } - if !action_errors.is_empty() { - rejected_stage_receipts.extend( - ordered - .values() - .flat_map(|(_, stages)| stages.iter().map(|stage| stage.receipt.clone())), - ); - return Err(anyhow::Error::new(StrategicOutcomeResolutionFailure { - action_errors, - stage_receipts: rejected_stage_receipts, - })); - } - if ordered.len() != proposals.len() { - return Err(anyhow!( - "strategic outcome workers returned {} slots for {} selected actions", - ordered.len(), - proposals.len() - )); - } - let mut outcomes = Vec::with_capacity(proposals.len()); - let mut stages = Vec::new(); - for (_, (mut action_outcomes, mut action_stages)) in ordered { - outcomes.append(&mut action_outcomes); - stages.append(&mut action_stages); - } - Ok((outcomes, stages)) -} - -async fn resolve_activity_outcome( - model: &dyn ModelPort, - campaign: &Campaign, - proposal: &CellActionProposal, - causal_anchors: Vec, -) -> Result<(Vec, Vec)> { - let proposals = std::slice::from_ref(proposal); - let context = build_context_with_causal_anchors(campaign, proposals, &causal_anchors)?; - let digests = proposals - .iter() - .map(cell_action_digest) - .collect::>>()?; - let binding = activity_outcome_binding( - campaign.id, - campaign.revision, - campaign.resolution_policy.resolution_epoch, - &digests, - ); - let mut schema = serde_json::to_value(schema_for!(OutcomeProposalBundle))?; - constrain_outcome_schema(&mut schema, &context.actions)?; - let source_receipt_ids: Vec = proposals - .iter() - .flat_map(|proposal| outcome_source_receipts(campaign, proposal)) - .collect::>() - .into_iter() - .collect(); - let static_contract = format!( - "You are Ghostlight's private strategic outcome resolver. The Interpreter already established each exact constituent's selected attempt; you alone assess opposition and choose its bounded durable result. Resolve every supplied action_digest exactly once. Never add or remove an action. causal_anchors contains the exact committed account that caused Nemesis to assign this responder a turn; use it to judge causal follow-through, but never treat it as new mutation authority. For each action, effect_kind must come from that action's admissible_effect_kinds; this is the runtime's exact projection of locally valid consequence handles. Use only IDs, resources, pressure resolutions, relations, facts, member owners, targets, and state references supplied for that same action. Never mutate the player. Never treat an arena as an actor or union constituents' private state. Prefer the most specific causally supported durable effect when the attempt and its band establish one. A mixed result should preserve bounded progress, cost, or a new unresolved pressure when a supplied handle supports it; do not collapse concrete partial work into no change merely because it is incomplete. Use no_material_change when none of the other supplied handles honestly represents a durable result; success or mixed success does not itself authorize inventing a response, fact, relationship, or resource. A failure may create a pressure or spend a committed resource when causally supported. Every material effect must actually change the supplied state; do not repeat an existing resource, pressure, memory, obligation, relationship description, or known fact. Choose exactly one effect_kind. Populate only its fields and omit every irrelevant optional field. no_material_change requires reason. resource_created creates one bounded branch-local resource and requires a capability reference. Its owner_subject_id must copy one exact resource_creation_owner_ids value: choose the source for portable stock or equipment it retains, or an exact activity location for a durable installed, placed, or repaired feature there. resource_consumed spends one exact existing source resource. resource_transferred gives one exact existing source resource to one recipient: copy one exact resource_recipient_ids value into the output field other_subject_id; it cannot take from a target. For resource_consumed and resource_transferred, owner_subject_id must copy that action's exact resource_owner_id, including any member: prefix. gestalt_pressure copies one exact pressure_owners.owner_subject_id value adjacent to that owner's current_pressures into owner_subject_id; resolutions must copy exact current pressure text. agency_relation_shift uses one supplied active relation and a nonzero delta from -10 through 10. Member memory, obligation, or relationship may change only the supplied member_state_owner_id; member_id omits the member: prefix. A relationship's other_subject_id must be one exact action target. knowledge_learned uses one supplied discoverable fact and teaches only the source. knowledge_communicated copies one communicable_facts fact_id and a nonempty subset of its exact recipient_subject_ids; owner_subject_id is the source speaker. Every material effect needs at least one supporting_state_reference copied literally and only from that action's allowed_state_references. IDs shown in source_state, target_state, target_subject_ids, or effect-specific owner and target fields are not provenance handles unless repeated in allowed_state_references. Return one JSON object and no prose outside JSON.\n\nOUTPUT CONTRACT:\n{OUTCOME_PROPOSAL_OUTPUT_CONTRACT}" - ); - let request = ModelStageRequest { - stage: "strategic_outcome_resolver".into(), - model: MODEL_FAST.into(), - snapshot_binding: binding.clone(), - lived_stream: format!( - "{static_contract}\n\nOUTCOME_CONTEXT:\n{}", - serde_json::to_string(&context)? - ), - output_schema: Some(schema.clone()), - source_receipt_ids: source_receipt_ids.clone(), - temperature: Some(0.0), - max_output_tokens: Some(2_400), - }; - let mut stages = Vec::new(); - let mut candidate_stage = run_validated_stage(model, &request).await?; - let mut candidate_bundle: OutcomeProposalBundle = serde_json::from_value( - candidate_stage - .structured - .clone() - .ok_or_else(|| anyhow!("strategic outcome resolver produced no typed output"))?, - )?; - let mut candidate_was_reconciled = false; - loop { - let candidate_sources = source_receipt_ids - .iter() - .cloned() - .chain(std::iter::once( - candidate_stage.receipt.storage_key().to_owned(), - )) - .collect::>() - .into_iter() - .collect::>(); - let evaluation = evaluate_outcome_candidate( - model, - campaign, - proposals, - &context, - candidate_bundle.clone(), - &candidate_sources, - ) - .await; - let evaluation = match evaluation { - Ok(evaluation) => evaluation, - Err(error) => { - reject_candidate_stage(&mut candidate_stage, &error.to_string()); - stages.push(candidate_stage); - return Err(outcome_failure(error.to_string(), &stages)); - } - }; - match evaluation { - OutcomeCandidateEvaluation::Accepted { outcomes, verifier } => { - stages.push(candidate_stage); - if let Some(verifier) = verifier { - stages.push(verifier); - } - return Ok((outcomes, stages)); - } - OutcomeCandidateEvaluation::Rejected { finding, verifier } => { - reject_candidate_stage(&mut candidate_stage, &finding); - stages.push(candidate_stage); - if let Some(verifier) = verifier { - stages.push(verifier); - } - if candidate_was_reconciled { - return Err(outcome_failure( - format!( - "strategic outcome reconciliation did not survive admission: {finding}" - ), - &stages, - )); - } - let reconciliation_sources = source_receipt_ids - .iter() - .cloned() - .chain( - stages - .iter() - .map(|stage| stage.receipt.storage_key().to_owned()), - ) - .collect::>() - .into_iter() - .collect::>(); - let reconciliation = reconcile_activity_outcome( - model, - &context, - &candidate_bundle, - &finding, - &reconciliation_sources, - &schema, - &binding, - ) - .await; - let (reconciled_bundle, reconciliation_stage) = match reconciliation { - Ok(reconciliation) => reconciliation, - Err(error) => { - return Err(outcome_failure(error.to_string(), &stages)); - } - }; - candidate_bundle = reconciled_bundle; - candidate_stage = reconciliation_stage; - candidate_was_reconciled = true; - } - } - } -} - -async fn evaluate_outcome_candidate( - model: &dyn ModelPort, - campaign: &Campaign, - proposals: &[CellActionProposal], - context: &OutcomeContext, - proposal_bundle: OutcomeProposalBundle, - source_receipt_ids: &[String], -) -> Result { - let outcomes = match bind_outcomes(campaign, proposals, proposal_bundle) { - Ok(outcomes) => outcomes, - Err(error) => { - return Ok(OutcomeCandidateEvaluation::Rejected { - finding: error.to_string(), - verifier: None, - }); - } - }; - let semantic_outcomes = outcomes - .iter() - .filter(|outcome| is_material_outcome(&outcome.effect)) - .cloned() - .collect::>(); - if semantic_outcomes.is_empty() { - return Ok(OutcomeCandidateEvaluation::Accepted { - outcomes, - verifier: None, - }); - } - let semantic_digests = semantic_outcomes - .iter() - .map(|outcome| outcome.action_digest.clone()) - .collect::>(); - let semantic_digest_set = semantic_digests.iter().cloned().collect::>(); - let semantic_context = OutcomeContext { - world_revision: context.world_revision, - resolution_epoch: context.resolution_epoch, - actions: context - .actions - .iter() - .filter(|action| semantic_digest_set.contains(&action.action_digest)) - .cloned() - .collect(), - }; - let (verifier, mismatches) = verify_outcomes( - model, - campaign, - &semantic_context, - &semantic_outcomes, - &semantic_digests, - source_receipt_ids, - ) - .await?; - if mismatches.is_empty() { - Ok(OutcomeCandidateEvaluation::Accepted { - outcomes, - verifier: Some(verifier), - }) - } else { - Ok(OutcomeCandidateEvaluation::Rejected { - finding: mismatches.join("; "), - verifier: Some(verifier), - }) - } -} - -#[allow(clippy::too_many_arguments)] -async fn reconcile_activity_outcome( - model: &dyn ModelPort, - context: &OutcomeContext, - rejected_bundle: &OutcomeProposalBundle, - finding: &str, - source_receipt_ids: &[String], - schema: &serde_json::Value, - binding: &str, -) -> Result<(OutcomeProposalBundle, ModelStageOutput)> { - let request = ModelStageRequest { - // Reconciliation is a cheaper route to the same terminal authority, - // not a second kind of world decision. The model and causal sources - // retain how this candidate was produced. - stage: "strategic_outcome_resolver".into(), - model: MODEL_BALANCED.into(), - snapshot_binding: binding.into(), - lived_stream: format!( - "Repair one frozen strategic outcome bundle. The cell appraisal, selected attempt, action digest, snapshot, and admissible handles are immutable. Replace only the outcome bundle. Resolve the exact finding against the supplied action context. Preserve a material effect only when the attempt and an exact supplied handle causally establish it; otherwise use no_material_change with a concrete reason. Return one complete bundle and no prose.\n\nOUTPUT CONTRACT:\n{OUTCOME_PROPOSAL_OUTPUT_CONTRACT}\n\nACTION_CONTEXT:\n{}\n\nREPAIR FINDING:\n{}\n\nFROZEN REJECTED BUNDLE:\n{}", - serde_json::to_string(context)?, - finding, - serde_json::to_string(rejected_bundle)?, - ), - output_schema: Some(schema.clone()), - source_receipt_ids: source_receipt_ids.to_vec(), - temperature: Some(0.0), - max_output_tokens: Some(2_400), - }; - let stage = run_validated_stage(model, &request).await?; - let bundle = - serde_json::from_value(stage.structured.clone().ok_or_else(|| { - anyhow!("strategic outcome reconciliation produced no typed output") - })?)?; - Ok((bundle, stage)) -} - -fn reject_candidate_stage(stage: &mut ModelStageOutput, finding: &str) { - stage.receipt.validation_result = "semantic_invalid".into(); - stage.receipt.local_validation_error = Some(finding.chars().take(1_000).collect::()); -} - -fn outcome_failure(diagnostic: String, stages: &[ModelStageOutput]) -> anyhow::Error { - anyhow::Error::new(StrategicOutcomeResolutionFailure { - action_errors: vec![diagnostic], - stage_receipts: stages.iter().map(|stage| stage.receipt.clone()).collect(), - }) -} - -fn is_material_outcome(effect: &StrategicOutcomeEffect) -> bool { - !matches!(effect, StrategicOutcomeEffect::NoMaterialChange { .. }) -} - -pub fn activity_outcome_verification_binding( - campaign_id: uuid::Uuid, - world_revision: u64, - resolution_epoch: u64, - outcomes: &[StrategicActivityOutcome], -) -> Result { - let digests = outcomes - .iter() - .map(|outcome| outcome.action_digest.clone()) - .collect::>(); - let outcome_hash = format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(outcomes)?) - ); - Ok(format!( - "{}:verifier:{outcome_hash}", - activity_outcome_binding(campaign_id, world_revision, resolution_epoch, &digests,) - )) -} - -async fn verify_outcomes( - model: &dyn ModelPort, - campaign: &Campaign, - context: &OutcomeContext, - outcomes: &[StrategicActivityOutcome], - digests: &[String], - source_receipt_ids: &[String], -) -> Result<(ModelStageOutput, Vec)> { - let mut schema = serde_json::to_value(schema_for!(OutcomeVerifierBundle))?; - constrain_verifier_schema(&mut schema, digests)?; - let request = ModelStageRequest { - stage: "strategic_outcome_verifier".into(), - model: MODEL_FAST.into(), - snapshot_binding: activity_outcome_verification_binding( - campaign.id, - campaign.revision, - campaign.resolution_policy.resolution_epoch, - outcomes, - )?, - lived_stream: format!( - "You are Ghostlight's independent semantic verifier for material strategic outcomes. The local validator has already proved IDs, custody, scope, and bounds. Judge only whether each proposed durable mutation is causally entailed by that exact subject's attempt and supplied state. Return one verdict per action_digest in supplied order. Resource creation requires concrete making, repair, or preparation that establishes the named durable result. Its custodian must match the result: portable stock or equipment stays with the source, while an installed, placed, or repaired feature belongs to the exact activity location where it was established. A resource_consumed must be an exact resource the attempt actually uses, spends, gives up, damages, or transforms; reject unrelated inventory charges. A resource_transferred requires the attempt to give that exact resource to that exact recipient. A pressure addition or resolution must follow from the attempted activity rather than merely naming a current pressure. A relation shift requires an interaction capable of changing that relationship, not merely a message, proximity, or unrelated work. Member memory, obligation, and relationship effects require an event in the attempt that could create that exact personal delta. Knowledge learned requires an investigation, observation, or communication that can actually teach the source that exact fact; the fact merely appearing in supplied state or references is not enough. Knowledge communicated requires the attempt to convey that exact source-known fact to those exact recipients; addressing them without stating the fact is insufficient. result is match or mismatch. match requires null repair_guidance; mismatch requires one concrete correction sentence of at most 240 characters. Return JSON only.\n\nOUTPUT CONTRACT:\n{OUTCOME_VERIFIER_OUTPUT_CONTRACT}\n\nACTION_CONTEXT:\n{}\n\nPROPOSED_OUTCOMES:\n{}", - serde_json::to_string(context)?, - serde_json::to_string(outcomes)?, - ), - output_schema: Some(schema), - source_receipt_ids: source_receipt_ids.to_vec(), - temperature: Some(0.0), - max_output_tokens: Some(1_200), - }; - let stage = run_validated_stage(model, &request).await?; - let bundle: OutcomeVerifierBundle = serde_json::from_value( - stage - .structured - .clone() - .ok_or_else(|| anyhow!("strategic outcome verifier produced no typed output"))?, - )?; - let expected = digests.iter().cloned().collect::>(); - let mut seen = BTreeSet::new(); - let mut mismatches = Vec::new(); - for verdict in bundle.verdicts { - if !expected.contains(&verdict.action_digest) || !seen.insert(verdict.action_digest.clone()) - { - return Err(anyhow!( - "strategic outcome verifier changed or duplicated an action digest" - )); - } - match (verdict.result, verdict.repair_guidance) { - (OutcomeVerifierResult::Match, None) => {} - (OutcomeVerifierResult::Mismatch, Some(guidance)) if !guidance.trim().is_empty() => { - mismatches.push(format!( - "{}: {}", - verdict.action_digest, - guidance.chars().take(240).collect::() - )); - } - _ => { - return Err(anyhow!( - "strategic outcome verifier returned incoherent result or repair guidance" - )); - } - } - } - if seen != expected { - return Err(anyhow!( - "strategic outcome verifier omitted an action digest" - )); - } - Ok((stage, mismatches)) -} - -pub fn activity_outcome_binding( - campaign_id: uuid::Uuid, - world_revision: u64, - resolution_epoch: u64, - digests: &[String], -) -> String { - let mut exact = digests.to_vec(); - exact.sort(); - let digest = format!("sha256:{:x}", Sha256::digest(exact.join("|").as_bytes())); - format!( - "campaign:{campaign_id}:revision:{world_revision}:resolution:{resolution_epoch}:strategic-outcomes:{digest}" - ) -} - -pub fn plan_activity_digests(plan: &StrategicTickPlan) -> Vec { - plan.gestalt_activities - .iter() - .map(|activity| activity.action_digest.clone()) - .chain( - plan.actor_activities - .iter() - .map(|activity| activity.action_digest.clone()), - ) - .chain( - plan.member_activities - .iter() - .map(|activity| activity.action_digest.clone()), - ) - .collect::>() - .into_iter() - .collect() -} - -pub fn validate_activity_outcomes( - campaign: &Campaign, - proposals: &[CellActionProposal], - outcomes: &[StrategicActivityOutcome], -) -> Result<()> { - let expected = proposals - .iter() - .map(|proposal| Ok((cell_action_digest(proposal)?, proposal))) - .collect::>>()?; - validate_outcomes_against_expected(campaign, &expected, outcomes) -} - -pub fn validate_plan_activity_outcomes( - campaign: &Campaign, - plan: &StrategicTickPlan, -) -> Result<()> { - if !plan.selected_actions.is_empty() { - let selected = plan - .selected_actions - .iter() - .filter(|proposal| proposal.effects.iter().any(is_activity_effect)) - .map(|proposal| Ok((cell_action_digest(proposal)?, proposal))) - .collect::>>()?; - if selected.len() - != plan - .selected_actions - .iter() - .filter(|proposal| proposal.effects.iter().any(is_activity_effect)) - .count() - { - return Err(anyhow!( - "selected strategic activities contain duplicate action digests" - )); - } - return validate_outcomes_against_expected(campaign, &selected, &plan.activity_outcomes); - } - let synthetic = plan - .gestalt_activities - .iter() - .map(|activity| { - ( - activity.action_digest.clone(), - CellActionProposal { - subject_id: activity.gestalt_id.clone(), - intent: "committed strategic activity".into(), - intended_effect: "resolve the committed strategic activity".into(), - priority: 0, - state_references: vec![], - public_channels: activity.public_channels.clone(), - effects: vec![StrategicCellEffect::GestaltActivity { - gestalt_id: activity.gestalt_id.clone(), - activity: activity.activity.clone(), - target_subject_ids: activity.target_subject_ids.clone(), - location_ids: activity.location_ids.clone(), - }], - }, - ) - }) - .chain(plan.actor_activities.iter().map(|activity| { - ( - activity.action_digest.clone(), - CellActionProposal { - subject_id: activity.actor_id.clone(), - intent: "committed strategic activity".into(), - intended_effect: "resolve the committed strategic activity".into(), - priority: 0, - state_references: vec![], - public_channels: activity.public_channels.clone(), - effects: vec![StrategicCellEffect::ActorActivity { - actor_id: activity.actor_id.clone(), - activity: activity.activity.clone(), - target_subject_ids: activity.target_subject_ids.clone(), - location_ids: activity.location_ids.clone(), - }], - }, - ) - })) - .chain(plan.member_activities.iter().map(|activity| { - ( - activity.action_digest.clone(), - CellActionProposal { - subject_id: crate::domain::gestalt_member_subject_id(&activity.member_id), - intent: "committed strategic activity".into(), - intended_effect: "resolve the committed strategic activity".into(), - priority: 0, - state_references: vec![], - public_channels: activity.public_channels.clone(), - effects: vec![StrategicCellEffect::MemberActivity { - member_id: activity.member_id.clone(), - activity: activity.activity.clone(), - target_subject_ids: activity.target_subject_ids.clone(), - location_ids: activity.location_ids.clone(), - }], - }, - ) - })) - .collect::>(); - if synthetic.len() - != plan.gestalt_activities.len() - + plan.actor_activities.len() - + plan.member_activities.len() - { - return Err(anyhow!( - "strategic activities contain duplicate action digests" - )); - } - let expected = synthetic - .iter() - .map(|(digest, proposal)| (digest.clone(), proposal)) - .collect(); - validate_outcomes_against_expected(campaign, &expected, &plan.activity_outcomes) -} - -fn validate_outcomes_against_expected( - campaign: &Campaign, - expected: &BTreeMap, - outcomes: &[StrategicActivityOutcome], -) -> Result<()> { - if outcomes.len() != expected.len() { - return Err(anyhow!( - "every selected strategic activity requires exactly one outcome" - )); - } - let mut seen = BTreeSet::new(); - let mut exclusive_effects = BTreeSet::new(); - let mut relation_totals = BTreeMap::::new(); - for outcome in outcomes { - let proposal = expected - .get(&outcome.action_digest) - .ok_or_else(|| anyhow!("strategic outcome is not bound to a selected activity"))?; - if !seen.insert(outcome.action_digest.clone()) - || outcome.schema != "ghostlight.strategic_activity_outcome.v1" - || outcome.source_subject_id != proposal.subject_id - || !valid_sha256(&outcome.action_digest) - || !bounded_text(&outcome.summary, 240) - { - return Err(anyhow!( - "strategic outcome identity or summary is malformed" - )); - } - let allowed_references = allowed_state_references(campaign, proposal)?; - let unique_references = outcome - .supporting_state_references - .iter() - .collect::>(); - if unique_references.len() != outcome.supporting_state_references.len() { - return Err(anyhow!( - "outcome {} repeats a supporting_state_reference; each exact handle may appear once", - outcome.action_digest - )); - } - if outcome.supporting_state_references.len() > 8 { - return Err(anyhow!( - "outcome {} cites {} supporting_state_references; the exact limit is 8", - outcome.action_digest, - outcome.supporting_state_references.len() - )); - } - let unavailable_references = outcome - .supporting_state_references - .iter() - .filter(|reference| !allowed_references.contains(*reference)) - .cloned() - .collect::>(); - if !unavailable_references.is_empty() { - return Err(anyhow!( - "outcome {} cites unavailable supporting_state_references {}; copy only from this action's exact allowed_state_references {}", - outcome.action_digest, - serde_json::to_string(&unavailable_references)?, - serde_json::to_string(&allowed_references)?, - )); - } - if !matches!( - outcome.effect, - StrategicOutcomeEffect::NoMaterialChange { .. } - ) && outcome.supporting_state_references.is_empty() - { - return Err(anyhow!( - "material outcome {} requires at least one supporting_state_reference copied from its exact allowed_state_references {}", - outcome.action_digest, - serde_json::to_string(&allowed_references)?, - )); - } - validate_effect(campaign, proposal, outcome, &mut exclusive_effects).map_err(|error| { - let admissible = admissible_effect_kinds(campaign, proposal) - .and_then(|kinds| serde_json::to_string(&kinds).map_err(Into::into)) - .unwrap_or_else(|_| "[unavailable]".into()); - anyhow!( - "outcome {} is invalid: {error}; exact admissible_effect_kinds are {admissible}", - outcome.action_digest - ) - })?; - if let StrategicOutcomeEffect::AgencyRelationShift { - relation_id, - strength_delta, - } = &outcome.effect - { - *relation_totals.entry(relation_id.clone()).or_default() += *strength_delta; - } - } - if seen.len() != expected.len() { - return Err(anyhow!("strategic outcome bundle omitted an activity")); - } - for (relation_id, total) in relation_totals { - let relation = &campaign.agency_relations[&relation_id]; - if total.abs() > 10 || !(1..=100).contains(&(i16::from(relation.strength) + total)) { - return Err(anyhow!( - "strategic outcome relation shifts exceed one bounded wave" - )); - } - } - Ok(()) -} - -fn bind_outcomes( - campaign: &Campaign, - proposals: &[CellActionProposal], - bundle: OutcomeProposalBundle, -) -> Result> { - let sources = proposals - .iter() - .map(|proposal| Ok((cell_action_digest(proposal)?, proposal))) - .collect::>>()?; - let outcomes = bundle - .outcomes - .into_iter() - .map(|proposal| { - let action = sources - .get(&proposal.action_digest) - .copied() - .ok_or_else(|| anyhow!("outcome used an unknown action digest"))?; - let source_subject_id = action.subject_id.clone(); - let effect = bind_effect(&proposal)?; - let summary = resolved_outcome_summary(campaign, action, &effect)?; - Ok(StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: proposal.action_digest, - source_subject_id, - band: proposal.band, - summary, - supporting_state_references: proposal.supporting_state_references, - effect, - }) - }) - .collect::>>()?; - validate_activity_outcomes(campaign, proposals, &outcomes)?; - Ok(outcomes) -} - -fn bind_effect(proposal: &OutcomeProposal) -> Result { - let populated = proposal.populated_effect_fields(); - let require_exact = |allowed: &[&str]| -> Result<()> { - let allowed = allowed.iter().copied().collect::>(); - let irrelevant = populated.difference(&allowed).copied().collect::>(); - if !irrelevant.is_empty() { - return Err(anyhow!( - "outcome populated irrelevant fields [{}]; the chosen effect_kind permits only [{}]", - irrelevant.join(", "), - allowed.into_iter().collect::>().join(", ") - )); - } - Ok(()) - }; - Ok(match proposal.effect_kind { - OutcomeEffectKind::NoMaterialChange => { - require_exact(&["reason"])?; - StrategicOutcomeEffect::NoMaterialChange { - reason: required(&proposal.reason, "reason")?, - } - } - OutcomeEffectKind::ResourceCreated => { - require_exact(&["owner_subject_id", "resource"])?; - StrategicOutcomeEffect::ResourceCreated { - owner_subject_id: required(&proposal.owner_subject_id, "owner_subject_id")?, - resource: required(&proposal.resource, "resource")?, - } - } - OutcomeEffectKind::ResourceConsumed => { - require_exact(&["owner_subject_id", "resource"])?; - StrategicOutcomeEffect::ResourceConsumed { - owner_subject_id: required(&proposal.owner_subject_id, "owner_subject_id")?, - resource: required(&proposal.resource, "resource")?, - } - } - OutcomeEffectKind::ResourceTransferred => { - require_exact(&["owner_subject_id", "other_subject_id", "resource"])?; - StrategicOutcomeEffect::ResourceTransferred { - from_subject_id: required(&proposal.owner_subject_id, "owner_subject_id")?, - to_subject_id: required(&proposal.other_subject_id, "other_subject_id")?, - resource: required(&proposal.resource, "resource")?, - } - } - OutcomeEffectKind::GestaltPressure => { - require_exact(&[ - "owner_subject_id", - "pressure_additions", - "pressure_resolutions", - ])?; - StrategicOutcomeEffect::GestaltPressure { - gestalt_id: required(&proposal.owner_subject_id, "owner_subject_id")?, - pressure_additions: proposal.pressure_additions.clone(), - pressure_resolutions: proposal.pressure_resolutions.clone(), - } - } - OutcomeEffectKind::AgencyRelationShift => { - require_exact(&["relation_id", "strength_delta"])?; - StrategicOutcomeEffect::AgencyRelationShift { - relation_id: required(&proposal.relation_id, "relation_id")?, - strength_delta: proposal - .strength_delta - .ok_or_else(|| anyhow!("outcome omitted strength_delta"))?, - } - } - OutcomeEffectKind::MemberMemory => { - require_exact(&["member_id", "memory"])?; - StrategicOutcomeEffect::MemberMemory { - member_id: required(&proposal.member_id, "member_id")?, - memory: required(&proposal.memory, "memory")?, - } - } - OutcomeEffectKind::MemberObligation => { - require_exact(&["member_id", "obligation"])?; - StrategicOutcomeEffect::MemberObligation { - member_id: required(&proposal.member_id, "member_id")?, - obligation: required(&proposal.obligation, "obligation")?, - } - } - OutcomeEffectKind::MemberRelationship => { - require_exact(&["member_id", "other_subject_id", "relationship_description"])?; - StrategicOutcomeEffect::MemberRelationship { - member_id: required(&proposal.member_id, "member_id")?, - other_subject_id: required(&proposal.other_subject_id, "other_subject_id")?, - description: required( - &proposal.relationship_description, - "relationship_description", - )?, - } - } - OutcomeEffectKind::KnowledgeLearned => { - require_exact(&["owner_subject_id", "fact_id"])?; - StrategicOutcomeEffect::KnowledgeLearned { - owner_subject_id: required(&proposal.owner_subject_id, "owner_subject_id")?, - fact_id: required(&proposal.fact_id, "fact_id")?, - } - } - OutcomeEffectKind::KnowledgeCommunicated => { - require_exact(&["owner_subject_id", "recipient_subject_ids", "fact_id"])?; - StrategicOutcomeEffect::KnowledgeCommunicated { - from_subject_id: required(&proposal.owner_subject_id, "owner_subject_id")?, - to_subject_ids: proposal.recipient_subject_ids.clone(), - fact_id: required(&proposal.fact_id, "fact_id")?, - } - } - }) -} - -fn resolved_outcome_summary( - campaign: &Campaign, - action: &CellActionProposal, - effect: &StrategicOutcomeEffect, -) -> Result { - let source_subject_id = &action.subject_id; - let source_name = subject_name(campaign, source_subject_id)?; - let summary = match effect { - StrategicOutcomeEffect::NoMaterialChange { .. } => { - format!("{source_name}'s attempt produces no durable state change.") - } - StrategicOutcomeEffect::ResourceCreated { - owner_subject_id, - resource, - } if owner_subject_id == source_subject_id => { - format!("{source_name} creates and retains {resource}.") - } - StrategicOutcomeEffect::ResourceCreated { - owner_subject_id, - resource, - } => format!( - "At {}, {source_name} establishes {resource}.", - subject_name(campaign, owner_subject_id)? - ), - StrategicOutcomeEffect::ResourceConsumed { resource, .. } => { - format!("{source_name} expends {resource}.") - } - StrategicOutcomeEffect::ResourceTransferred { - to_subject_id, - resource, - .. - } => format!( - "{source_name} transfers {resource} to {}.", - subject_name(campaign, to_subject_id)? - ), - StrategicOutcomeEffect::GestaltPressure { - gestalt_id, - pressure_additions, - pressure_resolutions, - } => { - let owner = subject_name(campaign, gestalt_id)?; - if let Some(pressure) = pressure_additions.first() { - format!("New pressure on {owner}: {pressure}.") - } else if let Some(pressure) = pressure_resolutions.first() { - format!("A live dispute involving {owner} is settled: {pressure}.") - } else { - return Err(anyhow!("pressure outcome has no state transition")); - } - } - StrategicOutcomeEffect::AgencyRelationShift { - relation_id, - strength_delta, - } => { - let relation = campaign - .agency_relations - .get(relation_id) - .ok_or_else(|| anyhow!("relation outcome relation vanished"))?; - let direction = match (&relation.kind, *strength_delta > 0) { - (crate::domain::AgencyRelationKind::Rivalry, true) => "deepens", - (crate::domain::AgencyRelationKind::Rivalry, false) => "eases", - (_, true) => "strengthens", - (_, false) => "weakens", - }; - let action = activity_label(action); - format!( - "{action} by {source_name} {direction} the {} relationship between {} and {}.", - agency_relation_label(&relation.kind), - subject_name(campaign, &relation.from_subject_id)?, - subject_name(campaign, &relation.to_subject_id)?, - ) - } - StrategicOutcomeEffect::MemberMemory { member_id, memory } => format!( - "{} retains a new memory: {memory}.", - subject_name( - campaign, - &crate::domain::gestalt_member_subject_id(member_id) - )? - ), - StrategicOutcomeEffect::MemberObligation { - member_id, - obligation, - } => format!( - "{} accepts an obligation: {obligation}.", - subject_name( - campaign, - &crate::domain::gestalt_member_subject_id(member_id) - )? - ), - StrategicOutcomeEffect::MemberRelationship { - member_id, - other_subject_id, - description, - } => format!( - "{}'s relationship with {} becomes: {description}.", - subject_name( - campaign, - &crate::domain::gestalt_member_subject_id(member_id) - )?, - subject_name(campaign, other_subject_id)? - ), - StrategicOutcomeEffect::KnowledgeLearned { - owner_subject_id, - fact_id, - } => format!( - "{} learns: {}.", - subject_name(campaign, owner_subject_id)?, - campaign - .facts - .get(fact_id) - .ok_or_else(|| anyhow!("knowledge outcome fact vanished"))? - .statement - ), - StrategicOutcomeEffect::KnowledgeCommunicated { - to_subject_ids, - fact_id, - .. - } => { - let statement = campaign - .facts - .get(fact_id) - .ok_or_else(|| anyhow!("knowledge outcome fact vanished"))? - .statement - .trim() - .trim_end_matches(['.', '!', '?']); - format!( - "{source_name} shares this with {}: {statement}.", - to_subject_ids - .iter() - .map(|subject_id| subject_name(campaign, subject_id)) - .collect::>>()? - .join(", ") - ) - } - }; - let summary = summary - .chars() - .take(MAX_PUBLIC_EVENT_SUMMARY_CHARS) - .collect::(); - if !bounded_text(&summary, MAX_PUBLIC_EVENT_SUMMARY_CHARS) { - return Err(anyhow!("derived strategic outcome summary is empty")); - } - Ok(summary) -} - -fn activity_label(action: &CellActionProposal) -> &'static str { - let mut activities = action.effects.iter().filter_map(|effect| match effect { - StrategicCellEffect::GestaltActivity { activity, .. } - | StrategicCellEffect::ActorActivity { activity, .. } - | StrategicCellEffect::MemberActivity { activity, .. } => Some(activity), - _ => None, - }); - let Some(activity) = activities.next() else { - return "A concerted campaign"; - }; - if activities.any(|candidate| candidate != activity) { - return "A concerted campaign"; - } - match activity { - StrategicActivityKind::Prepare => "Preparations", - StrategicActivityKind::Coordinate => "An organizing effort", - StrategicActivityKind::Investigate => "An inquiry", - StrategicActivityKind::Recruit => "A recruitment drive", - StrategicActivityKind::Obstruct => "An obstruction", - StrategicActivityKind::Trade => "A trade offer", - StrategicActivityKind::Communicate if action.public_channels.is_empty() => "A message", - StrategicActivityKind::Communicate => "A public appeal", - } -} - -fn agency_relation_label(kind: &crate::domain::AgencyRelationKind) -> &'static str { - use crate::domain::AgencyRelationKind; - match kind { - AgencyRelationKind::Containment => "territorial", - AgencyRelationKind::Command => "command", - AgencyRelationKind::Membership => "membership", - AgencyRelationKind::Alliance => "alliance", - AgencyRelationKind::Rivalry => "rivalry", - AgencyRelationKind::Trade => "trade", - AgencyRelationKind::Migration => "migration", - AgencyRelationKind::Communication => "communication", - AgencyRelationKind::Coercion => "coercive", - AgencyRelationKind::SharedLocation => "local", - } -} - -impl OutcomeProposal { - fn populated_effect_fields(&self) -> BTreeSet<&'static str> { - let mut fields = BTreeSet::new(); - macro_rules! present { - ($field:ident) => { - if self.$field.is_some() { - fields.insert(stringify!($field)); - } - }; - } - present!(owner_subject_id); - present!(other_subject_id); - present!(relation_id); - present!(strength_delta); - present!(resource); - present!(member_id); - present!(memory); - present!(obligation); - present!(relationship_description); - present!(fact_id); - if !self.recipient_subject_ids.is_empty() { - fields.insert("recipient_subject_ids"); - } - present!(reason); - if !self.pressure_additions.is_empty() { - fields.insert("pressure_additions"); - } - if !self.pressure_resolutions.is_empty() { - fields.insert("pressure_resolutions"); - } - fields - } -} - -fn validate_effect( - campaign: &Campaign, - proposal: &CellActionProposal, - outcome: &StrategicActivityOutcome, - exclusive_effects: &mut BTreeSet, -) -> Result<()> { - let source = proposal.subject_id.as_str(); - let (activities, targets, locations) = activity_parts(proposal)?; - let target_set = targets.iter().cloned().collect::>(); - match &outcome.effect { - StrategicOutcomeEffect::NoMaterialChange { reason } => { - if !bounded_text(reason, 240) { - return Err(anyhow!("no-change outcome requires a bounded reason")); - } - } - StrategicOutcomeEffect::ResourceCreated { - owner_subject_id, - resource, - } => { - if owner_subject_id != source && !locations.contains(owner_subject_id) { - return Err(anyhow!( - "outcome {} resource_created owner_subject_id must be the source or one exact activity location", - outcome.action_digest - )); - } - if !activities.contains(&StrategicActivityKind::Prepare) { - return Err(anyhow!( - "outcome {} resource_created requires a prepare activity", - outcome.action_digest - )); - } - if !bounded_text(resource, 160) { - return Err(anyhow!( - "outcome {} resource_created requires one bounded resource description", - outcome.action_digest - )); - } - let existing_resources = subject_resources(campaign, owner_subject_id)?; - if contains_normalized(&existing_resources, resource) { - return Err(anyhow!( - "outcome {} resource_created repeats an existing custodian resource", - outcome.action_digest - )); - } - if existing_resources.len() >= 64 || !can_hold_resources(campaign, owner_subject_id) { - return Err(anyhow!( - "outcome {} resource_created exceeds custodian resource capacity", - outcome.action_digest - )); - } - if !outcome - .supporting_state_references - .iter() - .any(|reference| reference.starts_with("capability:")) - { - return Err(anyhow!( - "outcome {} resource_created requires one supplied capability reference", - outcome.action_digest - )); - } - if !exclusive_effects.insert(format!("resource:{owner_subject_id}:{resource}")) { - return Err(anyhow!( - "outcome {} duplicates a resource creation in this wave", - outcome.action_digest - )); - } - } - StrategicOutcomeEffect::ResourceConsumed { - owner_subject_id, - resource, - } => { - if owner_subject_id != source - || !subject_resources(campaign, source)?.contains(resource) - || !exclusive_effects.insert(format!("resource:{source}:{resource}")) - { - return Err(anyhow!("resource consumption lacks exact source custody")); - } - } - StrategicOutcomeEffect::ResourceTransferred { - from_subject_id, - to_subject_id, - resource, - } => { - if from_subject_id != source - || !target_set.contains(to_subject_id) - || is_human_controlled_actor(campaign, to_subject_id) - || !can_hold_resources(campaign, to_subject_id) - || !subject_resources(campaign, source)?.contains(resource) - || contains_normalized(&subject_resources(campaign, to_subject_id)?, resource) - || subject_resources(campaign, to_subject_id)?.len() >= 64 - || !activities.iter().any(|activity| { - matches!( - activity, - StrategicActivityKind::Trade - | StrategicActivityKind::Communicate - | StrategicActivityKind::Recruit - | StrategicActivityKind::Coordinate - ) - }) - || !exclusive_effects.insert(format!("resource:{source}:{resource}")) - { - return Err(anyhow!( - "resource transfer exceeds exact custody or target scope" - )); - } - } - StrategicOutcomeEffect::GestaltPressure { - gestalt_id, - pressure_additions, - pressure_resolutions, - } => { - let allowed = pressure_owner_ids(campaign, proposal)?; - let gestalt = campaign - .gestalts - .get(gestalt_id) - .ok_or_else(|| anyhow!("outcome pressure owner is not a gestalt"))?; - crate::resolution::validate_gestalt_pressure_transition( - &gestalt.pressures, - pressure_additions, - pressure_resolutions, - )?; - if !allowed.contains(gestalt_id) - || gestalt.pressures.len() + pressure_additions.len() - > 64 + pressure_resolutions.len() - || !exclusive_effects.insert(format!("pressure:{gestalt_id}")) - { - return Err(anyhow!( - "outcome pressure transition exceeds exact target scope" - )); - } - } - StrategicOutcomeEffect::AgencyRelationShift { - relation_id, - strength_delta, - } => { - let relation = campaign - .agency_relations - .get(relation_id) - .filter(|relation| relation.active) - .ok_or_else(|| anyhow!("outcome relation is not active"))?; - let other = if relation.from_subject_id == source { - &relation.to_subject_id - } else if relation.to_subject_id == source { - &relation.from_subject_id - } else { - return Err(anyhow!("outcome relation is not incident to its source")); - }; - if source.starts_with("member:") - || !target_set.contains(other) - || *strength_delta == 0 - || strength_delta.abs() > 10 - || !activities.iter().any(|activity| { - matches!( - activity, - StrategicActivityKind::Coordinate - | StrategicActivityKind::Recruit - | StrategicActivityKind::Obstruct - | StrategicActivityKind::Trade - | StrategicActivityKind::Communicate - ) - }) - { - return Err(anyhow!( - "outcome relation shift exceeds exact source or activity" - )); - } - } - StrategicOutcomeEffect::MemberMemory { member_id, memory } => { - validate_member_owner(source, member_id, memory, "memory", exclusive_effects)?; - let member = &campaign.gestalt_members[member_id]; - if member.memories.len() >= 64 || contains_normalized_slice(&member.memories, memory) { - return Err(anyhow!( - "member memory outcome is duplicate or over capacity" - )); - } - } - StrategicOutcomeEffect::MemberObligation { - member_id, - obligation, - } => { - validate_member_owner( - source, - member_id, - obligation, - "obligation", - exclusive_effects, - )?; - let member = &campaign.gestalt_members[member_id]; - if member.obligations.len() >= 64 - || contains_normalized(&member.obligations, obligation) - { - return Err(anyhow!( - "member obligation outcome is duplicate or over capacity" - )); - } - } - StrategicOutcomeEffect::MemberRelationship { - member_id, - other_subject_id, - description, - } => { - validate_member_owner( - source, - member_id, - description, - &format!("relationship:{other_subject_id}"), - exclusive_effects, - )?; - if !target_set.contains(other_subject_id) { - return Err(anyhow!( - "member relationship target was not part of the attempt" - )); - } - let member = &campaign.gestalt_members[member_id]; - if (member.relationships.len() >= 64 - && !member.relationships.contains_key(other_subject_id)) - || member - .relationships - .get(other_subject_id) - .is_some_and(|current| { - !crate::resolution::substantive_text_change(current, description) - }) - { - return Err(anyhow!( - "member relationship outcome is unchanged or over capacity" - )); - } - } - StrategicOutcomeEffect::KnowledgeLearned { - owner_subject_id, - fact_id, - } => { - if owner_subject_id != source - || !activities.iter().any(|activity| { - matches!( - activity, - StrategicActivityKind::Investigate | StrategicActivityKind::Communicate - ) - }) - || !discoverable_fact_ids(campaign, proposal)?.contains(fact_id) - || source_knowledge(campaign, source)?.contains(&campaign.facts[fact_id].statement) - || !exclusive_effects.insert(format!("knowledge:{source}:{fact_id}")) - { - return Err(anyhow!("knowledge outcome exceeds exact fact access")); - } - } - StrategicOutcomeEffect::KnowledgeCommunicated { - from_subject_id, - to_subject_ids, - fact_id, - } => { - let permitted = communicable_facts(campaign, proposal)? - .into_iter() - .find(|fact| fact.fact_id == *fact_id) - .ok_or_else(|| anyhow!("knowledge communication fact is not source-known"))?; - let recipients = to_subject_ids.iter().cloned().collect::>(); - let permitted_recipients = permitted - .recipient_subject_ids - .into_iter() - .collect::>(); - if from_subject_id != source - || !activities.contains(&StrategicActivityKind::Communicate) - || recipients.is_empty() - || recipients.len() != to_subject_ids.len() - || recipients.len() > 4 - || !recipients.is_subset(&target_set) - || !recipients.is_subset(&permitted_recipients) - { - return Err(anyhow!( - "knowledge communication exceeds exact speaker, fact, or recipients" - )); - } - for recipient in recipients { - if !exclusive_effects.insert(format!("knowledge:{recipient}:{fact_id}")) { - return Err(anyhow!( - "knowledge communication duplicates a recipient fact in this wave" - )); - } - } - } - } - if locations - .iter() - .any(|location| !campaign.locations.contains_key(location)) - { - return Err(anyhow!("outcome activity location vanished")); - } - Ok(()) -} - -fn validate_member_owner( - source: &str, - member_id: &str, - text: &str, - field: &str, - exclusive_effects: &mut BTreeSet, -) -> Result<()> { - if source.strip_prefix("member:") != Some(member_id) - || !bounded_text(text, 240) - || !exclusive_effects.insert(format!("member:{member_id}:{field}")) - { - return Err(anyhow!( - "member outcome does not belong to its exact person" - )); - } - Ok(()) -} - -#[cfg(test)] -fn build_context(campaign: &Campaign, proposals: &[CellActionProposal]) -> Result { - build_context_with_causal_anchors(campaign, proposals, &[]) -} - -fn build_context_with_causal_anchors( - campaign: &Campaign, - proposals: &[CellActionProposal], - causal_anchors: &[CausalAnchorOutcomeContext], -) -> Result { - Ok(OutcomeContext { - world_revision: campaign.revision, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - actions: proposals - .iter() - .map(|proposal| action_context_with_causal_anchors(campaign, proposal, causal_anchors)) - .collect::>()?, - }) -} - -#[cfg(test)] -fn action_context( - campaign: &Campaign, - proposal: &CellActionProposal, -) -> Result { - action_context_with_causal_anchors(campaign, proposal, &[]) -} - -fn action_context_with_causal_anchors( - campaign: &Campaign, - proposal: &CellActionProposal, - causal_anchors: &[CausalAnchorOutcomeContext], -) -> Result { - let (activities, targets, locations) = activity_parts(proposal)?; - let source_name = subject_name(campaign, &proposal.subject_id)?; - let source_state = subject_summary(campaign, &proposal.subject_id)?; - let target_state = targets - .iter() - .map(|target| subject_summary(campaign, target)) - .collect::>()?; - let target_set = targets.iter().collect::>(); - let active_relations = campaign - .agency_relations - .values() - .filter(|relation| { - relation.active - && ((relation.from_subject_id == proposal.subject_id - && target_set.contains(&relation.to_subject_id)) - || (relation.to_subject_id == proposal.subject_id - && target_set.contains(&relation.from_subject_id))) - }) - .map(|relation| { - serde_json::json!({ - "relation_id":relation.id, - "from_subject_id":relation.from_subject_id, - "to_subject_id":relation.to_subject_id, - "kind":relation.kind, - "strength":relation.strength, - }) - }) - .collect(); - let resource_recipient_ids = targets - .iter() - .filter(|target| { - !is_human_controlled_actor(campaign, target) && can_hold_resources(campaign, target) - }) - .cloned() - .collect(); - let discoverable_facts = discoverable_fact_ids(campaign, proposal)? - .into_iter() - .map(|fact_id| { - let fact = &campaign.facts[&fact_id]; - serde_json::json!({"fact_id":fact.id,"statement":fact.statement}) - }) - .collect(); - let communicable_facts = communicable_facts(campaign, proposal)?; - let resource_creation_owner_ids = std::iter::once(proposal.subject_id.clone()) - .chain(locations.iter().cloned()) - .filter(|owner| can_hold_resources(campaign, owner)) - .collect::>() - .into_iter() - .collect(); - Ok(ActionOutcomeContext { - action_digest: cell_action_digest(proposal)?, - source_subject_id: proposal.subject_id.clone(), - source_name, - intent: proposal.intent.clone(), - intended_effect: proposal.intended_effect.clone(), - causal_anchors: causal_anchors.to_vec(), - activities, - target_subject_ids: targets, - location_ids: locations, - source_state, - target_state, - active_relations, - pressure_owners: pressure_owner_ids(campaign, proposal)? - .into_iter() - .map(|owner_subject_id| PressureOwnerContext { - current_pressures: campaign.gestalts[&owner_subject_id] - .pressures - .iter() - .cloned() - .collect(), - owner_subject_id, - }) - .collect(), - resource_owner_id: proposal.subject_id.clone(), - resource_creation_owner_ids, - resource_recipient_ids, - discoverable_facts, - communicable_facts, - member_state_owner_id: crate::resolution::dormant_member_id_for_subject( - campaign, - &proposal.subject_id, - ) - .map(str::to_owned), - admissible_effect_kinds: admissible_effect_kinds(campaign, proposal)?, - allowed_state_references: allowed_state_references(campaign, proposal)? - .into_iter() - .collect(), - }) -} - -fn causal_anchor_contexts( - campaign: &Campaign, - proposal: &CellActionProposal, - assignments: &[CausalFollowThroughAssignment], -) -> Result> { - let matching = assignments - .iter() - .filter(|assignment| assignment.responder_subject_id == proposal.subject_id) - .collect::>(); - if matching.len() > 1 { - return Err(anyhow!( - "one strategic action cannot inherit more than one Nemesis attention anchor" - )); - } - matching - .into_iter() - .map(|assignment| { - if !proposal - .state_references - .contains(&assignment.anchor_reference) - { - return Err(anyhow!( - "Nemesis-assigned action omitted its exact causal anchor" - )); - } - let committed_account = crate::follow_through::causal_anchor_summary( - campaign, - &assignment.anchor_reference, - ) - .ok_or_else(|| anyhow!("Nemesis attention anchor is no longer grounded"))?; - Ok(CausalAnchorOutcomeContext { - anchor_reference: assignment.anchor_reference.clone(), - committed_account, - }) - }) - .collect() -} - -fn admissible_effect_kinds( - campaign: &Campaign, - proposal: &CellActionProposal, -) -> Result> { - let (activities, targets, _) = activity_parts(proposal)?; - let source = proposal.subject_id.as_str(); - let resources = subject_resources(campaign, source)?; - let references = allowed_state_references(campaign, proposal)?; - let mut kinds = vec![OutcomeEffectKind::NoMaterialChange]; - - if activities.contains(&StrategicActivityKind::Prepare) - && resources.len() < 64 - && can_hold_resources(campaign, source) - && references - .iter() - .any(|reference| reference.starts_with("capability:")) - { - kinds.push(OutcomeEffectKind::ResourceCreated); - } - if !resources.is_empty() { - kinds.push(OutcomeEffectKind::ResourceConsumed); - } - if !resources.is_empty() - && activities.iter().any(|activity| { - matches!( - activity, - StrategicActivityKind::Trade - | StrategicActivityKind::Communicate - | StrategicActivityKind::Recruit - | StrategicActivityKind::Coordinate - ) - }) - && targets.iter().any(|target| { - !is_human_controlled_actor(campaign, target) && can_hold_resources(campaign, target) - }) - { - kinds.push(OutcomeEffectKind::ResourceTransferred); - } - if !pressure_owner_ids(campaign, proposal)?.is_empty() { - kinds.push(OutcomeEffectKind::GestaltPressure); - } - if crate::resolution::dormant_member_id_for_subject(campaign, source).is_none() - && activities.iter().any(|activity| { - matches!( - activity, - StrategicActivityKind::Coordinate - | StrategicActivityKind::Recruit - | StrategicActivityKind::Obstruct - | StrategicActivityKind::Trade - | StrategicActivityKind::Communicate - ) - }) - && campaign.agency_relations.values().any(|relation| { - relation.active - && ((relation.from_subject_id == source - && targets.contains(&relation.to_subject_id)) - || (relation.to_subject_id == source - && targets.contains(&relation.from_subject_id))) - }) - { - kinds.push(OutcomeEffectKind::AgencyRelationShift); - } - if let Some(member_id) = crate::resolution::dormant_member_id_for_subject(campaign, source) { - let member = &campaign.gestalt_members[member_id]; - if member.memories.len() < 64 { - kinds.push(OutcomeEffectKind::MemberMemory); - } - if member.obligations.len() < 64 - && activities.iter().any(|activity| { - matches!( - activity, - StrategicActivityKind::Communicate - | StrategicActivityKind::Coordinate - | StrategicActivityKind::Recruit - | StrategicActivityKind::Trade - ) - }) - { - kinds.push(OutcomeEffectKind::MemberObligation); - } - if !targets.is_empty() { - kinds.push(OutcomeEffectKind::MemberRelationship); - } - } - if activities.iter().any(|activity| { - matches!( - activity, - StrategicActivityKind::Investigate | StrategicActivityKind::Communicate - ) - }) && !discoverable_fact_ids(campaign, proposal)?.is_empty() - { - kinds.push(OutcomeEffectKind::KnowledgeLearned); - } - if !communicable_facts(campaign, proposal)?.is_empty() { - kinds.push(OutcomeEffectKind::KnowledgeCommunicated); - } - Ok(kinds) -} - -fn subject_summary(campaign: &Campaign, subject_id: &str) -> Result { - if let Some(actor) = campaign.actors.get(subject_id) { - return Ok(serde_json::json!({ - "subject_id":subject_id,"name":actor.name,"kind":"actor", - "capabilities":actor.capabilities,"knowledge":actor.knowledge, - "resources":actor.equipment,"conditions":actor.conditions, - "obligations":actor.obligations,"relationships":actor.relationships,"goals":actor.goals, - })); - } - if let Some(member_id) = crate::resolution::dormant_member_id_for_subject(campaign, subject_id) - { - let member = campaign - .gestalt_members - .get(member_id) - .ok_or_else(|| anyhow!("outcome context member vanished"))?; - return Ok(serde_json::json!({ - "subject_id":subject_id, - "name":member.name, - "kind":"member", - "gestalt_id":member.gestalt_id, - "capabilities":crate::resolution::effective_member_capabilities(campaign, member_id)?, - "knowledge":effective_member_knowledge(campaign, member_id)?, - "resources":member.equipment, - "conditions":member.conditions, - "obligations":member.obligations, - "relationships":member.relationships, - "goals":member.goals, - })); - } - if let Some(gestalt) = campaign.gestalts.get(subject_id) { - return Ok(serde_json::json!({ - "subject_id":subject_id,"name":gestalt.name,"kind":"gestalt", - "capabilities":gestalt.shared_capabilities,"knowledge":gestalt.shared_knowledge, - "resources":gestalt.resources,"goals":gestalt.goals,"pressures":gestalt.pressures, - })); - } - if let Some(institution) = campaign.institutions.get(subject_id) { - return Ok(serde_json::json!({ - "subject_id":subject_id,"name":institution.name,"kind":"institution", - "resources":institution.resources,"goals":institution.goals,"posture":institution.posture, - })); - } - Err(anyhow!("outcome context subject vanished")) -} - -fn allowed_state_references( - campaign: &Campaign, - proposal: &CellActionProposal, -) -> Result> { - let mut references = if let Some(member_id) = - crate::resolution::dormant_member_id_for_subject(campaign, &proposal.subject_id) - { - crate::resolution::member_state_references(campaign, member_id)? - } else { - subject_state_references(campaign, &proposal.subject_id)? - }; - for relation in campaign - .agency_relations - .values() - .filter(|relation| relation.active) - { - if relation.from_subject_id == proposal.subject_id - || relation.to_subject_id == proposal.subject_id - { - references.insert(format!("relation:{}", relation.id)); - } - } - for owner_id in pressure_owner_ids(campaign, proposal)? { - if let Some(gestalt) = campaign.gestalts.get(&owner_id) { - references.extend( - gestalt - .pressures - .iter() - .map(|pressure| format!("pressure:{owner_id}:{pressure}")), - ); - } - } - for fact_id in discoverable_fact_ids(campaign, proposal)? { - references.insert(format!("fact:{fact_id}")); - } - for fact in communicable_facts(campaign, proposal)? { - references.insert(format!("fact:{}", fact.fact_id)); - } - Ok(references) -} - -fn pressure_owner_ids( - campaign: &Campaign, - proposal: &CellActionProposal, -) -> Result> { - let (_, targets, _) = activity_parts(proposal)?; - let mut ids = targets - .into_iter() - .filter(|target| campaign.gestalts.contains_key(target)) - .collect::>(); - if campaign.gestalts.contains_key(&proposal.subject_id) { - ids.insert(proposal.subject_id.clone()); - } - Ok(ids) -} - -fn discoverable_fact_ids( - campaign: &Campaign, - proposal: &CellActionProposal, -) -> Result> { - let (activities, targets, locations) = activity_parts(proposal)?; - let mut facts = campaign - .facts - .values() - .filter(|fact| { - !fact.discoverable_at_location_ids.is_empty() - && locations - .iter() - .any(|location| fact.discoverable_at_location_ids.contains(location)) - }) - .map(|fact| fact.id.clone()) - .collect::>(); - if activities.contains(&StrategicActivityKind::Communicate) { - for target in targets { - if is_human_controlled_actor(campaign, &target) { - continue; - } - let known = source_knowledge(campaign, &target)?; - facts.extend( - campaign - .facts - .values() - .filter(|fact| known.contains(&fact.id) || known.contains(&fact.statement)) - .map(|fact| fact.id.clone()), - ); - } - } - let source_known = source_knowledge(campaign, &proposal.subject_id)?; - facts.retain(|fact_id| { - let fact = &campaign.facts[fact_id]; - !source_known.contains(fact_id) && !source_known.contains(&fact.statement) - }); - Ok(facts) -} - -fn communicable_facts( - campaign: &Campaign, - proposal: &CellActionProposal, -) -> Result> { - let (activities, targets, _) = activity_parts(proposal)?; - if !activities.contains(&StrategicActivityKind::Communicate) { - return Ok(Vec::new()); - } - let source_known = source_knowledge(campaign, &proposal.subject_id)?; - let mut facts = Vec::new(); - for fact in campaign - .facts - .values() - .filter(|fact| source_known.contains(&fact.id) || source_known.contains(&fact.statement)) - { - let mut recipient_subject_ids = Vec::new(); - for target in &targets { - if is_human_controlled_actor(campaign, target) || !can_hold_knowledge(campaign, target) - { - continue; - } - let target_known = source_knowledge(campaign, target)?; - if !target_known.contains(&fact.id) && !target_known.contains(&fact.statement) { - recipient_subject_ids.push(target.clone()); - } - } - if !recipient_subject_ids.is_empty() { - facts.push(CommunicableFactContext { - fact_id: fact.id.clone(), - statement: fact.statement.clone(), - recipient_subject_ids, - }); - } - } - Ok(facts) -} - -fn can_hold_knowledge(campaign: &Campaign, subject_id: &str) -> bool { - campaign.actors.contains_key(subject_id) - || campaign.gestalts.contains_key(subject_id) - || crate::resolution::dormant_member_id_for_subject(campaign, subject_id).is_some() -} - -fn source_knowledge(campaign: &Campaign, subject_id: &str) -> Result> { - if let Some(gestalt) = campaign.gestalts.get(subject_id) { - return Ok(gestalt.shared_knowledge.clone()); - } - if let Some(actor) = campaign.actors.get(subject_id) { - return Ok(actor.knowledge.clone()); - } - if let Some(member_id) = crate::resolution::dormant_member_id_for_subject(campaign, subject_id) - { - return effective_member_knowledge(campaign, member_id); - } - Ok(BTreeSet::new()) -} - -pub fn subject_resources(campaign: &Campaign, subject_id: &str) -> Result> { - if let Some(actor) = campaign.actors.get(subject_id) { - return Ok(actor.equipment.clone()); - } - if let Some(member_id) = crate::resolution::dormant_member_id_for_subject(campaign, subject_id) - { - return campaign - .gestalt_members - .get(member_id) - .map(|member| member.equipment.clone()) - .ok_or_else(|| anyhow!("resource owner member is unknown")); - } - if let Some(gestalt) = campaign.gestalts.get(subject_id) { - return Ok(gestalt.resources.clone()); - } - if let Some(institution) = campaign.institutions.get(subject_id) { - return Ok(institution.resources.iter().cloned().collect()); - } - if let Some(location) = campaign.locations.get(subject_id) { - return Ok(location.persistent_features.iter().cloned().collect()); - } - Err(anyhow!("resource owner is unknown")) -} - -pub fn can_hold_resources(campaign: &Campaign, subject_id: &str) -> bool { - subject_id - .strip_prefix("member:") - .is_some_and(|member_id| campaign.gestalt_members.contains_key(member_id)) - || campaign.gestalts.contains_key(subject_id) - || campaign.institutions.contains_key(subject_id) - || campaign.actors.contains_key(subject_id) - || campaign.locations.contains_key(subject_id) -} - -fn is_human_controlled_actor(campaign: &Campaign, subject_id: &str) -> bool { - subject_id == campaign.player_actor_id - || campaign - .agency_profiles - .get(subject_id) - .is_some_and(|profile| !profile.simulation_eligible) -} - -fn activity_parts( - proposal: &CellActionProposal, -) -> Result<(Vec, Vec, Vec)> { - let activity_effects = proposal - .effects - .iter() - .filter(|effect| is_activity_effect(effect)) - .collect::>(); - if activity_effects.is_empty() { - return Err(anyhow!( - "strategic outcome was requested for a non-activity" - )); - } - let mut activities = Vec::with_capacity(activity_effects.len()); - let mut targets = BTreeSet::new(); - let mut locations = BTreeSet::new(); - for effect in activity_effects { - let (activity, effect_targets, effect_locations) = match effect { - StrategicCellEffect::GestaltActivity { - activity, - target_subject_ids, - location_ids, - .. - } - | StrategicCellEffect::ActorActivity { - activity, - target_subject_ids, - location_ids, - .. - } - | StrategicCellEffect::MemberActivity { - activity, - target_subject_ids, - location_ids, - .. - } => (activity, target_subject_ids, location_ids), - _ => unreachable!("activity filter admitted a non-activity"), - }; - if !activities.contains(activity) { - activities.push(activity.clone()); - } - targets.extend(effect_targets.iter().cloned()); - locations.extend(effect_locations.iter().cloned()); - } - Ok(( - activities, - targets.into_iter().collect(), - locations.into_iter().collect(), - )) -} - -fn is_activity_effect(effect: &StrategicCellEffect) -> bool { - matches!( - effect, - StrategicCellEffect::GestaltActivity { .. } - | StrategicCellEffect::ActorActivity { .. } - | StrategicCellEffect::MemberActivity { .. } - ) -} - -fn subject_name(campaign: &Campaign, subject_id: &str) -> Result { - campaign - .actors - .get(subject_id) - .map(|value| value.name.clone()) - .or_else(|| { - campaign - .institutions - .get(subject_id) - .map(|value| value.name.clone()) - }) - .or_else(|| { - campaign - .gestalts - .get(subject_id) - .map(|value| value.name.clone()) - }) - .or_else(|| { - crate::resolution::dormant_member_id_for_subject(campaign, subject_id).and_then( - |member_id| { - campaign - .gestalt_members - .get(member_id) - .map(|value| value.name.clone()) - }, - ) - }) - .or_else(|| { - campaign - .locations - .get(subject_id) - .map(|value| value.name.clone()) - }) - .ok_or_else(|| anyhow!("outcome source vanished")) -} - -fn outcome_source_receipts(campaign: &Campaign, proposal: &CellActionProposal) -> Vec { - let mut ids = Vec::new(); - let mut subjects = vec![proposal.subject_id.clone()]; - if let Ok((_, targets, _)) = activity_parts(proposal) { - subjects.extend(targets); - } - for subject in subjects { - let profile_id = crate::resolution::dormant_member_id_for_subject(campaign, &subject) - .and_then(|member_id| campaign.gestalt_members.get(member_id)) - .map(|member| member.gestalt_id.as_str()) - .unwrap_or(&subject); - if let Some(profile) = campaign.agency_profiles.get(profile_id) { - ids.extend(profile.evidence_receipt_ids.clone()); - } - } - ids -} - -fn constrain_outcome_schema( - schema: &mut serde_json::Value, - actions: &[ActionOutcomeContext], -) -> Result<()> { - { - let outcomes = schema - .pointer_mut("/properties/outcomes") - .ok_or_else(|| anyhow!("strategic outcome schema has no outcomes property"))?; - outcomes["minItems"] = serde_json::json!(actions.len()); - outcomes["maxItems"] = serde_json::json!(actions.len()); - } - let proposal = schema - .pointer_mut("/$defs/OutcomeProposal") - .ok_or_else(|| anyhow!("strategic outcome schema has no proposal definition"))?; - for field in [ - "pressure_additions", - "pressure_resolutions", - "recipient_subject_ids", - ] { - let array_schema = proposal["properties"][field].take(); - proposal["properties"][field] = serde_json::json!({ - "anyOf":[array_schema,{"type":"null"}] - }); - } - proposal["required"] = serde_json::json!([ - "action_digest", - "band", - "effect_kind", - "supporting_state_references" - ]); - proposal["properties"]["action_digest"] = exact_string_value_schema( - &actions - .iter() - .map(|action| action.action_digest.clone()) - .collect::>(), - ); - let mut constraints = vec![serde_json::json!({ - "oneOf":outcome_effect_shape_schemas() - })]; - constraints.extend(actions.iter().map(|action| { - serde_json::json!({ - "if":{ - "properties":{"action_digest":{"const":action.action_digest}}, - "required":["action_digest"] - }, - "then":outcome_action_scope_schema(action) - }) - })); - proposal["allOf"] = serde_json::json!(constraints); - Ok(()) -} - -fn outcome_effect_shape_schemas() -> Vec { - vec![ - outcome_effect_shape(OutcomeEffectKind::NoMaterialChange, &["reason"], false), - outcome_effect_shape( - OutcomeEffectKind::ResourceCreated, - &["owner_subject_id", "resource"], - true, - ), - outcome_effect_shape( - OutcomeEffectKind::ResourceConsumed, - &["owner_subject_id", "resource"], - true, - ), - outcome_effect_shape( - OutcomeEffectKind::ResourceTransferred, - &["owner_subject_id", "other_subject_id", "resource"], - true, - ), - outcome_effect_shape( - OutcomeEffectKind::GestaltPressure, - &[ - "owner_subject_id", - "pressure_additions", - "pressure_resolutions", - ], - true, - ), - outcome_effect_shape( - OutcomeEffectKind::AgencyRelationShift, - &["relation_id", "strength_delta"], - true, - ), - outcome_effect_shape( - OutcomeEffectKind::MemberMemory, - &["member_id", "memory"], - true, - ), - outcome_effect_shape( - OutcomeEffectKind::MemberObligation, - &["member_id", "obligation"], - true, - ), - outcome_effect_shape( - OutcomeEffectKind::MemberRelationship, - &["member_id", "other_subject_id", "relationship_description"], - true, - ), - outcome_effect_shape( - OutcomeEffectKind::KnowledgeLearned, - &["owner_subject_id", "fact_id"], - true, - ), - outcome_effect_shape( - OutcomeEffectKind::KnowledgeCommunicated, - &["owner_subject_id", "recipient_subject_ids", "fact_id"], - true, - ), - ] -} - -fn outcome_effect_shape( - effect_kind: OutcomeEffectKind, - required_effect_fields: &[&str], - material: bool, -) -> serde_json::Value { - const EFFECT_FIELDS: [&str; 14] = [ - "owner_subject_id", - "other_subject_id", - "relation_id", - "strength_delta", - "resource", - "pressure_additions", - "pressure_resolutions", - "member_id", - "memory", - "obligation", - "relationship_description", - "fact_id", - "recipient_subject_ids", - "reason", - ]; - let forbidden = EFFECT_FIELDS - .iter() - .filter(|field| !required_effect_fields.contains(field)) - .map(|field| { - if matches!( - *field, - "pressure_additions" | "pressure_resolutions" | "recipient_subject_ids" - ) { - serde_json::json!({ - "required":[field], - "properties":{(*field):{"type":"array","minItems":1}} - }) - } else { - serde_json::json!({ - "required":[field], - "properties":{(*field):{"not":{"type":"null"}}} - }) - } - }) - .collect::>(); - let mut required = vec!["effect_kind"]; - required.extend_from_slice(required_effect_fields); - let mut shape = serde_json::json!({ - "properties":{ - "effect_kind":{"const":effect_kind}, - "supporting_state_references":if material { - serde_json::json!({"minItems":1,"maxItems":8}) - } else { - serde_json::json!({"maxItems":0}) - } - }, - "required":required - }); - for field in required_effect_fields.iter() { - shape["properties"][*field] = if matches!( - *field, - "pressure_additions" | "pressure_resolutions" | "recipient_subject_ids" - ) { - serde_json::json!({"type":"array"}) - } else { - serde_json::json!({"not":{"type":"null"}}) - }; - } - if !forbidden.is_empty() { - shape["not"] = serde_json::json!({"anyOf":forbidden}); - } - shape -} - -fn outcome_action_scope_schema(action: &ActionOutcomeContext) -> serde_json::Value { - let mut constraints = Vec::new(); - let admits = |kind: &OutcomeEffectKind| action.admissible_effect_kinds.contains(kind); - let source_resources = action - .source_state - .get("resources") - .and_then(serde_json::Value::as_array) - .into_iter() - .flatten() - .filter_map(serde_json::Value::as_str) - .map(str::to_owned) - .collect::>(); - let admitted_existing_resource_kinds = [ - OutcomeEffectKind::ResourceConsumed, - OutcomeEffectKind::ResourceTransferred, - ] - .into_iter() - .filter(|kind| admits(kind)) - .collect::>(); - if !admitted_existing_resource_kinds.is_empty() { - constraints.push(effect_scope_condition( - &admitted_existing_resource_kinds, - serde_json::json!({ - "properties":{"owner_subject_id":{"const":action.resource_owner_id}} - }), - )); - } - if admits(&OutcomeEffectKind::ResourceCreated) { - constraints.push(effect_scope_condition( - &[OutcomeEffectKind::ResourceCreated], - serde_json::json!({ - "properties":{ - "owner_subject_id":exact_string_value_schema(&action.resource_creation_owner_ids), - "resource":{"type":"string","minLength":1,"maxLength":160} - } - }), - )); - } - if !admitted_existing_resource_kinds.is_empty() { - constraints.push(effect_scope_condition( - &admitted_existing_resource_kinds, - serde_json::json!({ - "properties":{"resource":exact_string_value_schema(&source_resources)} - }), - )); - } - if admits(&OutcomeEffectKind::ResourceTransferred) { - constraints.push(effect_scope_condition( - &[OutcomeEffectKind::ResourceTransferred], - serde_json::json!({ - "properties":{"other_subject_id":exact_string_value_schema(&action.resource_recipient_ids)} - }), - )); - } - if admits(&OutcomeEffectKind::GestaltPressure) { - let pressure_owner_constraints = action - .pressure_owners - .iter() - .map(|owner| { - serde_json::json!({ - "if":{ - "properties":{"owner_subject_id":{"const":owner.owner_subject_id}}, - "required":["owner_subject_id"] - }, - "then":{ - "properties":{ - "pressure_additions":{ - "type":"array","uniqueItems":true,"maxItems":4, - "items":{ - "type":"string","minLength":1,"maxLength":240 - } - }, - "pressure_resolutions":exact_string_array_value_schema( - &owner.current_pressures, - 0, - owner.current_pressures.len().min(4) - ) - }, - "anyOf":[ - {"properties":{"pressure_additions":{"minItems":1}}}, - {"properties":{"pressure_resolutions":{"minItems":1}}} - ] - } - }) - }) - .collect::>(); - let pressure_owner_ids = action - .pressure_owners - .iter() - .map(|owner| owner.owner_subject_id.clone()) - .collect::>(); - constraints.push(effect_scope_condition( - &[OutcomeEffectKind::GestaltPressure], - serde_json::json!({ - "properties":{ - "owner_subject_id":exact_string_value_schema(&pressure_owner_ids) - }, - "allOf":pressure_owner_constraints - }), - )); - } - let relation_ids = action - .active_relations - .iter() - .filter_map(|relation| relation.get("relation_id")) - .filter_map(serde_json::Value::as_str) - .map(str::to_owned) - .collect::>(); - if admits(&OutcomeEffectKind::AgencyRelationShift) { - constraints.push(effect_scope_condition( - &[OutcomeEffectKind::AgencyRelationShift], - serde_json::json!({ - "properties":{ - "relation_id":exact_string_value_schema(&relation_ids), - "strength_delta":{"type":"integer","enum":[-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,1,2,3,4,5,6,7,8,9,10]} - } - }), - )); - } - let admitted_member_kinds = [ - OutcomeEffectKind::MemberMemory, - OutcomeEffectKind::MemberObligation, - OutcomeEffectKind::MemberRelationship, - ] - .into_iter() - .filter(|kind| admits(kind)) - .collect::>(); - if !admitted_member_kinds.is_empty() { - if let Some(member_id) = &action.member_state_owner_id { - constraints.push(effect_scope_condition( - &admitted_member_kinds, - serde_json::json!({ - "properties":{"member_id":{"const":member_id}} - }), - )); - } - } - if admits(&OutcomeEffectKind::MemberMemory) { - constraints.push(effect_scope_condition( - &[OutcomeEffectKind::MemberMemory], - serde_json::json!({"properties":{"memory":{"type":"string","minLength":1,"maxLength":240}}}), - )); - } - if admits(&OutcomeEffectKind::MemberObligation) { - constraints.push(effect_scope_condition( - &[OutcomeEffectKind::MemberObligation], - serde_json::json!({"properties":{"obligation":{"type":"string","minLength":1,"maxLength":240}}}), - )); - } - if admits(&OutcomeEffectKind::MemberRelationship) { - constraints.push(effect_scope_condition( - &[OutcomeEffectKind::MemberRelationship], - serde_json::json!({ - "properties":{ - "other_subject_id":exact_string_value_schema(&action.target_subject_ids), - "relationship_description":{"type":"string","minLength":1,"maxLength":240} - } - }), - )); - } - let fact_ids = action - .discoverable_facts - .iter() - .filter_map(|fact| fact.get("fact_id")) - .filter_map(serde_json::Value::as_str) - .map(str::to_owned) - .collect::>(); - if admits(&OutcomeEffectKind::KnowledgeLearned) { - constraints.push(effect_scope_condition( - &[OutcomeEffectKind::KnowledgeLearned], - serde_json::json!({ - "properties":{ - "owner_subject_id":{"const":action.source_subject_id}, - "fact_id":exact_string_value_schema(&fact_ids) - } - }), - )); - } - if admits(&OutcomeEffectKind::KnowledgeCommunicated) { - let fact_constraints = action - .communicable_facts - .iter() - .map(|fact| { - serde_json::json!({ - "if":{ - "properties":{"fact_id":{"const":fact.fact_id}}, - "required":["fact_id"] - }, - "then":{ - "properties":{ - "recipient_subject_ids":exact_string_array_value_schema( - &fact.recipient_subject_ids, - 1, - fact.recipient_subject_ids.len().min(4) - ) - } - } - }) - }) - .collect::>(); - let fact_ids = action - .communicable_facts - .iter() - .map(|fact| fact.fact_id.clone()) - .collect::>(); - constraints.push(effect_scope_condition( - &[OutcomeEffectKind::KnowledgeCommunicated], - serde_json::json!({ - "properties":{ - "owner_subject_id":{"const":action.source_subject_id}, - "fact_id":exact_string_value_schema(&fact_ids) - }, - "allOf":fact_constraints - }), - )); - } - constraints.push(effect_scope_condition( - &[OutcomeEffectKind::NoMaterialChange], - serde_json::json!({"properties":{"reason":{"type":"string","minLength":1,"maxLength":240}}}), - )); - serde_json::json!({ - "properties":{ - "action_digest":{"const":action.action_digest}, - "effect_kind":{"enum":action.admissible_effect_kinds}, - "supporting_state_references":exact_string_array_value_schema( - &action.allowed_state_references, - 0, - action.allowed_state_references.len().min(8) - ) - }, - "required":["action_digest"], - "allOf":constraints - }) -} - -fn effect_scope_condition( - effect_kinds: &[OutcomeEffectKind], - consequence: serde_json::Value, -) -> serde_json::Value { - serde_json::json!({ - "if":{ - "properties":{"effect_kind":{"enum":effect_kinds}}, - "required":["effect_kind"] - }, - "then":consequence - }) -} - -fn exact_string_value_schema(values: &[String]) -> serde_json::Value { - serde_json::json!({"type":"string","enum":values}) -} - -fn exact_string_array_value_schema( - values: &[String], - min_items: usize, - max_items: usize, -) -> serde_json::Value { - if values.is_empty() { - return serde_json::json!({ - "type":"array", - "minItems":min_items, - "maxItems":0 - }); - } - serde_json::json!({ - "type":"array", - "uniqueItems":true, - "minItems":min_items, - "maxItems":max_items, - "items":exact_string_value_schema(values) - }) -} - -fn constrain_verifier_schema(schema: &mut serde_json::Value, digests: &[String]) -> Result<()> { - let verdicts = schema - .pointer_mut("/properties/verdicts") - .ok_or_else(|| anyhow!("strategic outcome verifier schema has no verdicts property"))?; - verdicts["minItems"] = serde_json::json!(digests.len()); - verdicts["maxItems"] = serde_json::json!(digests.len()); - let verdict = schema - .pointer_mut("/$defs/OutcomeVerifierVerdict") - .ok_or_else(|| anyhow!("strategic outcome verifier schema has no verdict definition"))?; - *verdict = serde_json::json!({ - "oneOf":[ - { - "type":"object", - "additionalProperties":false, - "required":["action_digest", "result", "repair_guidance"], - "properties":{ - "action_digest":{"enum":digests}, - "result":{"const":"match"}, - "repair_guidance":{"type":"null"} - } - }, - { - "type":"object", - "additionalProperties":false, - "required":["action_digest", "result", "repair_guidance"], - "properties":{ - "action_digest":{"enum":digests}, - "result":{"const":"mismatch"}, - "repair_guidance":{ - "type":"string", - "minLength":1 - } - } - } - ] - }); - Ok(()) -} - -fn required(value: &Option, field: &str) -> Result { - value - .clone() - .filter(|value| !value.trim().is_empty()) - .ok_or_else(|| anyhow!("outcome omitted {field}")) -} - -fn bounded_text(value: &str, max: usize) -> bool { - !value.trim().is_empty() && value.chars().count() <= max -} - -fn contains_normalized(values: &BTreeSet, candidate: &str) -> bool { - values - .iter() - .any(|value| value.eq_ignore_ascii_case(candidate)) -} - -fn contains_normalized_slice(values: &[String], candidate: &str) -> bool { - values - .iter() - .any(|value| value.eq_ignore_ascii_case(candidate)) -} - -fn valid_sha256(value: &str) -> bool { - value - .strip_prefix("sha256:") - .is_some_and(|hex| hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit())) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - domain::{ - AgencyProfile, AgencyRelation, AgencyRelationKind, AgencySubjectKind, BranchOrigin, - Event, GestaltPersonaState, Location, ResolutionPolicy, WorldFact, - }, - resolution::ensure_agency_profiles, - }; - use chrono::Utc; - use std::sync::Mutex; - use uuid::Uuid; - - struct OutcomeFixtureModel { - action_digest: String, - requests: Mutex>, - } - - struct RejectingVerifierModel { - action_digest: String, - } - - struct CorrectingOutcomeModel { - action_digest: String, - resolver_calls: Mutex, - } - - struct CorrectingKnowledgeModel { - action_digest: String, - resolver_calls: Mutex, - requests: Mutex>, - } - - struct RepeatingPressureModel { - action_digest: String, - requests: Mutex>, - } - - struct PersistentlyMismatchedOutcomeModel { - action_digest: String, - requests: Mutex>, - } - - struct IsolatingOutcomeModel { - requests: Mutex>, - } - - #[async_trait::async_trait] - impl ModelPort for IsolatingOutcomeModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - assert_eq!(request.stage, "strategic_outcome_resolver"); - self.requests.lock().unwrap().push(request.clone()); - let (_, payload) = request - .lived_stream - .rsplit_once("OUTCOME_CONTEXT:\n") - .ok_or_else(|| anyhow!("fixture request omitted outcome context"))?; - let context: serde_json::Value = serde_json::from_str(payload)?; - let actions = context["actions"] - .as_array() - .ok_or_else(|| anyhow!("fixture context omitted actions"))?; - if actions.len() != 1 { - return Err(anyhow!( - "unrelated strategic actions shared one resolver context" - )); - } - let digest = actions[0]["action_digest"] - .as_str() - .ok_or_else(|| anyhow!("fixture action omitted digest"))?; - Ok(serde_json::json!({ - "outcomes":[{ - "action_digest":digest, - "band":"mixed", - "effect_kind":"no_material_change", - "supporting_state_references":[], - "reason":"This exact attempt establishes no durable change." - }] - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "isolating-outcome-model" - } - } - - #[async_trait::async_trait] - impl ModelPort for RepeatingPressureModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - let mut requests = self.requests.lock().unwrap(); - requests.push(request.clone()); - if requests.len() == 1 { - return Ok(serde_json::json!({ - "outcomes":[{ - "action_digest":self.action_digest, - "band":"mixed", - "effect_kind":"gestalt_pressure", - "supporting_state_references":["pressure:dockers:storm damage"], - "owner_subject_id":"dockers", - "pressure_additions":["storm damage"], - "pressure_resolutions":[] - }] - }) - .to_string()); - } - Ok(serde_json::json!({ - "outcomes":[{ - "action_digest":self.action_digest, - "band":"mixed", - "effect_kind":"no_material_change", - "supporting_state_references":[], - "reason":"The preparation does not yet establish a new durable pressure or resolve the existing storm damage." - }] - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "repeating-pressure-model" - } - } - - #[async_trait::async_trait] - impl ModelPort for PersistentlyMismatchedOutcomeModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.requests.lock().unwrap().push(request.clone()); - if request.stage == "strategic_outcome_verifier" { - return Ok(serde_json::json!({ - "verdicts":[{ - "action_digest":self.action_digest, - "result":"mismatch", - "repair_guidance":"The attempt does not establish this fact; use no_material_change." - }] - }) - .to_string()); - } - Ok(serde_json::json!({ - "outcomes":[{ - "action_digest":self.action_digest, - "band":"mixed", - "effect_kind":"knowledge_learned", - "supporting_state_references":["fact:fact:safe-route"], - "owner_subject_id":"dockers", - "fact_id":"fact:safe-route" - }] - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "persistently-mismatched-outcome-model" - } - } - - #[async_trait::async_trait] - impl ModelPort for CorrectingOutcomeModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - if request.stage == "strategic_outcome_verifier" { - let rejects_consumption = request - .lived_stream - .contains("\"type\":\"resource_consumed\""); - return Ok(serde_json::json!({ - "verdicts":[{ - "action_digest":self.action_digest, - "result":if rejects_consumption {"mismatch"} else {"match"}, - "repair_guidance":if rejects_consumption { - Some("The inspection does not use spare rope; choose no_material_change.") - } else { - None - } - }] - }) - .to_string()); - } - let mut calls = self.resolver_calls.lock().unwrap(); - *calls += 1; - if *calls == 1 { - return Ok(serde_json::json!({ - "outcomes":[{ - "action_digest":self.action_digest, - "band":"mixed", - "effect_kind":"resource_consumed", - "supporting_state_references":["resource:spare rope"], - "owner_subject_id":"dockers", - "resource":"spare rope" - }] - }) - .to_string()); - } - Ok(serde_json::json!({ - "outcomes":[{ - "action_digest":self.action_digest, - "band":"mixed", - "effect_kind":"knowledge_learned", - "supporting_state_references":["fact:fact:safe-route"], - "owner_subject_id":"dockers", - "fact_id":"fact:safe-route" - }] - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "correcting-outcome-model" - } - } - - #[async_trait::async_trait] - impl ModelPort for CorrectingKnowledgeModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.requests.lock().unwrap().push(request.clone()); - if request.stage == "strategic_outcome_verifier" { - let rejects_uncommunicated_fact = request - .lived_stream - .contains("\"type\":\"knowledge_learned\""); - return Ok(serde_json::json!({ - "verdicts":[{ - "action_digest":self.action_digest, - "result":if rejects_uncommunicated_fact {"mismatch"} else {"match"}, - "repair_guidance":if rejects_uncommunicated_fact { - Some("The attempt does not observe, investigate, or communicate the proposed fact; choose no_material_change.") - } else { - None - } - }] - }) - .to_string()); - } - let mut calls = self.resolver_calls.lock().unwrap(); - *calls += 1; - if *calls == 1 { - return Ok(serde_json::json!({ - "outcomes":[{ - "action_digest":self.action_digest, - "band":"mixed", - "effect_kind":"knowledge_learned", - "supporting_state_references":["fact:fact:safe-route"], - "owner_subject_id":"dockers", - "fact_id":"fact:safe-route" - }] - }) - .to_string()); - } - Ok(serde_json::json!({ - "outcomes":[{ - "action_digest":self.action_digest, - "band":"mixed", - "effect_kind":"no_material_change", - "supporting_state_references":[], - "reason":"The coordination attempt does not establish or communicate a durable fact." - }] - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "correcting-knowledge-model" - } - } - - #[async_trait::async_trait] - impl ModelPort for RejectingVerifierModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - assert_eq!(request.stage, "strategic_outcome_verifier"); - Ok(serde_json::json!({ - "verdicts":[{ - "action_digest":self.action_digest, - "result":"mismatch", - "repair_guidance":"The inspection never uses or expends spare rope; choose no_material_change." - }] - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "rejecting-outcome-verifier" - } - } - - #[async_trait::async_trait] - impl ModelPort for OutcomeFixtureModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.requests.lock().unwrap().push(request.clone()); - if request.stage == "strategic_outcome_verifier" { - return Ok(serde_json::json!({ - "verdicts":[{ - "action_digest":self.action_digest, - "result":"match", - "repair_guidance":null - }] - }) - .to_string()); - } - Ok(serde_json::json!({ - "outcomes":[{ - "action_digest":self.action_digest, - "band":"success", - "effect_kind":"knowledge_learned", - "supporting_state_references":["fact:fact:safe-route"], - "owner_subject_id":"dockers", - "fact_id":"fact:safe-route" - }] - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "outcome-fixture" - } - } - - #[test] - fn member_outcome_text_retains_its_field_specific_bound() { - let mut exact = BTreeSet::new(); - validate_member_owner( - "member:mira", - "mira", - &"x".repeat(240), - "memory", - &mut exact, - ) - .unwrap(); - - let mut oversized = BTreeSet::new(); - assert!( - validate_member_owner( - "member:mira", - "mira", - &"x".repeat(241), - "memory", - &mut oversized, - ) - .is_err() - ); - } - - #[test] - fn outcome_verifier_schema_makes_result_guidance_coherence_structural() { - let digest = format!("sha256:{}", "a".repeat(64)); - let mut schema = serde_json::to_value(schema_for!(OutcomeVerifierBundle)).unwrap(); - constrain_verifier_schema(&mut schema, std::slice::from_ref(&digest)).unwrap(); - let validator = jsonschema::validator_for(&schema).unwrap(); - - assert!(validator.is_valid(&serde_json::json!({ - "verdicts":[{ - "action_digest":digest, - "result":"match", - "repair_guidance":null - }] - }))); - assert!(validator.is_valid(&serde_json::json!({ - "verdicts":[{ - "action_digest":digest, - "result":"mismatch", - "repair_guidance":"The proposed transfer is not causally supported by the exact attempt. Preserve the source subject, exact resource custody, and recipient boundary; if no supplied outcome can express the actual result, replace it with no_material_change instead of inventing an exchange or acceptance that never occurred." - }] - }))); - assert!(!validator.is_valid(&serde_json::json!({ - "verdicts":[{ - "action_digest":digest, - "result":"match", - "repair_guidance":"This cannot accompany a match." - }] - }))); - assert!(!validator.is_valid(&serde_json::json!({ - "verdicts":[{ - "action_digest":digest, - "result":"mismatch", - "repair_guidance":null - }] - }))); - } - - fn campaign() -> Campaign { - let mut value = Campaign { - schema: "ghostlight.campaign.v1".into(), - id: Uuid::new_v4(), - name: "outcome-test".into(), - revision: 4, - branch_origin: BranchOrigin { - canon_cutoff: "test".into(), - evidence_receipt_ids: vec![], - }, - world_time: Utc::now(), - tick_hours: 6, - player_actor_id: "player".into(), - locations: BTreeMap::from([( - "dock".into(), - Location { - id: "dock".into(), - name: "Dock".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - )]), - actors: BTreeMap::new(), - institutions: BTreeMap::new(), - clocks: BTreeMap::new(), - facts: BTreeMap::from([( - "fact:safe-route".into(), - WorldFact { - id: "fact:safe-route".into(), - statement: "the western causeway remains open".into(), - scope: crate::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::from(["dock".into()]), - }, - )]), - civic_systems: BTreeMap::new(), - transcript: vec![], - last_player_activity: Utc::now(), - pending_ticks: 0, - away_ticks_processed: 0, - events: vec![], - news: vec![], - canon_candidates: BTreeMap::new(), - gestalts: BTreeMap::from([( - "dockers".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "dockers".into(), - name: "Dockers".into(), - version: 0, - home_location_id: "dock".into(), - shared_capabilities: BTreeSet::from(["repair nets".into()]), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::from(["spare rope".into()]), - goals: vec!["keep the harbor working".into()], - pressures: vec!["storm damage".into()], - }, - )]), - gestalt_members: BTreeMap::new(), - pending_world_proposals: vec![], - agency_profiles: BTreeMap::new(), - agency_relations: BTreeMap::new(), - gestalt_lineages: BTreeMap::new(), - resolution_policy: ResolutionPolicy::default(), - resolution_pins: BTreeMap::new(), - resolution_cover: None, - nemesis_attention_history: Vec::new(), - strategic_tick_count: 0, - }; - value.actors.insert( - "player".into(), - crate::domain::ActorState { - id: "player".into(), - name: "Player".into(), - location_id: "dock".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - ensure_agency_profiles(&mut value); - value.agency_profiles.insert( - "dockers".into(), - AgencyProfile { - schema: "ghostlight.agency_profile.v1".into(), - id: "profile:dockers".into(), - subject_id: "dockers".into(), - subject_kind: AgencySubjectKind::Gestalt, - profile_version: 0, - collective_authority_id: Some("dockers".into()), - parent_subject_id: None, - active_leaf: true, - simulation_eligible: true, - facets: BTreeMap::new(), - location_ids: BTreeSet::from(["dock".into()]), - information_channels: BTreeSet::new(), - detail_debt: 0, - last_detail_tick: 0, - evidence_receipt_ids: vec![], - }, - ); - value - } - - fn proposal() -> CellActionProposal { - CellActionProposal { - subject_id: "dockers".into(), - intent: "inspect the damaged quay".into(), - intended_effect: "learn whether the western route remains usable".into(), - priority: 50, - state_references: vec!["capability:repair nets".into(), "location:dock".into()], - public_channels: vec![], - effects: vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "dockers".into(), - activity: StrategicActivityKind::Investigate, - target_subject_ids: vec![], - location_ids: vec!["dock".into()], - }], - } - } - - #[test] - fn outcome_context_carries_only_the_exact_nemesis_anchor_account() { - let mut value = campaign(); - value.events.push(Event { - id: "old-crisis".into(), - at: value.world_time, - kind: "public_crisis".into(), - summary: "The harbor court publicly voided the dockers' winter charter.".into(), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec!["dockers".into()], - location_ids: vec!["dock".into()], - public_channels: vec!["harbor-notices".into()], - }); - value.events.push(Event { - id: "unrelated".into(), - at: value.world_time, - kind: "public_notice".into(), - summary: "A distant bell was repaired.".into(), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec![], - public_channels: vec!["harbor-notices".into()], - }); - let mut action = proposal(); - action.state_references.push("event:old-crisis".into()); - action.state_references.push("event:unrelated".into()); - let assignments = [CausalFollowThroughAssignment { - anchor_reference: "event:old-crisis".into(), - responder_subject_id: "dockers".into(), - }]; - - let anchors = causal_anchor_contexts(&value, &action, &assignments).unwrap(); - let context = - build_context_with_causal_anchors(&value, std::slice::from_ref(&action), &anchors) - .unwrap(); - let serialized = serde_json::to_string(&context).unwrap(); - assert!(serialized.contains("event:old-crisis")); - assert!(serialized.contains("publicly voided the dockers' winter charter")); - assert!(!serialized.contains("A distant bell was repaired")); - assert!( - context.actions[0] - .allowed_state_references - .iter() - .all(|reference| reference != "event:unrelated") - ); - } - - #[test] - fn compound_strategic_means_share_one_digest_and_union_outcome_authority() { - let value = campaign(); - let mut action = proposal(); - action.effects.push(StrategicCellEffect::GestaltActivity { - gestalt_id: "dockers".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["dock".into()], - }); - - let context = action_context(&value, &action).unwrap(); - assert_eq!( - context.activities, - vec![ - StrategicActivityKind::Investigate, - StrategicActivityKind::Prepare, - ] - ); - assert_eq!(context.location_ids, ["dock"]); - let kinds = admissible_effect_kinds(&value, &action).unwrap(); - assert!(kinds.contains(&OutcomeEffectKind::KnowledgeLearned)); - assert!(kinds.contains(&OutcomeEffectKind::ResourceCreated)); - assert_eq!( - plan_activity_digests( - &crate::resolution::project_selected_actions(&value, vec![action.clone()],) - .unwrap() - ), - vec![cell_action_digest(&action).unwrap()] - ); - } - - #[test] - fn materialized_member_outcome_context_uses_actor_state_and_effects() { - let mut value = campaign(); - value.gestalt_members.insert( - "sable".into(), - crate::domain::GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "sable".into(), - gestalt_id: "dockers".into(), - version: 1, - name: "Sable".into(), - capability_additions: BTreeSet::new(), - capability_removals: BTreeSet::new(), - knowledge_additions: BTreeSet::new(), - knowledge_removals: BTreeSet::new(), - equipment: BTreeSet::from(["folded kit".into()]), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - last_location_id: Some("dock".into()), - materialized_actor_id: Some("member:sable".into()), - last_relevant_revision: 4, - relevance_lease_until_revision: 9, - }, - ); - value.actors.insert( - "member:sable".into(), - crate::domain::ActorState { - id: "member:sable".into(), - name: "Sable".into(), - location_id: "dock".into(), - capabilities: BTreeSet::from(["route scouting".into()]), - knowledge: BTreeSet::from(["the east gate is watched".into()]), - equipment: BTreeSet::from(["materialized kit".into()]), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - ensure_agency_profiles(&mut value); - let action = CellActionProposal { - subject_id: "member:sable".into(), - intent: "inspect the eastern trail".into(), - intended_effect: "identify an immediate route hazard".into(), - priority: 50, - state_references: vec![ - "subject:member:sable".into(), - "location:dock".into(), - "capability:route scouting".into(), - ], - public_channels: vec![], - effects: vec![StrategicCellEffect::ActorActivity { - actor_id: "member:sable".into(), - activity: StrategicActivityKind::Investigate, - target_subject_ids: vec![], - location_ids: vec!["dock".into()], - }], - }; - - let context = build_context(&value, &[action]).unwrap(); - let action = &context.actions[0]; - assert_eq!(action.source_state["kind"], "actor"); - assert_eq!(action.source_state["resources"][0], "materialized kit"); - assert_eq!(action.member_state_owner_id, None); - assert!( - action - .allowed_state_references - .contains(&"subject:member:sable".into()) - ); - assert!( - !action - .admissible_effect_kinds - .contains(&OutcomeEffectKind::MemberMemory) - ); - assert!( - !action - .admissible_effect_kinds - .contains(&OutcomeEffectKind::MemberObligation) - ); - assert!( - !action - .admissible_effect_kinds - .contains(&OutcomeEffectKind::MemberRelationship) - ); - } - - #[test] - fn knowledge_outcome_requires_exact_discoverable_fact() { - let value = campaign(); - let action = proposal(); - let digest = cell_action_digest(&action).unwrap(); - let outcome = StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: digest, - source_subject_id: "dockers".into(), - band: StrategicOutcomeBand::Success, - summary: "The inspection confirms the causeway is open.".into(), - supporting_state_references: vec!["fact:fact:safe-route".into()], - effect: StrategicOutcomeEffect::KnowledgeLearned { - owner_subject_id: "dockers".into(), - fact_id: "fact:safe-route".into(), - }, - }; - validate_activity_outcomes(&value, &[action], &[outcome]).unwrap(); - } - - #[test] - fn communication_projects_and_commits_only_source_known_facts_to_exact_nonhuman_targets() { - let mut value = campaign(); - let statement = value.facts["fact:safe-route"].statement.clone(); - value.facts.insert( - "fact:player-secret".into(), - WorldFact { - id: "fact:player-secret".into(), - statement: "the player alone knows the sealed passphrase".into(), - scope: crate::domain::FactScope::BranchLocal, - evidence_receipt_ids: vec![], - discoverable_at_location_ids: BTreeSet::new(), - }, - ); - value - .actors - .get_mut("player") - .unwrap() - .knowledge - .insert("the player alone knows the sealed passphrase".into()); - value - .gestalts - .get_mut("dockers") - .unwrap() - .shared_knowledge - .insert(statement.clone()); - value.actors.insert( - "reed".into(), - crate::domain::ActorState { - id: "reed".into(), - name: "Reed".into(), - location_id: "dock".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - ensure_agency_profiles(&mut value); - let action = CellActionProposal { - subject_id: "dockers".into(), - intent: "warn Reed that the western causeway remains open".into(), - intended_effect: "tell Reed the exact route fact".into(), - priority: 80, - state_references: vec![format!("knowledge:{statement}"), "location:dock".into()], - public_channels: vec![], - effects: vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "dockers".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["reed".into(), "player".into()], - location_ids: vec!["dock".into()], - }], - }; - let context = action_context(&value, &action).unwrap(); - assert!( - context - .admissible_effect_kinds - .contains(&OutcomeEffectKind::KnowledgeCommunicated) - ); - assert_eq!(context.communicable_facts.len(), 1); - assert!( - context - .discoverable_facts - .iter() - .all(|fact| fact["fact_id"] != "fact:player-secret") - ); - assert_eq!( - context.communicable_facts[0].recipient_subject_ids, - vec!["reed".to_string()] - ); - let mut schema = serde_json::to_value(schema_for!(OutcomeProposalBundle)).unwrap(); - constrain_outcome_schema(&mut schema, std::slice::from_ref(&context)).unwrap(); - let validator = jsonschema::validator_for(&schema).unwrap(); - let proposed = |recipient: &str| { - serde_json::json!({ - "outcomes":[{ - "action_digest":context.action_digest, - "band":"success", - "effect_kind":"knowledge_communicated", - "supporting_state_references":["fact:fact:safe-route"], - "owner_subject_id":"dockers", - "recipient_subject_ids":[recipient], - "fact_id":"fact:safe-route" - }] - }) - }; - assert!(validator.is_valid(&proposed("reed"))); - assert!(!validator.is_valid(&proposed("player"))); - let outcome = StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: cell_action_digest(&action).unwrap(), - source_subject_id: "dockers".into(), - band: StrategicOutcomeBand::Success, - summary: "Dockers shares this with Reed: the western causeway remains open.".into(), - supporting_state_references: vec!["fact:fact:safe-route".into()], - effect: StrategicOutcomeEffect::KnowledgeCommunicated { - from_subject_id: "dockers".into(), - to_subject_ids: vec!["reed".into()], - fact_id: "fact:safe-route".into(), - }, - }; - validate_activity_outcomes( - &value, - std::slice::from_ref(&action), - std::slice::from_ref(&outcome), - ) - .unwrap(); - let mut plan = crate::resolution::project_selected_actions(&value, vec![action]).unwrap(); - plan.activity_outcomes = vec![outcome]; - let lowered = crate::legacy_transition::lower_strategic_wave( - &value, - &plan, - "test:knowledge-communication", - Utc::now() + chrono::Duration::minutes(5), - ) - .unwrap() - .unwrap(); - assert!(lowered.batch.mutations.iter().any(|permitted| { - matches!( - &permitted.mutation, - crate::transition::WorldMutation::ChangeKnowledge { - operation: crate::transition::KnowledgeMutationOperation::Communicate, - .. - } - ) - })); - crate::legacy_transition::apply_lowered_transition(&mut value, &lowered, Utc::now()) - .unwrap(); - assert!(value.actors["reed"].knowledge.contains(&statement)); - assert!(!value.actors["player"].knowledge.contains(&statement)); - } - - #[test] - fn missing_outcome_is_rejected() { - let value = campaign(); - assert!(validate_activity_outcomes(&value, &[proposal()], &[]).is_err()); - } - - #[test] - fn outcome_schema_binds_required_fields_and_exact_action_authority() { - let value = campaign(); - let action = proposal(); - let context = build_context(&value, std::slice::from_ref(&action)).unwrap(); - let digest = context.actions[0].action_digest.clone(); - let mut schema = serde_json::to_value(schema_for!(OutcomeProposalBundle)).unwrap(); - constrain_outcome_schema(&mut schema, &context.actions).unwrap(); - assert!( - schema - .pointer("/properties/outcomes/items/properties") - .is_none(), - "runtime constraints belong to the referenced proposal definition" - ); - assert!( - schema - .pointer("/$defs/OutcomeProposal/properties/band") - .is_some(), - "every required field must remain declared on the constrained definition" - ); - let validator = jsonschema::validator_for(&schema).unwrap(); - let outcome = |owner: Option<&str>, extra: Option<(&str, serde_json::Value)>| { - let mut item = serde_json::json!({ - "action_digest":digest, - "band":"success", - "effect_kind":"knowledge_learned", - "supporting_state_references":["fact:fact:safe-route"], - "fact_id":"fact:safe-route" - }); - if let Some(owner) = owner { - item["owner_subject_id"] = serde_json::json!(owner); - } - if let Some((field, value)) = extra { - item[field] = value; - } - serde_json::json!({"outcomes":[item]}) - }; - - assert!(validator.is_valid(&outcome(Some("dockers"), None))); - assert!(validator.is_valid(&serde_json::json!({ - "outcomes":[{ - "action_digest":digest, - "band":"mixed", - "effect_kind":"no_material_change", - "supporting_state_references":[], - "owner_subject_id":null, - "other_subject_id":null, - "relation_id":null, - "strength_delta":null, - "resource":null, - "pressure_additions":[], - "pressure_resolutions":[], - "member_id":null, - "memory":null, - "obligation":null, - "relationship_description":null, - "fact_id":null, - "reason":"No durable state changes." - }] - }))); - let nullable_inactive_arrays = serde_json::json!({ - "outcomes":[{ - "action_digest":digest, - "band":"mixed", - "effect_kind":"no_material_change", - "supporting_state_references":[], - "pressure_additions":null, - "pressure_resolutions":null, - "recipient_subject_ids":null, - "reason":"No durable state changes." - }] - }); - assert!(validator.is_valid(&nullable_inactive_arrays)); - let normalized: OutcomeProposalBundle = - serde_json::from_value(nullable_inactive_arrays).unwrap(); - assert!(normalized.outcomes[0].pressure_additions.is_empty()); - assert!(normalized.outcomes[0].pressure_resolutions.is_empty()); - assert!(normalized.outcomes[0].recipient_subject_ids.is_empty()); - assert!(!validator.is_valid(&outcome(None, None))); - assert!(!validator.is_valid(&outcome(Some("invented-owner"), None))); - assert!(!validator.is_valid(&outcome( - Some("dockers"), - Some(("resource", serde_json::json!("spare rope"))) - ))); - assert!(!validator.is_valid(&serde_json::json!({ - "outcomes":[{ - "action_digest":format!("sha256:{}", "f".repeat(64)), - "band":"mixed", - "effect_kind":"no_material_change", - "supporting_state_references":[], - "reason":"No durable state changes." - }] - }))); - } - - #[test] - fn outcome_schema_omits_unavailable_empty_effect_lanes() { - let value = campaign(); - let action = proposal(); - let mut contexts = build_context(&value, &[action]).unwrap().actions; - let mut context = contexts.remove(0); - context.source_state["resources"] = serde_json::json!([]); - context.active_relations.clear(); - context.pressure_owners.clear(); - context.resource_recipient_ids.clear(); - context.discoverable_facts.clear(); - context.member_state_owner_id = None; - context.admissible_effect_kinds = vec![OutcomeEffectKind::NoMaterialChange]; - context.allowed_state_references.clear(); - let mut schema = serde_json::to_value(schema_for!(OutcomeProposalBundle)).unwrap(); - constrain_outcome_schema(&mut schema, std::slice::from_ref(&context)).unwrap(); - let validator = jsonschema::validator_for(&schema).unwrap(); - - assert!(validator.is_valid(&serde_json::json!({ - "outcomes":[{ - "action_digest":context.action_digest, - "band":"mixed", - "effect_kind":"no_material_change", - "supporting_state_references":[], - "reason":"The attempt changes no durable state." - }] - }))); - } - - #[test] - fn pressure_context_and_schema_expose_only_real_state_changes() { - let value = campaign(); - let action = proposal(); - let context = action_context(&value, &action).unwrap(); - assert_eq!(context.pressure_owners.len(), 1); - assert_eq!(context.pressure_owners[0].owner_subject_id, "dockers"); - assert_eq!( - context.pressure_owners[0].current_pressures, - vec!["storm damage"] - ); - - let mut schema = serde_json::to_value(schema_for!(OutcomeProposalBundle)).unwrap(); - constrain_outcome_schema(&mut schema, std::slice::from_ref(&context)).unwrap(); - let validator = jsonschema::validator_for(&schema).unwrap(); - let pressure = |additions: Vec<&str>, resolutions: Vec<&str>| { - serde_json::json!({ - "outcomes":[{ - "action_digest":context.action_digest, - "band":"mixed", - "effect_kind":"gestalt_pressure", - "supporting_state_references":["pressure:dockers:storm damage"], - "owner_subject_id":"dockers", - "pressure_additions":additions, - "pressure_resolutions":resolutions - }] - }) - }; - - assert!(validator.is_valid(&pressure(vec!["crew exhaustion"], vec![]))); - assert!(validator.is_valid(&pressure(vec![], vec!["storm damage"]))); - assert!(!validator.is_valid(&pressure(vec![], vec![]))); - assert!(!validator.is_valid(&serde_json::json!({ - "outcomes":[{ - "action_digest":context.action_digest, - "band":"mixed", - "effect_kind":"gestalt_pressure", - "supporting_state_references":["pressure:dockers:storm damage"], - "owner_subject_id":"dockers", - "pressure_additions":null, - "pressure_resolutions":["storm damage"] - }] - }))); - let repeated_pressure = pressure(vec!["storm damage"], vec![]); - assert!(validator.is_valid(&repeated_pressure)); - let repeated_bundle: OutcomeProposalBundle = - serde_json::from_value(repeated_pressure).unwrap(); - let repeated_error = bind_outcomes(&value, &[action], repeated_bundle) - .unwrap_err() - .to_string(); - assert!(repeated_error.contains("gestalt pressure additions already exist: storm damage")); - assert!(!validator.is_valid(&pressure(vec![], vec!["invented resolution"]))); - } - - #[tokio::test] - async fn repeated_current_pressure_uses_the_outcome_semantic_correction_owner() { - let value = campaign(); - let mut action = proposal(); - action.effects = vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "dockers".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["dock".into()], - }]; - let digest = cell_action_digest(&action).unwrap(); - let model = Arc::new(RepeatingPressureModel { - action_digest: digest, - requests: Mutex::new(Vec::new()), - }); - - let (outcomes, stages) = resolve_activity_outcomes(model.clone(), &value, &[action]) - .await - .unwrap(); - - assert_eq!(stages.len(), 2); - assert_eq!(stages[0].receipt.provider_attempts.len(), 1); - assert_eq!(stages[0].receipt.validation_result, "semantic_invalid"); - assert_eq!(stages[1].receipt.provider_attempts.len(), 1); - assert_eq!(stages[0].receipt.stage, "strategic_outcome_resolver"); - assert_eq!(stages[0].receipt.model, MODEL_FAST); - assert_eq!(stages[1].receipt.stage, "strategic_outcome_resolver"); - assert_eq!(stages[1].receipt.model, MODEL_BALANCED); - assert_eq!( - stages[1].receipt.snapshot_binding, - stages[0].receipt.snapshot_binding - ); - assert!( - stages[1] - .receipt - .source_receipt_ids - .contains(&stages[0].receipt.storage_key().to_owned()) - ); - assert!(matches!( - outcomes[0].effect, - StrategicOutcomeEffect::NoMaterialChange { .. } - )); - let requests = model.requests.lock().unwrap(); - assert_eq!(requests.len(), 2); - assert_eq!(requests[0].stage, "strategic_outcome_resolver"); - assert_eq!(requests[0].model, MODEL_FAST); - assert_eq!(requests[1].stage, "strategic_outcome_resolver"); - assert_eq!(requests[1].model, MODEL_BALANCED); - assert_eq!(requests[1].snapshot_binding, requests[0].snapshot_binding); - assert!( - requests[1] - .lived_stream - .contains("gestalt pressure additions already exist: storm damage") - ); - assert!(requests[1].lived_stream.contains("FROZEN REJECTED BUNDLE")); - assert!(requests[1].lived_stream.contains("pressure_additions")); - } - - #[test] - fn reference_rejection_names_the_action_offender_and_allowed_handles() { - let value = campaign(); - let action = proposal(); - let digest = cell_action_digest(&action).unwrap(); - let outcome = StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: digest.clone(), - source_subject_id: "dockers".into(), - band: StrategicOutcomeBand::Success, - summary: "The inspection confirms the causeway is open.".into(), - supporting_state_references: vec!["knowledge:borrowed from another action".into()], - effect: StrategicOutcomeEffect::KnowledgeLearned { - owner_subject_id: "dockers".into(), - fact_id: "fact:safe-route".into(), - }, - }; - - let error = validate_activity_outcomes(&value, &[action], &[outcome]) - .unwrap_err() - .to_string(); - - assert!(error.contains(&digest)); - assert!(error.contains("knowledge:borrowed from another action")); - assert!(error.contains("fact:fact:safe-route")); - assert!(error.contains("exact allowed_state_references")); - } - - #[test] - fn named_actor_possessions_use_the_resource_reference_ontology() { - let mut value = campaign(); - value.actors.insert( - "reed".into(), - crate::domain::ActorState { - id: "reed".into(), - name: "Reed".into(), - location_id: "dock".into(), - capabilities: BTreeSet::from(["field repair".into()]), - knowledge: BTreeSet::new(), - equipment: BTreeSet::from(["medical satchel".into()]), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec!["keep the patients together".into()], - memories: vec![], - }, - ); - ensure_agency_profiles(&mut value); - - let references = allowed_state_references( - &value, - &CellActionProposal { - subject_id: "reed".into(), - intent: "use the satchel to stabilize a patient".into(), - intended_effect: "spend its remaining supplies".into(), - priority: 90, - state_references: vec!["resource:medical satchel".into()], - public_channels: vec![], - effects: vec![StrategicCellEffect::ActorActivity { - actor_id: "reed".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["dock".into()], - }], - }, - ) - .unwrap(); - - assert!(references.contains("resource:medical satchel")); - assert!(!references.contains("equipment:medical satchel")); - } - - #[test] - fn resource_outcome_reports_the_exact_required_owner() { - let value = campaign(); - let mut action = proposal(); - action.effects = vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "dockers".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["dock".into()], - }]; - let outcome = StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: cell_action_digest(&action).unwrap(), - source_subject_id: "dockers".into(), - band: StrategicOutcomeBand::Success, - summary: "The dockers finish a new net.".into(), - supporting_state_references: vec!["capability:repair nets".into()], - effect: StrategicOutcomeEffect::ResourceCreated { - owner_subject_id: "member:dockers".into(), - resource: "finished storm net".into(), - }, - }; - let error = validate_activity_outcomes(&value, &[action], &[outcome]).unwrap_err(); - assert!( - error - .to_string() - .contains("owner_subject_id must be the source or one exact activity location") - ); - assert!(error.to_string().contains("exact admissible_effect_kinds")); - } - - #[test] - fn resource_creation_can_belong_to_the_exact_activity_place() { - let value = campaign(); - let mut action = proposal(); - action.intent = "brace a permanent public warning at the damaged quay".into(); - action.intended_effect = "leave a durable warning where travelers will see it".into(); - action.effects = vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "dockers".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["dock".into()], - }]; - let outcome = StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: cell_action_digest(&action).unwrap(), - source_subject_id: "dockers".into(), - band: StrategicOutcomeBand::Success, - summary: "ignored model summary".into(), - supporting_state_references: vec!["capability:repair nets".into()], - effect: StrategicOutcomeEffect::ResourceCreated { - owner_subject_id: "dock".into(), - resource: "reinforced public hazard marker".into(), - }, - }; - - validate_activity_outcomes( - &value, - std::slice::from_ref(&action), - std::slice::from_ref(&outcome), - ) - .unwrap(); - assert_eq!( - resolved_outcome_summary(&value, &action, &outcome.effect).unwrap(), - "At Dock, Dockers establishes reinforced public hazard marker." - ); - } - - #[test] - fn relation_outcome_summary_names_people_and_consequence_without_state_coordinates() { - let mut value = campaign(); - value.agency_relations.insert( - "dock-command".into(), - AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "dock-command".into(), - from_subject_id: "dockers".into(), - to_subject_id: "player".into(), - kind: AgencyRelationKind::Command, - strength: 50, - active: true, - evidence_receipt_ids: vec![], - }, - ); - - let mut action = proposal(); - action.public_channels = vec!["dock broadsheet".into()]; - action.effects = vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "dockers".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["player".into()], - location_ids: vec!["dock".into()], - }]; - - let summary = resolved_outcome_summary( - &value, - &action, - &StrategicOutcomeEffect::AgencyRelationShift { - relation_id: "dock-command".into(), - strength_delta: -5, - }, - ) - .unwrap(); - - assert_eq!( - summary, - "A public appeal by Dockers weakens the command relationship between Dockers and Player." - ); - assert!(!summary.contains("dock-command")); - assert!(!summary.contains("-5")); - - value.agency_relations.insert( - "dock-rivalry".into(), - AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "dock-rivalry".into(), - from_subject_id: "dockers".into(), - to_subject_id: "player".into(), - kind: AgencyRelationKind::Rivalry, - strength: 50, - active: true, - evidence_receipt_ids: vec![], - }, - ); - assert_eq!( - resolved_outcome_summary( - &value, - &action, - &StrategicOutcomeEffect::AgencyRelationShift { - relation_id: "dock-rivalry".into(), - strength_delta: -5, - }, - ) - .unwrap(), - "A public appeal by Dockers eases the rivalry relationship between Dockers and Player." - ); - } - - #[tokio::test] - async fn resolver_keeps_each_selected_attempt_in_one_digest_bound_stage() { - let value = campaign(); - let action = proposal(); - let digest = cell_action_digest(&action).unwrap(); - let model = Arc::new(OutcomeFixtureModel { - action_digest: digest.clone(), - requests: Mutex::new(Vec::new()), - }); - - let (outcomes, stages) = resolve_activity_outcomes(model.clone(), &value, &[action]) - .await - .unwrap(); - - assert_eq!(outcomes.len(), 1); - assert!(matches!( - outcomes[0].effect, - StrategicOutcomeEffect::KnowledgeLearned { .. } - )); - assert_eq!( - outcomes[0].summary, - "Dockers learns: the western causeway remains open." - ); - assert_eq!(stages.len(), 2); - let requests = model.requests.lock().unwrap(); - assert_eq!(requests.len(), 2); - assert_eq!(requests[0].stage, "strategic_outcome_resolver"); - assert_eq!(requests[1].stage, "strategic_outcome_verifier"); - assert!( - requests[0] - .lived_stream - .contains("exactly one field named outcomes") - ); - assert!( - requests[0] - .lived_stream - .contains("never action_resolutions") - ); - assert!(requests[0].lived_stream.contains("Do not emit summary")); - assert!(requests[0].lived_stream.contains("admissible_effect_kinds")); - assert!(requests[0].lived_stream.contains("knowledge_learned")); - assert!( - requests[0] - .lived_stream - .contains("copied literally and only from that action's allowed_state_references") - ); - assert!( - requests[0] - .lived_stream - .contains("the target field already identifies the target") - ); - assert!( - requests[0] - .lived_stream - .contains("resource_recipient_ids value into the output field other_subject_id") - ); - assert_eq!( - requests[0].snapshot_binding, - activity_outcome_binding( - value.id, - value.revision, - value.resolution_policy.resolution_epoch, - &[digest] - ) - ); - assert!(requests[1].lived_stream.contains( - "Knowledge learned requires an investigation, observation, or communication" - )); - } - - #[tokio::test] - async fn resolver_never_shares_authority_context_between_selected_attempts() { - let value = campaign(); - let first = proposal(); - let mut second = proposal(); - second.intent = "inspect the eastern causeway supports".into(); - second.intended_effect = "establish whether the eastern supports remain sound".into(); - let expected = vec![ - cell_action_digest(&first).unwrap(), - cell_action_digest(&second).unwrap(), - ]; - let model = Arc::new(IsolatingOutcomeModel { - requests: Mutex::new(Vec::new()), - }); - - let (outcomes, stages) = resolve_activity_outcomes(model.clone(), &value, &[first, second]) - .await - .unwrap(); - - assert_eq!( - outcomes - .iter() - .map(|outcome| outcome.action_digest.clone()) - .collect::>(), - expected - ); - assert_eq!(stages.len(), 2); - assert_eq!(model.requests.lock().unwrap().len(), 2); - } - - #[test] - fn prepare_context_projects_only_locally_admissible_durable_handles() { - let value = campaign(); - let mut action = proposal(); - action.effects = vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "dockers".into(), - activity: StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["dock".into()], - }]; - - let context = action_context(&value, &action).unwrap(); - - assert!( - context - .admissible_effect_kinds - .contains(&OutcomeEffectKind::NoMaterialChange) - ); - assert!( - context - .admissible_effect_kinds - .contains(&OutcomeEffectKind::ResourceCreated) - ); - assert!( - context - .admissible_effect_kinds - .contains(&OutcomeEffectKind::ResourceConsumed) - ); - assert!( - context - .admissible_effect_kinds - .contains(&OutcomeEffectKind::GestaltPressure) - ); - assert!( - !context - .admissible_effect_kinds - .contains(&OutcomeEffectKind::KnowledgeLearned) - ); - assert_eq!(context.resource_owner_id, "dockers"); - assert_eq!(context.resource_creation_owner_ids, ["dock", "dockers"]); - - let mut schema = serde_json::to_value(schema_for!(OutcomeProposalBundle)).unwrap(); - constrain_outcome_schema(&mut schema, std::slice::from_ref(&context)).unwrap(); - let validator = jsonschema::validator_for(&schema).unwrap(); - let proposed = |owner: &str| { - serde_json::json!({ - "outcomes":[{ - "action_digest":context.action_digest, - "band":"success", - "effect_kind":"resource_created", - "supporting_state_references":["capability:repair nets"], - "owner_subject_id":owner, - "resource":"reinforced public hazard marker" - }] - }) - }; - assert!(validator.is_valid(&proposed("dock"))); - assert!(validator.is_valid(&proposed("dockers"))); - assert!(!validator.is_valid(&proposed("somewhere-else"))); - } - - #[test] - fn physical_member_activity_cannot_mint_an_unrelated_obligation() { - let mut value = campaign(); - value.gestalt_members.insert( - "mira".into(), - crate::domain::GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "mira".into(), - gestalt_id: "dockers".into(), - version: 0, - name: "Mira".into(), - capability_additions: BTreeSet::from(["pull relays".into()]), - 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!["keep the harbor working".into()], - memories: vec![], - last_location_id: Some("dock".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }, - ); - ensure_agency_profiles(&mut value); - let mut action = CellActionProposal { - subject_id: "member:mira".into(), - intent: "pull the local relay".into(), - intended_effect: "interrupt the local signal".into(), - priority: 70, - state_references: vec!["capability:pull relays".into(), "location:dock".into()], - public_channels: vec![], - effects: vec![StrategicCellEffect::MemberActivity { - member_id: "mira".into(), - activity: StrategicActivityKind::Obstruct, - target_subject_ids: vec![], - location_ids: vec!["dock".into()], - }], - }; - - let physical = action_context(&value, &action).unwrap(); - assert!( - !physical - .admissible_effect_kinds - .contains(&OutcomeEffectKind::MemberObligation) - ); - - if let StrategicCellEffect::MemberActivity { activity, .. } = &mut action.effects[0] { - *activity = StrategicActivityKind::Communicate; - } - let social = action_context(&value, &action).unwrap(); - assert!( - social - .admissible_effect_kinds - .contains(&OutcomeEffectKind::MemberObligation) - ); - } - - #[test] - fn outcome_shape_error_names_the_exact_irrelevant_fields() { - let proposal = OutcomeProposal { - action_digest: "sha256:ignored".into(), - band: StrategicOutcomeBand::Success, - effect_kind: OutcomeEffectKind::AgencyRelationShift, - supporting_state_references: vec![], - owner_subject_id: Some("dockers".into()), - other_subject_id: Some("rivals".into()), - relation_id: Some("dock-rivalry".into()), - strength_delta: Some(-2), - resource: None, - pressure_additions: vec![], - pressure_resolutions: vec![], - member_id: None, - memory: None, - obligation: None, - relationship_description: None, - fact_id: None, - recipient_subject_ids: vec![], - reason: None, - }; - - let error = bind_effect(&proposal).unwrap_err().to_string(); - - assert!(error.contains("other_subject_id, owner_subject_id")); - assert!(error.contains("relation_id, strength_delta")); - } - - #[tokio::test] - async fn independent_verifier_can_reject_a_structurally_legal_unrelated_resource_cost() { - let value = campaign(); - let action = proposal(); - let digest = cell_action_digest(&action).unwrap(); - let outcome = StrategicActivityOutcome { - schema: "ghostlight.strategic_activity_outcome.v1".into(), - action_digest: digest.clone(), - source_subject_id: "dockers".into(), - band: StrategicOutcomeBand::Mixed, - summary: "Dockers expends spare rope.".into(), - supporting_state_references: vec!["resource:spare rope".into()], - effect: StrategicOutcomeEffect::ResourceConsumed { - owner_subject_id: "dockers".into(), - resource: "spare rope".into(), - }, - }; - validate_activity_outcomes( - &value, - std::slice::from_ref(&action), - std::slice::from_ref(&outcome), - ) - .unwrap(); - let context = build_context(&value, std::slice::from_ref(&action)).unwrap(); - - let (_, mismatches) = verify_outcomes( - &RejectingVerifierModel { - action_digest: digest.clone(), - }, - &value, - &context, - &[outcome], - &[digest], - &[], - ) - .await - .unwrap(); - - assert_eq!(mismatches.len(), 1); - assert!(mismatches[0].contains("never uses or expends spare rope")); - } - - #[tokio::test] - async fn verifier_rejection_returns_to_resolver_without_mutating_the_effect() { - let value = campaign(); - let action = proposal(); - let digest = cell_action_digest(&action).unwrap(); - let model = Arc::new(CorrectingOutcomeModel { - action_digest: digest, - resolver_calls: Mutex::new(0), - }); - - let (outcomes, stages) = resolve_activity_outcomes(model.clone(), &value, &[action]) - .await - .unwrap(); - - assert_eq!(stages.len(), 4); - assert!(matches!( - outcomes[0].effect, - StrategicOutcomeEffect::KnowledgeLearned { .. } - )); - assert_eq!(*model.resolver_calls.lock().unwrap(), 2); - assert_eq!(stages[0].receipt.stage, "strategic_outcome_resolver"); - assert_eq!(stages[1].receipt.stage, "strategic_outcome_verifier"); - assert_eq!(stages[2].receipt.stage, "strategic_outcome_resolver"); - assert_eq!(stages[2].receipt.model, MODEL_BALANCED); - assert_eq!( - stages[2].receipt.snapshot_binding, - stages[0].receipt.snapshot_binding - ); - assert_eq!(stages[3].receipt.stage, "strategic_outcome_verifier"); - assert!( - stages[3] - .receipt - .source_receipt_ids - .contains(&stages[2].receipt.storage_key().to_owned()) - ); - } - - #[tokio::test] - async fn verifier_rejects_a_fact_that_the_attempt_did_not_learn_or_communicate() { - let value = campaign(); - let mut action = proposal(); - action.intent = - "ask the dock watch to confirm the next rotation without discussing the western route" - .into(); - action.intended_effect = "receive the watchkeeper's answer about the next rotation".into(); - action.effects = vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "dockers".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec![], - location_ids: vec!["dock".into()], - }]; - let digest = cell_action_digest(&action).unwrap(); - let model = Arc::new(CorrectingKnowledgeModel { - action_digest: digest, - resolver_calls: Mutex::new(0), - requests: Mutex::new(Vec::new()), - }); - - let (outcomes, stages) = resolve_activity_outcomes(model.clone(), &value, &[action]) - .await - .unwrap(); - - assert_eq!(stages.len(), 3); - assert!(matches!( - outcomes[0].effect, - StrategicOutcomeEffect::NoMaterialChange { .. } - )); - assert_eq!(*model.resolver_calls.lock().unwrap(), 2); - let requests = model.requests.lock().unwrap(); - assert_eq!(requests[1].stage, "strategic_outcome_verifier"); - assert_eq!(requests[2].stage, "strategic_outcome_resolver"); - assert_eq!(requests[2].model, MODEL_BALANCED); - assert_eq!(requests[2].snapshot_binding, requests[0].snapshot_binding); - assert!( - requests[2] - .lived_stream - .contains("does not observe, investigate, or communicate the proposed fact") - ); - } - - #[tokio::test] - async fn rejected_reconciliation_preserves_the_complete_outcome_receipt_chain() { - let value = campaign(); - let action = proposal(); - let digest = cell_action_digest(&action).unwrap(); - let model = Arc::new(PersistentlyMismatchedOutcomeModel { - action_digest: digest, - requests: Mutex::new(Vec::new()), - }); - - let error = resolve_activity_outcomes(model.clone(), &value, &[action]) - .await - .expect_err("a rejected reconciled outcome must fail closed"); - let failure = error - .downcast_ref::() - .expect("terminal outcome failures must retain typed evidence"); - - assert_eq!(failure.action_errors.len(), 1); - assert!(failure.action_errors[0].contains("did not survive admission")); - assert_eq!(failure.stage_receipts.len(), 4); - assert_eq!( - failure - .stage_receipts - .iter() - .map(|receipt| receipt.stage.as_str()) - .collect::>(), - vec![ - "strategic_outcome_resolver", - "strategic_outcome_verifier", - "strategic_outcome_resolver", - "strategic_outcome_verifier", - ] - ); - assert_eq!( - failure.stage_receipts[0].validation_result, - "semantic_invalid" - ); - assert_eq!( - failure.stage_receipts[2].validation_result, - "semantic_invalid" - ); - assert_eq!(failure.stage_receipts[2].model, MODEL_BALANCED); - assert!( - failure.stage_receipts[3] - .source_receipt_ids - .contains(&failure.stage_receipts[2].storage_key().to_owned()) - ); - let requests = model.requests.lock().unwrap(); - assert_eq!(requests.len(), 4); - assert_eq!( - requests - .iter() - .filter(|request| request.stage == "strategic_outcome_resolver") - .count(), - 2 - ); - } -} diff --git a/crates/ghostlight-dungeon/src/persistence.rs b/crates/ghostlight-dungeon/src/persistence.rs deleted file mode 100644 index 9d39672..0000000 --- a/crates/ghostlight-dungeon/src/persistence.rs +++ /dev/null @@ -1,1410 +0,0 @@ -use crate::clock::ClockConsequenceBindingReceipt; -use crate::consumer::{ - ExternalProposalReceipt, ExternalSnapshotReceipt, ExternalSubjectAuthority, - ExternalWorldProposal, WorldSeedAdmission, WorldSeedAdmissionReceipt, -}; -use crate::domain::{ - Campaign, CampaignLifecycleReceipt, GestaltMaterializationReceipt, ResolutionControlReceipt, - ResolutionWaveCommit, StrategicTickReceipt, VaultEvidenceReceipt, VaultManifest, - WorldCommitReceipt, -}; -use crate::model::ModelStageReceipt; -use crate::session_zero::{ - CellBudgetProposal, GroupTravelProposal, PublishedSessionZeroSeed, TimeAdvanceProposal, -}; -use crate::transition::{MutationAuthorityEnvelope, WorldMutationBatch, WorldMutationReceipt}; -use anyhow::{Context, Result, anyhow}; -use chrono::Utc; -use cultcache_legacy::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; -use serde::{Serialize, de::DeserializeOwned}; -use std::{ - collections::{BTreeMap, BTreeSet}, - path::Path, -}; - -#[derive(Clone)] -pub struct CampaignStore { - inner: OwnedRedbMessagePackBackingStore, -} - -impl CampaignStore { - pub fn open(path: impl AsRef) -> Result { - Ok(Self { - inner: OwnedRedbMessagePackBackingStore::new(path.as_ref())?, - }) - } - pub fn identity(&self) -> &str { - self.inner.file_identity() - } - - pub fn keys(&self, kind: &str) -> Result> { - Ok(self - .inner - .pull_all()? - .into_iter() - .filter(|r| r.r#type == kind) - .map(|r| r.key) - .collect()) - } - - pub fn load_all(&self, kind: &str) -> Result> { - self.inner - .pull_all()? - .into_iter() - .filter(|row| row.r#type == kind) - .map(|row| rmp_serde::from_slice(&row.payload).context("decode CultCache row")) - .collect() - } - - pub fn load( - &self, - kind: &str, - key: &str, - ) -> Result> { - let row = self.load_envelope(kind, key)?; - row.map(|r| { - let value = rmp_serde::from_slice(&r.payload).context("decode CultCache row")?; - Ok((r, value)) - }) - .transpose() - } - - fn load_envelope(&self, kind: &str, key: &str) -> Result> { - Ok(self - .inner - .pull_all()? - .into_iter() - .find(|row| row.r#type == kind && row.key == key)) - } - - pub fn insert( - &self, - kind: &str, - schema: &str, - key: &str, - value: &T, - ) -> Result { - let row = envelope(kind, schema, key, value)?; - if !self.inner.insert_entry_if_absent(row.clone())? { - return Err(anyhow!("row already exists: {kind}/{key}")); - } - Ok(row) - } - - pub fn persist_model_stage_receipts(&self, receipts: &[ModelStageReceipt]) -> Result<()> { - for receipt in receipts { - if self.matching_model_stage_receipt(receipt)?.is_some() { - continue; - } - let inserted = self.insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - receipt, - ); - if let Err(error) = inserted { - if self.matching_model_stage_receipt(receipt)?.is_none() { - return Err(error); - } - } - } - Ok(()) - } - - fn matching_model_stage_receipt( - &self, - receipt: &ModelStageReceipt, - ) -> Result> { - let Some((row, existing)) = - self.load::("persona_stage_receipt.v1", receipt.storage_key())? - else { - return Ok(None); - }; - if !existing.same_receipted_content(receipt) { - return Err(anyhow!( - "immutable model-stage receipt conflict: {}", - receipt.storage_key() - )); - } - Ok(Some(row)) - } - - #[doc(hidden)] - pub fn create_unadmitted_fixture_campaign( - &self, - campaign: &Campaign, - receipts: &[VaultEvidenceReceipt], - model_receipts: &[crate::model::ModelStageReceipt], - ) -> Result { - self.create_campaign_rows(campaign, receipts, model_receipts, None, None) - } - - pub fn create_admitted_campaign( - &self, - campaign: &Campaign, - receipts: &[VaultEvidenceReceipt], - model_receipts: &[crate::model::ModelStageReceipt], - admission: &WorldSeedAdmission, - admission_receipt: &WorldSeedAdmissionReceipt, - session_zero_publication: Option<&PublishedSessionZeroSeed>, - ) -> Result { - if admission.campaign_id != campaign.id - || admission_receipt.campaign_id != campaign.id - || admission.seed_digest != admission_receipt.seed_digest - || admission.producer_id != admission_receipt.producer_id - || admission.idempotency_key != admission_receipt.idempotency_key - { - return Err(anyhow!( - "world seed admission persistence bundle is inconsistent" - )); - } - self.create_campaign_rows( - campaign, - receipts, - model_receipts, - Some((admission, admission_receipt)), - session_zero_publication, - ) - } - - #[cfg(test)] - pub(crate) fn create_session_zero_campaign( - &self, - campaign: &Campaign, - receipts: &[VaultEvidenceReceipt], - model_receipts: &[crate::model::ModelStageReceipt], - publication: &PublishedSessionZeroSeed, - ) -> Result { - if publication.membership.campaign_id != campaign.id - || publication.governance.campaign_id != campaign.id - { - return Err(anyhow!("Session Zero publication targets another campaign")); - } - self.create_campaign_rows(campaign, receipts, model_receipts, None, Some(publication)) - } - - fn create_campaign_rows( - &self, - campaign: &Campaign, - receipts: &[VaultEvidenceReceipt], - model_receipts: &[crate::model::ModelStageReceipt], - admission: Option<(&WorldSeedAdmission, &WorldSeedAdmissionReceipt)>, - publication: Option<&PublishedSessionZeroSeed>, - ) -> Result { - let campaign_row = envelope( - "campaign.v1", - "ghostlight.campaign.v1", - &campaign.id.to_string(), - campaign, - )?; - let mut rows = vec![campaign_row.clone()]; - rows.push(envelope( - "campaign_seed.v1", - "ghostlight.campaign.v1", - &campaign.id.to_string(), - campaign, - )?); - if let Some((admission, receipt)) = admission { - rows.push(envelope( - "world_seed_admission.v1", - "ghostlight.world_seed_admission.v1", - &campaign.id.to_string(), - admission, - )?); - rows.push(envelope( - "world_seed_admission_receipt.v1", - "ghostlight.world_seed_admission_receipt.v1", - &campaign.id.to_string(), - receipt, - )?); - for authority in &admission.external_subjects { - rows.push(envelope( - "external_subject_authority.v1", - "ghostlight.external_subject_authority.v1", - &authority.id, - authority, - )?); - } - } - let manifest = merge_vault_manifest(None, receipts); - rows.push(envelope( - "vault_manifest.v1", - "ghostlight.vault_manifest.v1", - &campaign.id.to_string(), - &manifest, - )?); - for receipt in receipts { - rows.push(envelope( - "vault_evidence_receipt.v1", - "ghostlight.vault_evidence_receipt.v1", - &receipt.id, - receipt, - )?); - } - for receipt in model_receipts { - rows.push(envelope( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - receipt.storage_key(), - receipt, - )?); - } - for candidate in campaign.canon_candidates.values() { - rows.push(envelope( - "canon_candidate.v1", - "ghostlight.canon_candidate.v1", - &candidate.id, - candidate, - )?); - } - rows.push(envelope( - "campaign_lifecycle_receipt.v1", - "ghostlight.campaign_lifecycle_receipt.v1", - &format!("{}:create", campaign.id), - &CampaignLifecycleReceipt { - schema: "ghostlight.campaign_lifecycle_receipt.v1".into(), - campaign_id: campaign.id, - operation: "create".into(), - parent_campaign_id: None, - parent_revision: None, - created_at: Utc::now(), - }, - )?); - if let Some(publication) = publication { - rows.push(envelope( - "session_zero_publication.v1", - "ghostlight.published_session_zero_seed.v1", - &campaign.id.to_string(), - publication, - )?); - rows.push(envelope( - "campaign_membership.v1", - "ghostlight.campaign_membership.v1", - &campaign.id.to_string(), - &publication.membership, - )?); - rows.push(envelope( - "campaign_contract.v1", - "ghostlight.campaign_contract.v1", - &campaign.id.to_string(), - &publication.contract, - )?); - rows.push(envelope( - "campaign_governance.v1", - "ghostlight.campaign_governance.v1", - &campaign.id.to_string(), - &publication.governance, - )?); - rows.push(envelope( - "campaign_dm_persona.v1", - "ghostlight.campaign_dm_persona.v1", - &publication.dm_persona.id, - &publication.dm_persona, - )?); - rows.push(envelope( - "approved_campaign_brief.v1", - "ghostlight.approved_campaign_brief.v1", - &campaign.id.to_string(), - &publication.approved_brief, - )?); - for approval in &publication.approvals { - rows.push(envelope( - "session_zero_approval.v1", - "ghostlight.session_zero_approval.v1", - &approval.member_id, - approval, - )?); - } - for boundary in &publication.boundaries { - rows.push(envelope( - "content_boundary.v1", - "ghostlight.content_boundary.v1", - &boundary.id, - boundary, - )?); - } - } - if !self.inner.compare_and_swap_batch(&[], rows)? { - return Err(anyhow!("campaign store is not empty")); - } - Ok(campaign_row) - } - - pub fn append_external_snapshot( - &self, - expected_campaign: &CultCacheEnvelope, - expected_authority: &CultCacheEnvelope, - next_campaign: &Campaign, - next_authority: &ExternalSubjectAuthority, - receipt: &ExternalSnapshotReceipt, - ) -> Result { - if expected_campaign.key != next_campaign.id.to_string() - || expected_authority.key != next_authority.id - || receipt.campaign_id != next_campaign.id - || receipt.authority_id != next_authority.id - || receipt.subject_id != next_authority.subject_id - || receipt.world_revision != next_campaign.revision - || receipt.previous_world_revision.saturating_add(1) != next_campaign.revision - { - return Err(anyhow!( - "external snapshot persistence bundle is inconsistent" - )); - } - let next_campaign_row = envelope( - "campaign.v1", - "ghostlight.campaign.v1", - &next_campaign.id.to_string(), - next_campaign, - )?; - let rows = vec![ - next_campaign_row.clone(), - envelope( - "external_subject_authority.v1", - "ghostlight.external_subject_authority.v1", - &next_authority.id, - next_authority, - )?, - envelope( - "external_snapshot_receipt.v1", - "ghostlight.external_snapshot_receipt.v1", - &format!("{}:{}", receipt.authority_id, receipt.source_revision), - receipt, - )?, - ]; - if !self.inner.compare_and_swap_batch( - &[expected_campaign.clone(), expected_authority.clone()], - rows, - )? { - return Err(anyhow!("stale external snapshot or authority watermark")); - } - Ok(next_campaign_row) - } - - pub fn append_external_proposals( - &self, - rows: &mut Vec, - proposals: &[ExternalWorldProposal], - ) -> Result<()> { - for proposal in proposals { - rows.push(envelope( - "external_world_proposal.v1", - "ghostlight.external_world_proposal.v1", - &proposal.id, - proposal, - )?); - } - Ok(()) - } - - pub fn record_external_proposal_receipt( - &self, - receipt: &ExternalProposalReceipt, - ) -> Result { - let key = receipt.proposal_id.clone(); - if let Some((_, existing)) = - self.load::("external_proposal_receipt.v1", &key)? - { - return if existing == *receipt { - Ok(existing) - } else { - Err(anyhow!("external proposal receipt idempotency conflict")) - }; - } - self.insert( - "external_proposal_receipt.v1", - "ghostlight.external_proposal_receipt.v1", - &key, - receipt, - )?; - Ok(receipt.clone()) - } - - pub fn snapshot_to(&self, path: impl AsRef) -> Result<()> { - let rows = self.inner.pull_all()?; - let target = OwnedRedbMessagePackBackingStore::new(path.as_ref())?; - if !target.compare_and_swap_batch(&[], rows)? { - return Err(anyhow!("export target is not empty")); - } - Ok(()) - } - - pub fn replace( - &self, - expected: &CultCacheEnvelope, - schema: &str, - value: &T, - ) -> Result { - let next = envelope(&expected.r#type, schema, &expected.key, value)?; - if !self.inner.compare_and_swap_entry(expected, next.clone())? { - return Err(anyhow!("stale CultCache snapshot")); - } - Ok(next) - } - - pub fn append_world_transition( - &self, - expected: &CultCacheEnvelope, - next_schema: &str, - next: &T, - receipt_key: &str, - receipt: &WorldCommitReceipt, - ) -> Result { - let next_row = envelope(&expected.r#type, next_schema, &expected.key, next)?; - let mut rows = vec![ - next_row.clone(), - envelope( - "world_commit_receipt.v1", - "ghostlight.world_commit_receipt.v1", - receipt_key, - receipt, - )?, - ]; - if let Some(roll) = &receipt.roll { - rows.push(envelope( - "roll_receipt.v1", - "ghostlight.roll_receipt.v1", - &roll.assessment_digest, - roll, - )?); - } - if !self - .inner - .compare_and_swap_batch(std::slice::from_ref(expected), rows)? - { - return Err(anyhow!("stale CultCache snapshot")); - } - Ok(next_row) - } - - pub fn append_world_transition_with_mutation( - &self, - expected: &CultCacheEnvelope, - next_schema: &str, - next: &T, - receipt_key: &str, - receipt: &WorldCommitReceipt, - authority: &MutationAuthorityEnvelope, - batch: &WorldMutationBatch, - mutation_receipt: &WorldMutationReceipt, - ) -> Result { - if mutation_receipt.previous_world_revision != receipt.previous_revision - || mutation_receipt.world_revision != receipt.revision - || mutation_receipt.campaign_id != receipt.campaign_id - || mutation_receipt.batch_digest != batch.digest - || mutation_receipt.authority_envelope_digest != authority.digest - { - return Err(anyhow!( - "world and mutation receipts do not describe one transition" - )); - } - let next_row = envelope(&expected.r#type, next_schema, &expected.key, next)?; - let mut rows = vec![ - next_row.clone(), - envelope( - "world_commit_receipt.v1", - "ghostlight.world_commit_receipt.v1", - receipt_key, - receipt, - )?, - envelope( - "mutation_authority_envelope.v1", - "ghostlight.mutation_authority_envelope.v1", - &authority.id, - authority, - )?, - envelope( - "world_mutation_batch.v1", - "ghostlight.world_mutation_batch.v1", - &batch.id, - batch, - )?, - envelope( - "world_mutation_receipt.v1", - "ghostlight.world_mutation_receipt.v1", - &mutation_receipt.id, - mutation_receipt, - )?, - ]; - if let Some(roll) = &receipt.roll { - rows.push(envelope( - "roll_receipt.v1", - "ghostlight.roll_receipt.v1", - &roll.assessment_digest, - roll, - )?); - } - if !self - .inner - .compare_and_swap_batch(std::slice::from_ref(expected), rows)? - { - return Err(anyhow!("stale CultCache snapshot")); - } - Ok(next_row) - } - - pub fn commit_time_advance( - &self, - expected_campaign: &CultCacheEnvelope, - next_campaign: &Campaign, - expected_proposal: &CultCacheEnvelope, - next_proposal: &TimeAdvanceProposal, - receipt: &WorldCommitReceipt, - mutation: ( - &MutationAuthorityEnvelope, - &WorldMutationBatch, - &WorldMutationReceipt, - ), - ) -> Result { - let next_campaign_row = envelope( - &expected_campaign.r#type, - "ghostlight.campaign.v1", - &expected_campaign.key, - next_campaign, - )?; - let next_proposal_row = envelope( - &expected_proposal.r#type, - "ghostlight.time_advance_proposal.v1", - &expected_proposal.key, - next_proposal, - )?; - let mut rows = vec![ - next_campaign_row.clone(), - next_proposal_row, - envelope( - "world_commit_receipt.v1", - "ghostlight.world_commit_receipt.v1", - &format!("{}-{}", next_campaign.id, next_campaign.revision), - receipt, - )?, - ]; - append_mutation_proof(&mut rows, receipt, mutation)?; - if !self.inner.compare_and_swap_batch( - &[expected_campaign.clone(), expected_proposal.clone()], - rows, - )? { - return Err(anyhow!("stale campaign or time-advance proposal")); - } - Ok(next_campaign_row) - } - - pub fn commit_group_travel( - &self, - expected_campaign: &CultCacheEnvelope, - next_campaign: &Campaign, - expected_proposal: &CultCacheEnvelope, - next_proposal: &GroupTravelProposal, - receipt: &WorldCommitReceipt, - mutation: ( - &MutationAuthorityEnvelope, - &WorldMutationBatch, - &WorldMutationReceipt, - ), - ) -> Result { - let next_campaign_row = envelope( - &expected_campaign.r#type, - "ghostlight.campaign.v1", - &expected_campaign.key, - next_campaign, - )?; - let next_proposal_row = envelope( - &expected_proposal.r#type, - "ghostlight.group_travel_proposal.v1", - &expected_proposal.key, - next_proposal, - )?; - let mut rows = vec![ - next_campaign_row.clone(), - next_proposal_row, - envelope( - "world_commit_receipt.v1", - "ghostlight.world_commit_receipt.v1", - &format!("{}-{}", next_campaign.id, next_campaign.revision), - receipt, - )?, - ]; - append_mutation_proof(&mut rows, receipt, mutation)?; - if !self.inner.compare_and_swap_batch( - &[expected_campaign.clone(), expected_proposal.clone()], - rows, - )? { - return Err(anyhow!("stale campaign or group-travel proposal")); - } - Ok(next_campaign_row) - } - - pub fn commit_cell_budget( - &self, - expected_campaign: &CultCacheEnvelope, - next_campaign: &Campaign, - expected_proposal: &CultCacheEnvelope, - next_proposal: &CellBudgetProposal, - receipt: &ResolutionControlReceipt, - ) -> Result { - let next_campaign_row = envelope( - &expected_campaign.r#type, - "ghostlight.campaign.v1", - &expected_campaign.key, - next_campaign, - )?; - let rows = vec![ - next_campaign_row.clone(), - envelope( - &expected_proposal.r#type, - "ghostlight.cell_budget_proposal.v1", - &expected_proposal.key, - next_proposal, - )?, - envelope( - "resolution_control_receipt.v1", - "ghostlight.resolution_control_receipt.v1", - &format!( - "{}:{}:{}", - receipt.campaign_id, receipt.operation, receipt.resolution_epoch - ), - receipt, - )?, - ]; - if !self.inner.compare_and_swap_batch( - &[expected_campaign.clone(), expected_proposal.clone()], - rows, - )? { - return Err(anyhow!("stale campaign or cell-budget proposal")); - } - Ok(next_campaign_row) - } - - pub fn commit_contract_review( - &self, - expected_campaign: &CultCacheEnvelope, - next_campaign: &Campaign, - publication: &PublishedSessionZeroSeed, - receipt: &WorldCommitReceipt, - ) -> Result { - let campaign_key = next_campaign.id.to_string(); - let required = [ - "session_zero_publication.v1", - "campaign_contract.v1", - "campaign_membership.v1", - "campaign_governance.v1", - "approved_campaign_brief.v1", - ]; - let mut expected_rows = vec![expected_campaign.clone()]; - for kind in required { - let row = self - .load_envelope(kind, &campaign_key)? - .ok_or_else(|| anyhow!("contract review requires {kind}"))?; - expected_rows.push(row); - } - let dm_row = self - .load_envelope("campaign_dm_persona.v1", &publication.dm_persona.id)? - .ok_or_else(|| anyhow!("contract review requires campaign DM state"))?; - expected_rows.push(dm_row); - - let next_campaign_row = envelope( - &expected_campaign.r#type, - "ghostlight.campaign.v1", - &expected_campaign.key, - next_campaign, - )?; - let mut rows = vec![ - next_campaign_row.clone(), - envelope( - "session_zero_publication.v1", - "ghostlight.published_session_zero_seed.v1", - &campaign_key, - publication, - )?, - envelope( - "campaign_contract.v1", - "ghostlight.campaign_contract.v1", - &campaign_key, - &publication.contract, - )?, - envelope( - "campaign_membership.v1", - "ghostlight.campaign_membership.v1", - &campaign_key, - &publication.membership, - )?, - envelope( - "campaign_governance.v1", - "ghostlight.campaign_governance.v1", - &campaign_key, - &publication.governance, - )?, - envelope( - "campaign_dm_persona.v1", - "ghostlight.campaign_dm_persona.v1", - &publication.dm_persona.id, - &publication.dm_persona, - )?, - envelope( - "approved_campaign_brief.v1", - "ghostlight.approved_campaign_brief.v1", - &campaign_key, - &publication.approved_brief, - )?, - envelope( - "world_commit_receipt.v1", - "ghostlight.world_commit_receipt.v1", - &format!("{}-{}", next_campaign.id, next_campaign.revision), - receipt, - )?, - ]; - for approval in &publication.approvals { - rows.push(envelope( - "session_zero_approval.v1", - "ghostlight.session_zero_approval.v1", - &format!("{}:{}", publication.session_zero_id, approval.member_id), - approval, - )?); - } - if !self.inner.compare_and_swap_batch(&expected_rows, rows)? { - return Err(anyhow!("stale campaign contract review")); - } - Ok(next_campaign_row) - } - - pub fn append_world_commit( - &self, - expected: &CultCacheEnvelope, - next: &T, - receipt_key: &str, - receipt: &WorldCommitReceipt, - evidence: &[VaultEvidenceReceipt], - candidates: &[crate::domain::CanonCandidate], - model_receipts: &[crate::model::ModelStageReceipt], - clock_binding_receipt: Option<&ClockConsequenceBindingReceipt>, - mutation: Option<( - &MutationAuthorityEnvelope, - &WorldMutationBatch, - &WorldMutationReceipt, - )>, - ) -> Result { - let next_row = envelope( - &expected.r#type, - "ghostlight.campaign.v1", - &expected.key, - next, - )?; - let mut rows = vec![ - next_row.clone(), - envelope( - "world_commit_receipt.v1", - "ghostlight.world_commit_receipt.v1", - receipt_key, - receipt, - )?, - ]; - let existing_manifest = self.load::("vault_manifest.v1", &expected.key)?; - let manifest = - merge_vault_manifest(existing_manifest.as_ref().map(|(_, value)| value), evidence); - rows.push(envelope( - "vault_manifest.v1", - "ghostlight.vault_manifest.v1", - &expected.key, - &manifest, - )?); - let mut expected_rows = vec![expected.clone()]; - if let Some((row, _)) = existing_manifest { - expected_rows.push(row); - } - for item in evidence { - self.append_idempotent_companion( - &mut expected_rows, - &mut rows, - envelope( - "vault_evidence_receipt.v1", - "ghostlight.vault_evidence_receipt.v1", - &item.id, - item, - )?, - )?; - } - for item in candidates { - self.append_idempotent_companion( - &mut expected_rows, - &mut rows, - envelope( - "canon_candidate.v1", - "ghostlight.canon_candidate.v1", - &item.id, - item, - )?, - )?; - } - let mut unique_model_receipts = BTreeMap::::new(); - for item in model_receipts { - if let Some(existing) = unique_model_receipts.get(item.storage_key()) { - if !existing.same_receipted_content(item) { - return Err(anyhow!( - "immutable model-stage receipt conflict: {}", - item.storage_key() - )); - } - continue; - } - unique_model_receipts.insert(item.storage_key().to_owned(), item); - } - for item in unique_model_receipts.into_values() { - if let Some(existing) = self.matching_model_stage_receipt(item)? { - expected_rows.push(existing.clone()); - rows.push(existing); - } else { - rows.push(envelope( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - item.storage_key(), - item, - )?); - } - } - if let Some(binding) = clock_binding_receipt { - let supplied_model_receipt_ids = model_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - if receipt.command_kind != "bind_clock_consequences" - || binding.campaign_id != receipt.campaign_id - || binding.previous_revision != receipt.previous_revision - || binding.revision != receipt.revision - || binding.committed_at != receipt.committed_at - || !supplied_model_receipt_ids.contains(&binding.accepted_model_receipt_id) - || binding.model_receipt_ids.len() != supplied_model_receipt_ids.len() - || binding - .model_receipt_ids - .iter() - .cloned() - .collect::>() - != supplied_model_receipt_ids - { - return Err(anyhow!( - "clock consequence binding receipt contradicts its world commit bundle" - )); - } - self.append_idempotent_companion( - &mut expected_rows, - &mut rows, - envelope( - "clock_consequence_binding_receipt.v1", - "ghostlight.clock_consequence_binding_receipt.v1", - &format!("{}-{}", binding.campaign_id, binding.revision), - binding, - )?, - )?; - } - if let Some(mutation) = mutation { - append_mutation_proof(&mut rows, receipt, mutation)?; - } - if !self.inner.compare_and_swap_batch(&expected_rows, rows)? { - return Err(anyhow!("stale CultCache snapshot")); - } - Ok(next_row) - } - - fn append_idempotent_companion( - &self, - expected: &mut Vec, - replacements: &mut Vec, - row: CultCacheEnvelope, - ) -> Result<()> { - if let Some(pending) = replacements - .iter() - .find(|pending| pending.r#type == row.r#type && pending.key == row.key) - { - if !same_immutable_envelope_content(pending, &row) { - return Err(anyhow!( - "immutable world-commit companion conflict: {}/{}", - row.r#type, - row.key - )); - } - return Ok(()); - } - if let Some(existing) = self.load_envelope(&row.r#type, &row.key)? { - if !same_immutable_envelope_content(&existing, &row) { - return Err(anyhow!( - "immutable world-commit companion conflict: {}/{}", - row.r#type, - row.key - )); - } - expected.push(existing.clone()); - replacements.push(existing); - } else { - replacements.push(row); - } - Ok(()) - } - - pub fn append_strategic_tick( - &self, - expected: &CultCacheEnvelope, - next: &Campaign, - receipt_key: &str, - world_receipt: &WorldCommitReceipt, - strategic_receipt: &StrategicTickReceipt, - resolution_wave: Option<&ResolutionWaveCommit>, - external_proposals: &[ExternalWorldProposal], - mutation: Option<( - &MutationAuthorityEnvelope, - &WorldMutationBatch, - &WorldMutationReceipt, - )>, - ) -> Result { - let next_row = envelope( - &expected.r#type, - "ghostlight.campaign.v1", - &expected.key, - next, - )?; - let mut rows = vec![ - next_row.clone(), - envelope( - "world_commit_receipt.v1", - "ghostlight.world_commit_receipt.v1", - receipt_key, - world_receipt, - )?, - envelope( - "strategic_tick.v1", - "ghostlight.strategic_tick.v1", - receipt_key, - strategic_receipt, - )?, - ]; - if let Some(wave) = resolution_wave { - let key = format!( - "{}:{}:{}", - next.id, wave.world_revision, wave.resolution_epoch - ); - rows.push(envelope( - "resolution_cover.v1", - "ghostlight.resolution_cover.v1", - &key, - &wave.cover, - )?); - rows.push(envelope( - "resolution_plan_receipt.v1", - "ghostlight.resolution_plan_receipt.v1", - &key, - &wave.plan_receipt, - )?); - for appraisal in &wave.appraisals { - rows.push(envelope( - "cell_appraisal.v1", - "ghostlight.cell_appraisal.v1", - &format!( - "{}:{}:{}", - next.revision, wave.resolution_epoch, appraisal.cell_id - ), - appraisal, - )?); - } - for outcome in &wave.activity_outcomes { - rows.push(envelope( - "strategic_activity_outcome.v1", - "ghostlight.strategic_activity_outcome.v1", - &format!( - "{}:{}:{}", - next.revision, wave.resolution_epoch, outcome.action_digest - ), - outcome, - )?); - } - for individuation in &wave.strategic_individuations { - rows.push(envelope( - "strategic_gestalt_individuation.v1", - "ghostlight.strategic_gestalt_individuation.v1", - &format!( - "{}:{}:{}", - next.revision, - wave.resolution_epoch, - crate::domain::canonical_gestalt_member_local_id( - &individuation.individuation.member.id, - ) - ), - individuation, - )?); - } - } - self.append_external_proposals(&mut rows, external_proposals)?; - if let Some((authority, batch, mutation_receipt)) = mutation { - if mutation_receipt.previous_world_revision != world_receipt.previous_revision - || mutation_receipt.world_revision != world_receipt.revision - || mutation_receipt.batch_digest != batch.digest - || mutation_receipt.authority_envelope_digest != authority.digest - { - return Err(anyhow!( - "strategic and mutation receipts do not describe one transition" - )); - } - rows.push(envelope( - "mutation_authority_envelope.v1", - "ghostlight.mutation_authority_envelope.v1", - &authority.id, - authority, - )?); - rows.push(envelope( - "world_mutation_batch.v1", - "ghostlight.world_mutation_batch.v1", - &batch.id, - batch, - )?); - rows.push(envelope( - "world_mutation_receipt.v1", - "ghostlight.world_mutation_receipt.v1", - &mutation_receipt.id, - mutation_receipt, - )?); - } - if !self - .inner - .compare_and_swap_batch(std::slice::from_ref(expected), rows)? - { - return Err(anyhow!("stale CultCache snapshot")); - } - Ok(next_row) - } - - pub fn append_resolution_control( - &self, - expected: &CultCacheEnvelope, - next: &Campaign, - receipt: &ResolutionControlReceipt, - ) -> Result { - let next_row = envelope( - &expected.r#type, - "ghostlight.campaign.v1", - &expected.key, - next, - )?; - let rows = vec![ - next_row.clone(), - envelope( - "resolution_control_receipt.v1", - "ghostlight.resolution_control_receipt.v1", - &format!("{}:{}", next.id, receipt.resolution_epoch), - receipt, - )?, - ]; - if !self - .inner - .compare_and_swap_batch(std::slice::from_ref(expected), rows)? - { - return Err(anyhow!("stale CultCache snapshot")); - } - Ok(next_row) - } - - pub fn append_gestalt_presence( - &self, - expected: &CultCacheEnvelope, - next: &Campaign, - receipt_key: &str, - world_receipt: &WorldCommitReceipt, - gestalt_receipt: &GestaltMaterializationReceipt, - model_receipts: &[crate::model::ModelStageReceipt], - ) -> Result { - let next_row = envelope( - &expected.r#type, - "ghostlight.campaign.v1", - &expected.key, - next, - )?; - let mut rows = vec![ - next_row.clone(), - envelope( - "world_commit_receipt.v1", - "ghostlight.world_commit_receipt.v1", - receipt_key, - world_receipt, - )?, - envelope( - "gestalt_materialization_receipt.v1", - "ghostlight.gestalt_materialization_receipt.v1", - receipt_key, - gestalt_receipt, - )?, - ]; - let mut expected_rows = vec![expected.clone()]; - let mut unique_model_receipts = BTreeMap::::new(); - for item in model_receipts { - if let Some(existing) = unique_model_receipts.get(item.storage_key()) { - if !existing.same_receipted_content(item) { - return Err(anyhow!( - "immutable model-stage receipt conflict: {}", - item.storage_key() - )); - } - continue; - } - unique_model_receipts.insert(item.storage_key().to_owned(), item); - } - for item in unique_model_receipts.into_values() { - if let Some(existing) = self.matching_model_stage_receipt(item)? { - expected_rows.push(existing.clone()); - rows.push(existing); - } else { - rows.push(envelope( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - item.storage_key(), - item, - )?); - } - } - if !self.inner.compare_and_swap_batch(&expected_rows, rows)? { - return Err(anyhow!("stale CultCache snapshot")); - } - Ok(next_row) - } -} - -fn same_immutable_envelope_content(left: &CultCacheEnvelope, right: &CultCacheEnvelope) -> bool { - left.key == right.key - && left.r#type == right.r#type - && left.payload == right.payload - && left.schema_id == right.schema_id -} - -fn append_mutation_proof( - rows: &mut Vec, - world_receipt: &WorldCommitReceipt, - (authority, batch, mutation_receipt): ( - &MutationAuthorityEnvelope, - &WorldMutationBatch, - &WorldMutationReceipt, - ), -) -> Result<()> { - if mutation_receipt.previous_world_revision != world_receipt.previous_revision - || mutation_receipt.world_revision != world_receipt.revision - || mutation_receipt.campaign_id != world_receipt.campaign_id - || mutation_receipt.batch_digest != batch.digest - || mutation_receipt.authority_envelope_digest != authority.digest - { - return Err(anyhow!( - "world and mutation receipts do not describe one transition" - )); - } - rows.push(envelope( - "mutation_authority_envelope.v1", - "ghostlight.mutation_authority_envelope.v1", - &authority.id, - authority, - )?); - rows.push(envelope( - "world_mutation_batch.v1", - "ghostlight.world_mutation_batch.v1", - &batch.id, - batch, - )?); - rows.push(envelope( - "world_mutation_receipt.v1", - "ghostlight.world_mutation_receipt.v1", - &mutation_receipt.id, - mutation_receipt, - )?); - Ok(()) -} - -fn merge_vault_manifest( - existing: Option<&VaultManifest>, - receipts: &[VaultEvidenceReceipt], -) -> VaultManifest { - let mut providers = existing - .map(|manifest| BTreeSet::from([manifest.provider.clone()])) - .unwrap_or_default(); - let mut source_ids = existing - .map(|manifest| manifest.source_ids.clone()) - .unwrap_or_default(); - let mut authority_lanes = existing - .map(|manifest| manifest.authority_lanes.clone()) - .unwrap_or_default(); - let mut temporal_scopes = existing - .map(|manifest| manifest.temporal_scopes.clone()) - .unwrap_or_default(); - for receipt in receipts { - providers.insert(receipt.provider.clone()); - for witness in &receipt.witnesses { - source_ids.insert(witness.source_id.clone()); - authority_lanes.insert(witness.authority_lane.clone()); - temporal_scopes.insert(witness.temporal_scope.clone()); - } - } - VaultManifest { - schema: "ghostlight.vault_manifest.v1".into(), - provider: if providers.is_empty() { - "none".into() - } else { - providers.into_iter().collect::>().join("+") - }, - source_ids, - authority_lanes, - temporal_scopes, - } -} - -fn envelope( - kind: &str, - schema: &str, - key: &str, - value: &T, -) -> Result { - Ok(CultCacheEnvelope { - key: key.into(), - r#type: kind.into(), - payload: rmp_serde::to_vec_named(value)?, - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(schema.into()), - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn model_receipt() -> ModelStageReceipt { - ModelStageReceipt { - schema: "ghostlight.persona_stage_receipt.v1".into(), - receipt_hash: "sha256:persistence-receipt".into(), - provider: "fixture".into(), - model: "fixture-model".into(), - stage: "fixture-stage".into(), - snapshot_binding: "campaign:test:revision:0".into(), - request_hash: "sha256:request".into(), - output_hash: "sha256:output".into(), - source_receipt_ids: vec!["sha256:source".into()], - latency_ms: 17, - validation_result: "valid".into(), - local_validation_error: None, - input_chars: 120, - output_chars: 42, - provider_attempts: vec![], - } - } - - #[test] - fn world_commit_reuses_pre_persisted_semantically_identical_model_receipt() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let campaign = crate::kernel::tests::campaign(); - let campaign_row = store - .create_unadmitted_fixture_campaign(&campaign, &[], &[]) - .unwrap(); - let stored_receipt = model_receipt(); - store - .persist_model_stage_receipts(std::slice::from_ref(&stored_receipt)) - .unwrap(); - let (stored_envelope, _) = store - .load::("persona_stage_receipt.v1", stored_receipt.storage_key()) - .unwrap() - .unwrap(); - - let mut repeated_receipt = stored_receipt.clone(); - repeated_receipt.latency_ms = 91; - repeated_receipt.provider_attempts = vec![crate::model::ModelProviderAttemptReceipt { - provider_request_id: Some("repeated-provider-request".into()), - latency_ms: 91, - ..Default::default() - }]; - let mut next = campaign.clone(); - next.revision = 1; - let world_receipt = WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision: 0, - revision: 1, - command_kind: "persistence_regression".into(), - committed_at: Utc::now(), - roll: None, - }; - - store - .append_world_commit( - &campaign_row, - &next, - "persistence-regression-1", - &world_receipt, - &[], - &[], - std::slice::from_ref(&repeated_receipt), - None, - None, - ) - .unwrap(); - - let (reloaded_envelope, reloaded_receipt) = store - .load::("persona_stage_receipt.v1", stored_receipt.storage_key()) - .unwrap() - .unwrap(); - assert_eq!(reloaded_envelope, stored_envelope); - assert_eq!(reloaded_receipt, stored_receipt); - assert_eq!( - store - .load::("campaign.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1 - .revision, - 1 - ); - } - - #[test] - fn world_commit_rejects_a_semantic_model_receipt_collision_without_mutation() { - let dir = tempfile::tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); - let campaign = crate::kernel::tests::campaign(); - let campaign_row = store - .create_unadmitted_fixture_campaign(&campaign, &[], &[]) - .unwrap(); - let stored_receipt = model_receipt(); - store - .persist_model_stage_receipts(std::slice::from_ref(&stored_receipt)) - .unwrap(); - - let mut collision = stored_receipt; - collision.output_hash = "sha256:different-output".into(); - let mut next = campaign.clone(); - next.revision = 1; - let world_receipt = WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision: 0, - revision: 1, - command_kind: "persistence_regression".into(), - committed_at: Utc::now(), - roll: None, - }; - - let error = store - .append_world_commit( - &campaign_row, - &next, - "persistence-regression-1", - &world_receipt, - &[], - &[], - std::slice::from_ref(&collision), - None, - None, - ) - .unwrap_err(); - - assert!( - error - .to_string() - .contains("immutable model-stage receipt conflict") - ); - assert_eq!( - store - .load::("campaign.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1 - .revision, - 0 - ); - } -} diff --git a/crates/ghostlight-dungeon/src/persona.rs b/crates/ghostlight-dungeon/src/persona.rs deleted file mode 100644 index f048abf..0000000 --- a/crates/ghostlight-dungeon/src/persona.rs +++ /dev/null @@ -1,6540 +0,0 @@ -use crate::agent::{ - ModelAgentFailure, ModelAgentSpec, ModelAgentTool, ModelAgentToolContext, - ModelAgentToolOutcome, causal_source_ids, run_model_agent, -}; -use crate::model::{ModelPort, ModelStageOutput, ModelStageRequest, run_validated_stage}; -use crate::session_zero::{AggregatedBoundary, CampaignContract}; -use anyhow::{Context, Result, anyhow}; -use async_trait::async_trait; -use ghostlight_persona_projection::{ - InterpreterPrompt, MEMBRANE_SCHEMA, PersonaPrompt, ProjectorPrompt, build_interpreter_prompt, - build_persona_prompt, build_projector_prompt, narrative_stream_is_clean, -}; -use schemars::{JsonSchema, schema_for}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; -use std::sync::Arc; - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ActorInteractionRole { - DirectResponseExpected, - PresentObserver, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum PersonaSubjectKind { - IndividualActor, - CohesiveGestalt, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct PermittedActorSlice { - pub actor_id: String, - pub location_id: String, - pub subject_kind: PersonaSubjectKind, - pub snapshot_binding: String, - pub interaction_role: ActorInteractionRole, - pub identity_experience: Vec, - /// Established identifiers owned by other people in the actor's immediate - /// scene or source population. This is social context, not a namespace - /// registry: the kernel uses it only to prevent a newly adopted handle - /// from silently impersonating an already-durable person. - pub reserved_public_identities: BTreeSet, - pub memories: Vec, - /// Exact recent public responses already committed for this stable subject. - /// These are event-history witnesses, not private memory or new world fact. - pub recent_self_authored_turns: Vec, - pub perceived_events: Vec, - pub perceived_actors: std::collections::BTreeMap, - pub relationships: Vec, - pub goals: Vec, - pub knowledge: Vec, - pub capabilities: Vec, - pub pressures: Vec, - pub affordances: Vec, - pub source_receipt_ids: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct LivedNarrativeStream { - pub text: String, - pub snapshot_binding: String, - pub projector_receipt: crate::model::ModelStageReceipt, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct PersonaProposalBundle { - pub private_delta: crate::domain::ActorStateDelta, - pub speech: Option, - /// Typed refusal lane for a directly addressed actor. WorldKernel lowers - /// it deterministically; this field cannot carry free-form effects. - #[serde(default)] - pub deliberate_silence: bool, - pub reaction_priority: i16, - pub world_actions: Vec, -} - -#[derive(Clone, Debug)] -pub struct PersonaTerminalBundle { - pub lived_stream: LivedNarrativeStream, - pub persona_output: String, - pub proposals: PersonaProposalBundle, - pub stage_receipts: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct CellActivityTargetSlice { - pub name: String, - pub locations: BTreeMap, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct CellMigrationDestinationSlice { - pub population_name: String, - pub location_id: String, - pub location_name: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct CellConstituentSlice { - pub subject_id: String, - pub subject_kind: crate::domain::AgencySubjectKind, - pub name: String, - pub collective_authority_id: Option, - pub location_ids: BTreeSet, - pub knowledge: BTreeSet, - pub capabilities: BTreeSet, - pub resources: BTreeSet, - pub information_channels: BTreeSet, - pub permitted_state_references: BTreeSet, - pub reachable_destinations: BTreeMap, - pub migration_destinations: BTreeMap, - pub activity_targets: BTreeMap, - pub goals: Vec, - pub relationships: BTreeMap, - pub memories: Vec, - pub current_posture: Option, - pub pressures: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct CellMemberSlice { - pub subject_id: String, - pub member_id: String, - pub name: String, - pub source_gestalt_id: String, - pub source_location_id: String, - pub knowledge: BTreeSet, - pub capabilities: BTreeSet, - pub resources: BTreeSet, - pub information_channels: BTreeSet, - pub permitted_state_references: BTreeSet, - pub migration_destinations: BTreeMap, - pub activity_targets: BTreeMap, - pub goals: Vec, - pub pressures: Vec, - pub relationships: BTreeMap, - pub memories: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct CellPerceivedEventSlice { - pub event_id: String, - pub summary: String, - pub perceived_by_subject_ids: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct CellCausalFollowThroughSlice { - pub anchor_reference: String, - pub responder_subject_id: String, - pub summary: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -pub struct PermittedCellSlice { - pub cell_id: String, - pub mode: crate::domain::SimulationCellMode, - pub world_revision: u64, - pub resolution_epoch: u64, - pub snapshot_binding: String, - pub constituents: Vec, - pub member_exceptions: Vec, - pub shared_knowledge: BTreeSet, - pub shared_capabilities: BTreeSet, - pub perceived_events: Vec, - /// Scheduler-selected historical or durable pressure that owns an exact - /// response window in this cell. It is context and provenance, never a - /// prescribed action or outcome. - pub causal_follow_through: Vec, - pub world_clock_pressure: Vec, - /// Canonical names for the exact current locations already represented by - /// this slice. This is identity context only; it grants no movement, - /// activity, or mutation authority. - pub canonical_locations: BTreeMap, - pub detail_focus_subject_id: Option, - /// Exact subjects that own this cell's bounded decision slots for the - /// current strategic wave. Resolution chooses these before inference; - /// Projector output may describe them but may not decide who participates. - pub decision_owner_ids: BTreeSet, - pub max_actions: usize, - pub source_receipt_ids: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct CellTerminalBundle { - pub lived_stream: LivedNarrativeStream, - pub persona_output: String, - pub appraisal: crate::domain::CellAppraisal, - pub stage_receipts: Vec, -} - -#[derive(Clone, Debug)] -pub struct CellPipelineFailure { - pub diagnostic: String, - pub stage_receipts: Vec, -} - -impl std::fmt::Display for CellPipelineFailure { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter.write_str(&self.diagnostic) - } -} - -impl std::error::Error for CellPipelineFailure {} - -fn cell_pipeline_failure( - error: anyhow::Error, - mut prior_stage_receipts: Vec, -) -> anyhow::Error { - if let Some(failure) = error.downcast_ref::() { - prior_stage_receipts.extend(failure.stage_receipts.clone()); - } else if let Some(omission) = error.downcast_ref::() { - prior_stage_receipts.extend(omission.stage_receipts.clone()); - } - anyhow::Error::new(CellPipelineFailure { - diagnostic: format!("{error:#}").chars().take(4_000).collect(), - stage_receipts: distinct_stage_receipts(prior_stage_receipts), - }) -} - -fn distinct_stage_receipts( - receipts: Vec, -) -> Vec { - let mut seen = BTreeSet::new(); - receipts - .into_iter() - .filter(|receipt| seen.insert(receipt.storage_key().to_owned())) - .collect() -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellAppraisalProposal { - actions: Vec, - inactions: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -enum CellInterpreterAgentCommand { - Submit { - decisions: BTreeMap, - }, - UpsertDecision { - subject_id: String, - decision: serde_json::Value, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellInterpreterAgentAction { - command: CellInterpreterAgentCommand, -} - -#[derive(Debug)] -enum CellInterpreterAgentOutput { - Appraisal(crate::domain::CellAppraisal), - MissingPersonaDecision { subject_ids: Vec }, -} - -#[derive(Clone, Debug, Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -enum CellInterpreterFinding { - DraftProgress { - decision_subject_ids: Vec, - missing_subject_ids: Vec, - }, - UnknownDecisionOwner { - subject_id: String, - allowed_subject_ids: Vec, - }, - SubmitRequiresEmptyDraft { - repair_subject_ids: Vec, - }, - DecisionNotRepairable { - subject_id: String, - repair_subject_ids: Vec, - }, - LocalValidation { - diagnostic: String, - decision_subject_ids: Vec, - }, - EffectMismatch { - rejected: Vec, - }, -} - -#[derive(Clone, Debug, Serialize)] -struct CellInterpreterEffectFinding { - subject_id: String, - mismatch_kind: CellEffectMismatchKind, - repair_guidance: String, -} - -#[derive(Debug)] -struct MissingExplicitCellDecision { - cell_id: String, - stage_receipts: Vec, - lived_stream: LivedNarrativeStream, - active_subject_ids: BTreeSet, - projector_receipts: Vec, -} - -impl std::fmt::Display for MissingExplicitCellDecision { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - formatter, - "cell {} Persona supplied no explicit attributed action or inaction", - self.cell_id - ) - } -} - -impl std::error::Error for MissingExplicitCellDecision {} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellActionCandidate { - subject_id: String, - intent: String, - intended_effect: String, - priority: i16, - state_references: Vec, - public_channels: Vec, - effects: CellEffectBundleCandidate, -} - -#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellEffectBundleCandidate { - institution: Option, - gestalt_pressure: Option, - gestalt_activities: Option, - gestalt_migration: Option, - actor_move: Option, - actor_activities: Option, - member_activities: Option, - member_migration: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellInstitutionEffectCandidate { - #[schemars(length(min = 1, max = 240))] - posture: String, - location_ids: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellGestaltPressureEffectCandidate { - #[serde(default)] - pressure_additions: Vec, - #[serde(default)] - pressure_resolutions: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellActivityScopeCandidate { - #[serde(default)] - target_subject_ids: Vec, - #[serde(default)] - location_ids: Vec, -} - -#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellActivitySetCandidate { - prepare: Option>, - coordinate: Option>, - investigate: Option>, - recruit: Option>, - obstruct: Option>, - trade: Option>, - communicate: Option>, -} - -impl CellActivitySetCandidate { - fn into_effects( - self, - ) -> impl Iterator< - Item = ( - crate::domain::StrategicActivityKind, - CellActivityScopeCandidate, - ), - > { - [ - (crate::domain::StrategicActivityKind::Prepare, self.prepare), - ( - crate::domain::StrategicActivityKind::Coordinate, - self.coordinate, - ), - ( - crate::domain::StrategicActivityKind::Investigate, - self.investigate, - ), - (crate::domain::StrategicActivityKind::Recruit, self.recruit), - ( - crate::domain::StrategicActivityKind::Obstruct, - self.obstruct, - ), - (crate::domain::StrategicActivityKind::Trade, self.trade), - ( - crate::domain::StrategicActivityKind::Communicate, - self.communicate, - ), - ] - .into_iter() - .flat_map(|(activity, scopes)| { - scopes - .into_iter() - .flatten() - .map(move |scope| (activity.clone(), scope)) - }) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellMigrationEffectCandidate { - destination_gestalt_id: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellActorMoveEffectCandidate { - destination_id: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellEffectVerification { - verdicts: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellActionEffectVerdict { - action_index: usize, - result: CellEffectMatchResult, - findings: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellEffectMismatchFinding { - mismatch_kind: CellEffectMismatchKind, - repair_guidance: String, -} - -struct CellActionVerificationRun { - action_index: usize, - output: ModelStageOutput, - verdict: CellActionEffectVerdict, -} - -#[derive(Debug)] -struct CellEffectVerifierWaveFailure { - diagnostics: Vec, - completed_stage_receipts: Vec, -} - -impl std::fmt::Display for CellEffectVerifierWaveFailure { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - formatter, - "cell effect verifier wave failed: {}", - self.diagnostics.join("; ") - ) - } -} - -impl std::error::Error for CellEffectVerifierWaveFailure {} - -#[derive(Debug)] -struct CellEffectVerifierTaskFailure { - diagnostic: String, - completed_stage_receipt: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(rename_all = "snake_case")] -enum CellEffectMatchResult { - Match, - Mismatch, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)] -#[serde(rename_all = "snake_case")] -enum CellEffectMismatchKind { - SubjectSwap, - EffectOmission, - EffectReversal, - TargetSubstitution, - InventedOutcome, - WrongEffectKind, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellProjectionProposal { - segments: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct CellPerspectiveSegment { - subject_id: String, - narrative: String, -} - -const CELL_PROJECTION_OUTPUT_CONTRACT: &str = r#"{ - "segments":[ - {"subject_id":"one exact supplied perspective owner","narrative":"private lived prose for only that subject"} - ] -}"#; - -const CELL_EFFECT_VERIFIER_INSTRUCTIONS: &str = "You are the private semantic verifier between an Interpreter and the world kernel. Judge this one candidate action's typed effects as one composition against the exact attributed subject's choice in the Persona turn. Structural permissions were already checked. Use exact_subject_permission as the sole map of canonical subjects, locations, and destinations for this actor. canonical_locations is sibling identity context: compare it with exact_subject_permission.location_ids, and never treat a name as granting locality, co-presence, reach, publication, movement, target, effect, or mutation authority. A matching current-location name denotes that place or its unnamed local public, not an omitted canonical subject. activity_targets supplies each canonical target's exact name and current locations; reachable_destinations supplies exact actor-movement destination IDs and names; migration_destinations supplies exact population names and locations. Preserve every distinct affirmative means the subject actually chooses. Do not invent another means from a purpose, refusal, restraint, condition to preserve, desired social norm, or hoped-for state. Keeping someone's choice open, declining to coerce them, leaving state unchanged, respecting autonomy, or waiting for another subject's decision requires no additional typed effect unless the Persona separately chooses an observable act to do it. Communication can therefore be faithfully combined with restraint without implying coordinate, recruit, posture, or pressure effects. Reject effect omission only when the Persona explicitly undertakes another observable act. When one choice contains relocation, an activity at the subject's exact snapshot location occurs before relocation and an activity at the exact admitted destination occurs after arrival; activities within one location phase are an unordered atomic set. Array and object field order are not chronology. When the Persona chooses to go to a canonical target, actor_move must use that target's actual different reachable location. If actor and target are already co-located, reject movement to some other place; a local communicate, coordinate, or prepare may encode the stated attempt instead. A place named only in prose and absent from reachable_destinations and migration_destinations is local texture inside the supplied activity location; walking to it cannot justify rejecting a concrete local prepare or repair as omitted travel. Return exactly one verdict with action_index 0. A gestalt_migration means that exact population leaf chooses to travel together to the supplied destination within the strategic horizon; loading, waiting, giving away passage, sending only some other subject, or merely considering travel does not entail it. Conversely, when the population chooses to board, depart, or relocate together, reject gestalt_activity prepare that erases the chosen journey. Gestalt migration never entails that a named member moved. A member_migration means that named member personally chooses to travel to the destination. Boarding a transport whose supplied destination is unambiguous in the lived stream is a chosen journey; the Persona need not repeat the place name. Giving away a berth, sending somebody else, waiting, or merely considering travel does not entail migration. Conversely, when the member chooses to board, depart, travel, or join the supplied destination, reject member_activity that reduces that commitment to preparing, queuing, or approaching. A member_activity belongs only to that exact named person's stated attempt; it cannot be reassigned to their population. Communication targets must be the exact canonical subjects actually addressed in the Persona turn. An exact activity_targets entry is sufficient authority to attempt direct communication with that named subject; allowed_persistent_publication_channels governs only durable public publication and is never an additional requirement for direct contact. One communicate activity is also the complete supported composition when the same utterance addresses exact canonical targets and an unnamed public audience: target_subject_ids names the canonical addressees and candidate_action.public_channels names the simultaneous public reach. A call to unnamed people at a canonical location is such public or local audience, not a missing activity target. Do not demand a second targetless communicate for that same utterance. Use a targetless communicate only when the communication has no exact canonical addressee. Internal-population coordination is owner-specific: apply only coordination_target_contract.rule for this exact attributed subject, never a rule belonging to another subject kind. If the Persona addresses an unnamed clerk, dock master, passerby, or local environment, reject any effect that substitutes a containing population, related institution, or merely permitted ID. A targetless local investigate at the subject's exact current or paired movement destination is the faithful supported shape for seeking information from an unnamed role or the environment; its empty target list is intentional and must not itself be grounds for rejection. An institution posture must express its stated commitment or withholding. A gestalt pressure resolution must be causally supported by its stated attempt, and an added pressure must be a resulting unresolved condition rather than completed-action prose. An activity records only the exact attempt—never successful preparation, coordination, discovery, recruitment, obstruction, exchange, delivery, persuasion, acceptance, or target response. Reject omissions, reversals, subject swaps, wrong destinations, wishful outcomes, and effects that the Persona did not choose. Be concise. Return exactly one JSON object. A faithful verdict uses result \"match\" and an empty findings array. Otherwise use result \"mismatch\" and return the complete bounded set of distinct mismatches you can identify in this same action; do not reveal one defect per pass. Every finding needs mismatch_kind (\"subject_swap\", \"effect_omission\", \"effect_reversal\", \"target_substitution\", \"invented_outcome\", or \"wrong_effect_kind\") and one concrete repair_guidance sentence of at most 240 characters. Name the exact omitted choice, substituted target, or wrong destination. When no supplied typed effect composition can faithfully encode the choice, explicitly say to remove the action rather than downgrade or redirect it. Shape: {\"verdicts\":[{\"action_index\":0,\"result\":\"match\",\"findings\":[]}]}"; - -const CELL_ACTIVITY_CLASSIFICATION_GUIDANCE: &str = "Classify the chosen means by what the subject actually does. communicate means speak, send, offer, ask, or notify; coordinate means arrange a joint attempt; investigate means inspect, examine, diagnose, measure, test, or assess an existing condition in order to learn; recruit means invite; trade means offer an exchange; obstruct means attempt interference. prepare means materially repair, build, arrange, or ready a bounded resource, capability, or plan. Merely inspecting a handcart, regulator, record, route, patient, or other existing condition before deciding what to do is investigate, not prepare. Only actual repair or readiness work is prepare."; - -#[async_trait] -pub trait ExecutionPermit: Send + Sync { - async fn require(&self, actor_id: &str, snapshot_binding: &str, stage: &str) -> Result<()>; -} - -#[derive(Clone)] -pub struct AllowAllPermit; -#[async_trait] -impl ExecutionPermit for AllowAllPermit { - async fn require(&self, _: &str, _: &str, _: &str) -> Result<()> { - Ok(()) - } -} - -#[derive(Clone)] -pub struct PersonaProjectionEngine { - pub model: Arc, - pub permit: Arc, - pub projector_model: String, - pub persona_model: String, - pub interpreter_model: String, -} - -impl PersonaProjectionEngine { - pub async fn execute(&self, slice: PermittedActorSlice) -> Result { - self.permit - .require(&slice.actor_id, &slice.snapshot_binding, "projector") - .await?; - let typed_context = serde_json::to_string(&slice)?; - let visible_stimulus = slice.perceived_events.join("\n"); - let projector_prompt = build_projector_prompt(&ProjectorPrompt { - identity: &slice.actor_id, - typed_context: &typed_context, - visible_stimulus: &visible_stimulus, - domain_guidance: "The runtime is a persistent fictional world. Distances, knowledge, capabilities, relationships, and custody remain bounded by the supplied slice.", - word_budget: 140, - }); - let projected = run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "projector".into(), - model: self.projector_model.clone(), - snapshot_binding: slice.snapshot_binding.clone(), - lived_stream: projector_prompt, - output_schema: None, - source_receipt_ids: slice.source_receipt_ids.clone(), - temperature: Some(0.0), - max_output_tokens: Some(256), - }, - ) - .await?; - if !narrative_stream_is_clean(&projected.narrative) { - return Err(anyhow!("projector violated lived-narrative membrane")); - } - let lived = LivedNarrativeStream { - text: ground_actor_lived_stream(&slice, &projected.narrative), - snapshot_binding: slice.snapshot_binding.clone(), - projector_receipt: projected.receipt.clone(), - }; - - self.permit - .require(&slice.actor_id, &slice.snapshot_binding, "persona") - .await?; - // This is the membrane: the Persona's domain context is exactly one lived stream. - let persona = run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "persona".into(), - model: self.persona_model.clone(), - snapshot_binding: slice.snapshot_binding.clone(), - lived_stream: build_persona_prompt(&PersonaPrompt { - identity: &slice.actor_id, - lived_stream: &lived.text, - domain_guidance: "Respond as a situated character. When the lived stream says a response is expected from you, make your answer, refusal, or deliberate silence observable now. Speech and attempted effects are distinct; the world kernel resolves consequences. Asking, inviting, persuading, threatening, or demanding completes only your own speech: never supply the other person's answer, choice, consent, belief, disclosure, or obedience.", - word_budget: 160, - }), - output_schema: None, - source_receipt_ids: causal_source_ids( - &slice.source_receipt_ids, - std::slice::from_ref(&projected.receipt), - ), - temperature: Some(0.7), - max_output_tokens: Some(256), - }, - ) - .await?; - - self.permit - .require(&slice.actor_id, &slice.snapshot_binding, "interpreter") - .await?; - let prompt_schema = serde_json::to_value(schema_for!(PersonaProposalBundle))?; - let mut schema = prompt_schema.clone(); - constrain_interpreter_schema(&mut schema, &slice)?; - let permission_guidance = actor_interpreter_guidance(&slice); - let mut request = ModelStageRequest { - stage: "interpreter".into(), - model: self.interpreter_model.clone(), - snapshot_binding: slice.snapshot_binding.clone(), - lived_stream: build_interpreter_prompt(&InterpreterPrompt { - identity: &slice.actor_id, - typed_context: &typed_context, - lived_stream: &lived.text, - persona_output: &persona.narrative, - output_schema: Some(&serde_json::to_string(&prompt_schema)?), - domain_guidance: &permission_guidance, - }), - output_schema: Some(schema), - source_receipt_ids: causal_source_ids( - &slice.source_receipt_ids, - &[projected.receipt.clone(), persona.receipt.clone()], - ), - temperature: Some(0.0), - max_output_tokens: Some(768), - }; - let mut interpreter_receipts = Vec::new(); - let proposals = loop { - let mut interpreted = run_validated_stage(self.model.as_ref(), &request).await?; - let structured = interpreted - .structured - .clone() - .ok_or_else(|| anyhow!("interpreter produced no typed proposal"))?; - let proposals: PersonaProposalBundle = serde_json::from_value(structured.clone())?; - match validate_actor_proposals(&slice, &proposals) { - Ok(()) => { - interpreter_receipts.push(interpreted.receipt); - break proposals; - } - Err(error) if interpreter_receipts.is_empty() => { - interpreted.receipt.validation_result = "semantic_invalid".into(); - interpreted.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - interpreter_receipts.push(interpreted.receipt); - self.permit - .require(&slice.actor_id, &slice.snapshot_binding, "interpreter") - .await?; - append_actor_correction(&mut request, &error, &structured); - } - Err(error) => { - return Err(anyhow!( - "actor interpreter failed semantic validation after one correction: {error}" - )); - } - } - }; - self.permit - .require(&slice.actor_id, &slice.snapshot_binding, "terminal") - .await?; - let mut stage_receipts = vec![projected.receipt, persona.receipt]; - stage_receipts.extend(interpreter_receipts); - Ok(PersonaTerminalBundle { - lived_stream: lived, - persona_output: persona.narrative, - proposals, - stage_receipts, - }) - } -} - -fn actor_interpreter_guidance(slice: &PermittedActorSlice) -> String { - let response_guidance = match slice.interaction_role { - ActorInteractionRole::DirectResponseExpected => { - "This actor is an exact direct addressee. Extract an explicit spoken response, or set deliberate_silence true only when the Persona deliberately refuses or remains silent. Do not erase the Persona's response into null fields." - } - ActorInteractionRole::PresentObserver => { - "This actor is present but was not directly asked to respond. Speech or observable action remains optional and must follow only from this actor's projected choice." - } - }; - let ownership_guidance = match slice.subject_kind { - PersonaSubjectKind::IndividualActor => { - "Record only private changes supported by the lived stream and typed context. identity_adoption is null unless the Persona explicitly adopts or presents one public self-identifier in its own speech; when set, copy the exact spoken handle and nothing else. World actions are attempts, not completed effects." - } - PersonaSubjectKind::CohesiveGestalt => { - "This is a cohesive population appraisal. Extract only collective speech or deliberate silence. Every actor-private delta must remain empty, identity_adoption must be null, and world_actions must be empty; strategic population action uses the cell-resolution path, not foreground dialogue." - } - }; - format!( - "{response_guidance} {ownership_guidance} Speech is extracted separately and is already complete. Do not emit a world action merely to make another actor answer, choose, consent, believe, disclose, feel, or obey; the other actor retains agency and any requested response remains unresolved. actor_id must be {:?}. Exact allowed state references are {:?}. Relationship update keys may only be {:?}.", - slice.actor_id, - allowed_actor_references(slice), - slice.perceived_actors.keys().collect::>() - ) -} - -fn ground_actor_lived_stream(slice: &PermittedActorSlice, projection: &str) -> String { - let identity = if slice.identity_experience.is_empty() { - "no more specific self-identity than your exact actor identity".to_owned() - } else { - slice.identity_experience.join("; ") - }; - let reliable_knowledge = if slice.knowledge.is_empty() { - "no additional external fact beyond what is happening in front of you".to_owned() - } else { - slice.knowledge.join("; ") - }; - let visible_now = if slice.perceived_events.is_empty() { - "nothing new beyond the immediate situation".to_owned() - } else { - slice.perceived_events.join("; ") - }; - let people_now = if slice.perceived_actors.is_empty() { - "no one else clearly perceived".to_owned() - } else { - slice - .perceived_actors - .values() - .cloned() - .collect::>() - .join(", ") - }; - let recent_memory_start = slice.memories.len().saturating_sub(8); - let remembered_experience = if slice.memories.is_empty() { - "no additional autobiographical memory is active in this moment".to_owned() - } else { - slice.memories[recent_memory_start..].join("; ") - }; - let prior_public_response = if slice.recent_self_authored_turns.is_empty() { - "no earlier public response by this exact subject is active in this moment".to_owned() - } else { - slice.recent_self_authored_turns.join("; ") - }; - let interaction = match slice.interaction_role { - ActorInteractionRole::DirectResponseExpected => { - "You are an exact direct addressee of the current speech. A response is expected from you now. You retain the agency to answer, refuse, or remain silent, but refusal or silence must be made observable rather than disappearing from the scene." - } - ActorInteractionRole::PresentObserver => { - "You are present and perceive the current event, but you were not directly asked to respond. You may react from your own goals and pressures; you need not seize conversational focus." - } - }; - let established_peer_identities = if slice.reserved_public_identities.is_empty() { - "no other established public self-identifiers are active in your immediate social context" - .to_owned() - } else { - format!( - "these public self-identifiers already belong to other durable people in your immediate social context: {}", - slice - .reserved_public_identities - .iter() - .cloned() - .collect::>() - .join(", ") - ) - }; - let subject_grounding = match slice.subject_kind { - PersonaSubjectKind::IndividualActor => { - "You are one situated person. Speak and choose only for yourself." - } - PersonaSubjectKind::CohesiveGestalt => { - "You are a cohesive population Persona. You may speak plurally only from genuinely shared state. Do not invent unanimity about exceptions, speak for named individuals, or claim authority outside the supplied collective." - } - }; - format!( - "{projection}\n\n{subject_grounding} Your active self-identity: {identity}. In your social world, {established_peer_identities}. {interaction} Your reliable footing in this moment is narrow. What you know as external fact: {reliable_knowledge}. What you remember experiencing or being told: {remembered_experience}. These are your attributed recollections, not omniscient proof. Your exact recent public response history: {prior_public_response}. This response history records what you previously made observable; it does not prove that the content of those statements was true. What is happening now: {visible_now}. People you can presently perceive: {people_now}. Everything else in your impressions is feeling, inference, uncertainty, or possibility—not a remembered or witnessed fact." - ) -} - -fn validate_actor_proposals( - slice: &PermittedActorSlice, - proposals: &PersonaProposalBundle, -) -> Result<()> { - if matches!(slice.subject_kind, PersonaSubjectKind::CohesiveGestalt) - && (proposals.private_delta != crate::domain::ActorStateDelta::default() - || !proposals.world_actions.is_empty()) - { - return Err(anyhow!( - "cohesive foreground Gestalt appraisal may emit only speech or deliberate silence" - )); - } - if matches!( - slice.interaction_role, - ActorInteractionRole::DirectResponseExpected - ) && proposals - .speech - .as_deref() - .is_none_or(|value| value.trim().is_empty()) - && !proposals.deliberate_silence - { - return Err(anyhow!( - "directly addressed Persona produced no observable response" - )); - } - if proposals - .speech - .as_deref() - .is_some_and(|value| value.trim().is_empty() || value.chars().count() > 1_000) - { - return Err(anyhow!("Persona speech must contain 1 to 1000 characters")); - } - if let Some(identity) = proposals.private_delta.identity_adoption.as_deref() { - let identity = identity.trim(); - if identity.is_empty() || identity.chars().count() > 160 { - return Err(anyhow!( - "Persona identity adoption must contain 1 to 160 characters" - )); - } - let speech = proposals - .speech - .as_deref() - .ok_or_else(|| anyhow!("Persona identity adoption requires public speech"))?; - if !speech.to_lowercase().contains(&identity.to_lowercase()) { - return Err(anyhow!( - "Persona identity adoption must copy an exact spoken handle" - )); - } - if slice - .reserved_public_identities - .iter() - .any(|reserved| reserved.trim().to_lowercase() == identity.to_lowercase()) - { - return Err(anyhow!( - "Persona identity adoption conflicts with an established peer identity" - )); - } - } - Ok(()) -} - -fn append_actor_correction( - request: &mut ModelStageRequest, - error: &anyhow::Error, - rejected: &serde_json::Value, -) { - request.lived_stream.push_str(&format!( - "\n\nCORRECTION TASK—THE PREVIOUS INTERPRETATION WAS REJECTED.\nREJECTION: {error}\nPREVIOUS_REJECTED_INTERPRETATION:\n{}\nReturn one corrected complete interpretation against the same snapshot, lived stream, Persona output, and exact permissions. Preserve supported speech and private changes. Do not invent speech to justify a delta. If the Persona did not explicitly adopt or present a public self-identifier in its own speech, identity_adoption must be null. If the Persona explicitly claimed an established peer identity, do not hide the conflict by nulling identity_adoption; preserve the extracted claim so the unchanged Persona turn remains rejected.", - serde_json::to_string(rejected).unwrap_or_else(|_| "null".into()) - )); -} - -const INITIAL_ACTIVITY_TARGET_LIMIT: usize = 24; -const NARRATIVE_ACTIVITY_TARGET_LIMIT: usize = 24; - -fn initial_activity_targets( - targets: &BTreeMap, - relationships: &BTreeMap, - relevance_text: impl Iterator, - current_locations: &BTreeSet, -) -> BTreeMap { - let relevance_text = relevance_text.collect::>().join(" ").to_lowercase(); - let mut ranked = targets - .iter() - .map(|(subject_id, target)| { - let mut score = 0u8; - if relationships.contains_key(subject_id) { - score = score.saturating_add(4); - } - if relevance_text.contains(&subject_id.to_lowercase()) - || relevance_text.contains(&target.name.to_lowercase()) - { - score = score.saturating_add(2); - } - if target - .locations - .keys() - .any(|location_id| current_locations.contains(location_id)) - { - score = score.saturating_add(1); - } - (std::cmp::Reverse(score), subject_id, target) - }) - .collect::>(); - ranked.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(right.1))); - ranked - .into_iter() - .take(INITIAL_ACTIVITY_TARGET_LIMIT) - .map(|(_, subject_id, target)| (subject_id.clone(), target.clone())) - .collect() -} - -fn initial_constituent_activity_targets( - subject: &CellConstituentSlice, -) -> BTreeMap { - initial_activity_targets( - &subject.activity_targets, - &subject.relationships, - subject - .goals - .iter() - .chain(&subject.pressures) - .chain(&subject.memories) - .cloned(), - &subject.location_ids, - ) -} - -fn initial_member_activity_targets( - member: &CellMemberSlice, -) -> BTreeMap { - initial_activity_targets( - &member.activity_targets, - &member.relationships, - member - .goals - .iter() - .chain(&member.pressures) - .chain(&member.memories) - .cloned(), - &BTreeSet::from([member.source_location_id.clone()]), - ) -} - -fn narrative_activity_targets( - targets: &BTreeMap, - narrative: &str, -) -> BTreeMap { - let narrative = narrative.to_lowercase(); - targets - .iter() - .filter(|(_, target)| { - let name = target.name.trim().to_lowercase(); - name.chars().count() >= 3 - && narrative.match_indices(&name).any(|(start, matched)| { - let before = narrative[..start].chars().next_back(); - let after = narrative[start + matched.len()..].chars().next(); - !before.is_some_and(char::is_alphanumeric) - && !after.is_some_and(char::is_alphanumeric) - }) - }) - .take(NARRATIVE_ACTIVITY_TARGET_LIMIT) - .map(|(target_id, target)| (target_id.clone(), target.clone())) - .collect() -} - -fn bounded_interpreter_slice(slice: &PermittedCellSlice, narrative: &str) -> PermittedCellSlice { - let mut bounded = slice.clone(); - let decision_owner_ids = bounded.decision_owner_ids.clone(); - bounded - .constituents - .retain(|subject| decision_owner_ids.contains(&subject.subject_id)); - bounded - .member_exceptions - .retain(|member| decision_owner_ids.contains(&member.subject_id)); - for subject in &mut bounded.constituents { - let mut targets = initial_constituent_activity_targets(subject); - targets.extend(narrative_activity_targets( - &subject.activity_targets, - narrative, - )); - subject.activity_targets = targets; - } - for member in &mut bounded.member_exceptions { - let mut targets = initial_member_activity_targets(member); - targets.extend(narrative_activity_targets( - &member.activity_targets, - narrative, - )); - member.activity_targets = targets; - } - bounded -} - -fn decision_owner_perceived_events(slice: &PermittedCellSlice) -> Vec { - slice - .perceived_events - .iter() - .filter_map(|event| { - let perceived_by_subject_ids = event - .perceived_by_subject_ids - .intersection(&slice.decision_owner_ids) - .cloned() - .collect::>(); - (!perceived_by_subject_ids.is_empty()).then(|| CellPerceivedEventSlice { - event_id: event.event_id.clone(), - summary: event.summary.clone(), - perceived_by_subject_ids, - }) - }) - .collect() -} - -fn cell_projector_context(slice: &PermittedCellSlice) -> serde_json::Value { - serde_json::json!({ - "cell_id": slice.cell_id, - "mode": slice.mode, - "world_revision": slice.world_revision, - "resolution_epoch": slice.resolution_epoch, - "represented_constituent_count":slice.constituents.len(), - "constituents": slice.constituents.iter().filter(|subject| slice.decision_owner_ids.contains(&subject.subject_id)).map(|subject| serde_json::json!({ - "subject_id": subject.subject_id, - "subject_kind": subject.subject_kind, - "name": subject.name, - "collective_authority_id": subject.collective_authority_id, - "location_ids": subject.location_ids, - "knowledge": subject.knowledge, - "capabilities": subject.capabilities, - "resources": subject.resources, - "information_channels": subject.information_channels, - "reachable_destinations": subject.reachable_destinations, - "migration_destinations": subject.migration_destinations, - "activity_target_count":subject.activity_targets.len(), - "activity_targets":initial_constituent_activity_targets(subject), - "goals": subject.goals, - "relationships": subject.relationships, - "memories": subject.memories, - "already_committed_posture": subject.current_posture, - "pressures": subject.pressures, - })).collect::>(), - "represented_member_exception_count":slice.member_exceptions.len(), - "member_exceptions": slice.member_exceptions.iter().filter(|member| slice.decision_owner_ids.contains(&member.subject_id)).map(|member| serde_json::json!({ - "subject_id": member.subject_id, - "member_id": member.member_id, - "name": member.name, - "source_gestalt_id": member.source_gestalt_id, - "source_location_id": member.source_location_id, - "knowledge": member.knowledge, - "capabilities": member.capabilities, - "resources": member.resources, - "migration_destinations": member.migration_destinations, - "activity_target_count":member.activity_targets.len(), - "activity_targets":initial_member_activity_targets(member), - "goals": member.goals, - "pressures": member.pressures, - "relationships": member.relationships, - "memories": member.memories, - })).collect::>(), - "shared_knowledge": slice.shared_knowledge, - "shared_capabilities": slice.shared_capabilities, - "perceived_events":decision_owner_perceived_events(slice), - "causal_follow_through": slice.causal_follow_through, - "world_clock_pressure": slice.world_clock_pressure, - "canonical_locations": slice.canonical_locations, - "detail_focus_subject_id": slice.detail_focus_subject_id, - "max_actions": slice.max_actions, - }) -} - -fn cell_interpreter_context( - slice: &PermittedCellSlice, - active_subject_ids: &BTreeSet, -) -> serde_json::Value { - serde_json::json!({ - "cell_id": slice.cell_id, - "mode": slice.mode, - "world_revision": slice.world_revision, - "resolution_epoch": slice.resolution_epoch, - "canonical_locations": slice.canonical_locations, - "detail_focus_subject_id": slice.detail_focus_subject_id, - "causal_follow_through": slice.causal_follow_through, - "max_actions": slice.max_actions, - "exact_permissions": slice.constituents.iter().filter(|subject| active_subject_ids.contains(&subject.subject_id)).map(constituent_permission_context).collect::>(), - "member_permissions": slice.member_exceptions.iter().filter(|member| active_subject_ids.contains(&member.subject_id)).map(member_permission_context).collect::>(), - }) -} - -fn constituent_permission_context(subject: &CellConstituentSlice) -> serde_json::Value { - serde_json::json!({ - "subject_id": subject.subject_id, - "subject_kind": subject.subject_kind, - "name": subject.name, - "allowed_effect_types": allowed_constituent_effect_types(subject), - "collective_authority_id": subject.collective_authority_id, - "location_ids": subject.location_ids, - "allowed_persistent_publication_channels": subject.information_channels, - "permitted_state_references": subject.permitted_state_references, - "reachable_destinations": subject.reachable_destinations, - "migration_destinations": subject.migration_destinations, - "activity_targets": subject.activity_targets, - "already_committed_posture": subject.current_posture, - "current_pressures": subject.pressures, - }) -} - -fn member_permission_context(member: &CellMemberSlice) -> serde_json::Value { - serde_json::json!({ - "subject_id": member.subject_id, - "subject_kind": "gestalt_member", - "member_id": member.member_id, - "name": member.name, - "allowed_effect_types": allowed_member_effect_types(member), - "source_gestalt_id": member.source_gestalt_id, - "source_location_id": member.source_location_id, - "allowed_persistent_publication_channels": member.information_channels, - "permitted_state_references": member.permitted_state_references, - "migration_destinations": member.migration_destinations, - "activity_targets": member.activity_targets, - }) -} - -fn cell_action_verifier_permission( - slice: &PermittedCellSlice, - subject_id: &str, -) -> Result { - if let Some(subject) = slice - .constituents - .iter() - .find(|subject| subject.subject_id == subject_id) - { - return Ok(constituent_permission_context(subject)); - } - if let Some(member) = slice - .member_exceptions - .iter() - .find(|member| member.subject_id == subject_id) - { - return Ok(member_permission_context(member)); - } - Err(anyhow!( - "cell effect verifier cannot find exact authority for {subject_id}" - )) -} - -fn cell_action_verifier_permission_for_action( - slice: &PermittedCellSlice, - action: &crate::domain::CellActionProposal, -) -> Result { - let target_ids = action - .effects - .iter() - .flat_map(|effect| match effect { - crate::domain::StrategicCellEffect::GestaltActivity { - target_subject_ids, .. - } - | crate::domain::StrategicCellEffect::ActorActivity { - target_subject_ids, .. - } - | crate::domain::StrategicCellEffect::MemberActivity { - target_subject_ids, .. - } => target_subject_ids.iter(), - _ => [].iter(), - }) - .cloned() - .collect::>(); - let mut permission = cell_action_verifier_permission(slice, &action.subject_id)?; - if let Some(targets) = permission - .get_mut("activity_targets") - .and_then(serde_json::Value::as_object_mut) - { - targets.retain(|target_id, _| target_ids.contains(target_id)); - } - Ok(permission) -} - -fn coordination_target_contract(exact_subject_permission: &serde_json::Value) -> serde_json::Value { - if let Some(source_gestalt_id) = exact_subject_permission - .get("source_gestalt_id") - .and_then(serde_json::Value::as_str) - { - return serde_json::json!({ - "owner_kind":"gestalt_member", - "internal_population_target_subject_ids":[source_gestalt_id], - "rule":format!("For this named member, coordinating their source population is encoded by targeting exactly {source_gestalt_id}. A targetless coordinate would omit that chosen population target.") - }); - } - if exact_subject_permission.get("subject_kind") == Some(&serde_json::json!("gestalt")) { - return serde_json::json!({ - "owner_kind":"gestalt", - "internal_population_target_subject_ids":[], - "rule":"For this cohesive Gestalt owner, coordinating its own unnamed members is encoded as a targetless local coordinate. Named external targets remain explicit." - }); - } - serde_json::json!({ - "owner_kind":exact_subject_permission.get("subject_kind"), - "internal_population_target_subject_ids":null, - "rule":"This subject has no special internal-population coordination encoding. Preserve only exact addressed activity targets." - }) -} - -fn cell_scene_boundaries( - slice: &PermittedCellSlice, - active_subject_ids: &BTreeSet, -) -> String { - let mut by_location = BTreeMap::>::new(); - let mut unlocated = BTreeSet::new(); - let mut perspective_owners = BTreeSet::new(); - for subject in slice - .constituents - .iter() - .filter(|subject| active_subject_ids.contains(&subject.subject_id)) - { - perspective_owners.insert(subject.name.clone()); - if subject.location_ids.is_empty() { - unlocated.insert(subject.name.clone()); - } else { - for location_id in &subject.location_ids { - by_location - .entry(location_id.clone()) - .or_default() - .insert(subject.name.clone()); - } - } - } - for member in slice - .member_exceptions - .iter() - .filter(|member| active_subject_ids.contains(&member.subject_id)) - { - perspective_owners.insert(member.name.clone()); - by_location - .entry(member.source_location_id.clone()) - .or_default() - .insert(member.name.clone()); - } - let mut lines = vec![ - "Scene boundaries are reliable footing, not conjecture. Subjects listed at different locations are in simultaneous remote scenes and cannot directly see, hear, address, or answer one another without an explicitly perceived communication channel.".to_owned(), - ]; - lines.extend(by_location.into_iter().map(|(location_id, names)| { - format!( - "At location {location_id}: {}.", - names.into_iter().collect::>().join(", ") - ) - })); - if !unlocated.is_empty() { - lines.push(format!( - "No co-presence is established for these distributed or unlocated perspectives: {}.", - unlocated.into_iter().collect::>().join(", ") - )); - } - lines.push(format!( - "Only these projected perspectives may speak, choose, or receive an action or inaction record in this turn: {}. Every other constituent remains canonically represented by the cell but is inactive in this inference wave.", - perspective_owners - .into_iter() - .collect::>() - .join(", ") - )); - lines.join("\n") -} - -fn constrain_cell_projection_schema( - schema: &mut serde_json::Value, - slice: &PermittedCellSlice, -) -> Result<()> { - let segments = schema - .pointer_mut("/properties/segments") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("cell projection schema has no segment array"))?; - let required_count = required_projection_subject_ids(slice).len(); - if required_count == 0 || required_count > slice.max_actions { - return Err(anyhow!( - "resolution selected an invalid number of cell decision owners" - )); - } - segments.insert("minItems".into(), required_count.into()); - segments.insert("maxItems".into(), required_count.into()); - let segment = schema - .pointer_mut("/$defs/CellPerspectiveSegment/properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("cell projection schema has no segment properties"))?; - let mut subject_ids = slice - .decision_owner_ids - .iter() - .map(String::as_str) - .collect::>(); - if let Some(focus) = slice.detail_focus_subject_id.as_deref() - && let Some(index) = subject_ids - .iter() - .position(|subject_id| *subject_id == focus) - { - subject_ids.swap(0, index); - } - segment.insert( - "subject_id".into(), - serde_json::json!({"type":"string","enum":subject_ids}), - ); - Ok(()) -} - -fn bind_cell_projection( - slice: &PermittedCellSlice, - proposal: CellProjectionProposal, -) -> Result<(String, BTreeSet)> { - let required_subject_ids = required_projection_subject_ids(slice); - if proposal.segments.is_empty() - || proposal.segments.len() > slice.max_actions.max(required_subject_ids.len()).max(1) - { - return Err(anyhow!( - "cell Projector emitted an invalid perspective count" - )); - } - let mut segments = BTreeMap::new(); - for segment in proposal.segments { - if segment.narrative.trim().is_empty() || !narrative_stream_is_clean(&segment.narrative) { - return Err(anyhow!( - "cell Projector emitted an empty or non-narrative perspective" - )); - } - let owner_exists = slice - .constituents - .iter() - .any(|subject| subject.subject_id == segment.subject_id) - || slice - .member_exceptions - .iter() - .any(|member| member.subject_id == segment.subject_id); - if !owner_exists - || segments - .insert(segment.subject_id, segment.narrative) - .is_some() - { - return Err(anyhow!( - "cell Projector invented or duplicated a perspective owner" - )); - } - } - for subject_id in required_subject_ids { - if !segments.contains_key(&subject_id) { - return Err(anyhow!( - "cell Projector omitted required perspective owner {subject_id}" - )); - } - } - let active_subject_ids = segments.keys().cloned().collect::>(); - let mut lowered = Vec::with_capacity(segments.len()); - for (subject_id, narrative) in segments { - if let Some(subject) = slice - .constituents - .iter() - .find(|subject| subject.subject_id == subject_id) - { - let footing = if subject.location_ids.is_empty() { - "at an established but undisclosed location".to_owned() - } else { - format!( - "at {}", - subject - .location_ids - .iter() - .cloned() - .collect::>() - .join(", ") - ) - }; - lowered.push(format!( - "{} — {}:\n{}\n\n{}", - subject.name, - footing, - narrative.trim(), - constituent_agency_footing(subject) - )); - } else { - let member = slice - .member_exceptions - .iter() - .find(|member| member.subject_id == subject_id) - .expect("projection owner was validated"); - lowered.push(format!( - "{} — at {}:\n{}\n\n{}", - member.name, - member.source_location_id, - narrative.trim(), - member_agency_footing(member) - )); - } - } - Ok((lowered.join("\n\n"), active_subject_ids)) -} - -fn constituent_agency_footing(subject: &CellConstituentSlice) -> String { - let destinations = subject - .reachable_destinations - .values() - .cloned() - .chain(subject.migration_destinations.values().map(|destination| { - format!( - "{} at {}", - destination.population_name, destination.location_name - ) - })) - .collect::>(); - agency_footing( - &subject.name, - &destinations, - &subject.activity_targets, - &subject.information_channels, - ) -} - -fn member_agency_footing(member: &CellMemberSlice) -> String { - let destinations = member - .migration_destinations - .values() - .map(|destination| { - format!( - "{} at {}", - destination.population_name, destination.location_name - ) - }) - .collect::>(); - agency_footing( - &member.name, - &destinations, - &member.activity_targets, - &member.information_channels, - ) -} - -fn agency_footing( - subject_name: &str, - destinations: &[String], - targets: &BTreeMap, - publication_channels: &BTreeSet, -) -> String { - let destinations = if destinations.is_empty() { - "No distinct travel destination is presently established. You may seek a route from where you are, but you cannot assume arrival somewhere unnamed." - .to_owned() - } else { - format!( - "The distinct destinations you can presently choose to travel to are: {}. Somewhere else would first require finding a route from where you are.", - destinations.join(", ") - ) - }; - let targets = if targets.is_empty() { - "No named distant person or body is presently available to contact. You may still speak to an ordinary unnamed person nearby or work on the local environment." - .to_owned() - } else { - format!( - "The named people or bodies you can presently try to reach are: {}. You may still speak to an ordinary unnamed person nearby or work on the local environment.", - targets - .values() - .map(|target| { - let locations = target.locations.values().cloned().collect::>(); - if locations.is_empty() { - target.name.clone() - } else { - format!("{} at {}", target.name, locations.join(", ")) - } - }) - .collect::>() - .join(", ") - ) - }; - let channels = if publication_channels.is_empty() { - "You have no established channel for publishing this attempt beyond its immediate witnesses." - .to_owned() - } else { - format!( - "Your established channels for publishing an attempt are: {}.", - publication_channels - .iter() - .cloned() - .collect::>() - .join(", ") - ) - }; - format!("{subject_name}'s grounded agency: {destinations} {targets} {channels}") -} - -struct CellInterpreterWorkbench { - model: Arc, - permit: Arc, - interpreter_model: String, - slice: PermittedCellSlice, - active_subject_ids: BTreeSet, - lived_stream: String, - persona_turn: String, - campaign_policy: String, - appraisal_schema: serde_json::Value, - draft: BTreeMap, - repair_subject_ids: BTreeSet, - accepted_verifier_bindings: BTreeSet, -} - -impl CellInterpreterWorkbench { - fn progress(&self) -> CellInterpreterFinding { - let decision_subject_ids = self.draft.keys().cloned().collect::>(); - let decided = decision_subject_ids - .iter() - .cloned() - .collect::>(); - CellInterpreterFinding::DraftProgress { - decision_subject_ids, - missing_subject_ids: self - .active_subject_ids - .difference(&decided) - .cloned() - .collect(), - } - } - - async fn compile_draft( - &mut self, - source_receipt_ids: &[String], - ) -> ModelAgentToolOutcome { - let undecided_subject_ids = self - .draft - .iter() - .filter_map(|(subject_id, decision)| { - decision - .get("undecided") - .is_some() - .then_some(subject_id.clone()) - }) - .collect::>(); - if !undecided_subject_ids.is_empty() { - return ModelAgentToolOutcome::Accepted { - output: CellInterpreterAgentOutput::MissingPersonaDecision { - subject_ids: undecided_subject_ids, - }, - receipts: Vec::new(), - }; - } - if !self - .active_subject_ids - .iter() - .all(|subject_id| self.draft.contains_key(subject_id)) - { - self.repair_subject_ids = self - .active_subject_ids - .iter() - .filter(|subject_id| !self.draft.contains_key(*subject_id)) - .cloned() - .collect(); - return ModelAgentToolOutcome::Continue { - observation: self.progress(), - receipts: Vec::new(), - }; - } - - let value = serde_json::json!({"decisions":self.draft}); - let appraisal = - decode_cell_appraisal_proposal(&self.slice.cell_id, value).and_then(|proposal| { - let appraisal = - bind_cell_appraisal(&self.slice, &self.active_subject_ids, proposal)?; - validate_cell_appraisal(&self.slice, &appraisal)?; - validate_active_decision_owners(&self.active_subject_ids, &appraisal)?; - Ok(appraisal) - }); - let appraisal = match appraisal { - Ok(appraisal) => appraisal, - Err(error) => { - if self.repair_subject_ids.is_empty() { - self.repair_subject_ids = self.active_subject_ids.clone(); - } - return ModelAgentToolOutcome::Rejected { - finding: CellInterpreterFinding::LocalValidation { - diagnostic: error.to_string().chars().take(1_000).collect(), - decision_subject_ids: self.repair_subject_ids.iter().cloned().collect(), - }, - receipts: Vec::new(), - }; - } - }; - - let mut pending_actions = Vec::new(); - for action in &appraisal.actions { - let binding = match cell_effect_verification_binding( - &self.slice.snapshot_binding, - std::slice::from_ref(action), - ) { - Ok(binding) => binding, - Err(error) => { - return ModelAgentToolOutcome::Failed { - message: error.to_string(), - receipts: Vec::new(), - }; - } - }; - if !self.accepted_verifier_bindings.contains(&binding) { - pending_actions.push(action.clone()); - } - } - if pending_actions.is_empty() { - self.repair_subject_ids.clear(); - return ModelAgentToolOutcome::Accepted { - output: CellInterpreterAgentOutput::Appraisal(appraisal), - receipts: Vec::new(), - }; - } - - if let Err(error) = self - .permit - .require( - &self.slice.cell_id, - &self.slice.snapshot_binding, - "cell_effect_verifier", - ) - .await - { - return ModelAgentToolOutcome::Failed { - message: error.to_string(), - receipts: Vec::new(), - }; - } - let mut verifications = match run_cell_effect_verifier_wave( - self.model.clone(), - &self.interpreter_model, - &self.slice, - &self.lived_stream, - &self.persona_turn, - &self.campaign_policy, - &pending_actions, - source_receipt_ids, - ) - .await - { - Ok(verifications) => verifications, - Err(error) => { - let receipts = error - .downcast_ref::() - .map(|failure| failure.completed_stage_receipts.clone()) - .unwrap_or_default(); - return ModelAgentToolOutcome::Failed { - message: error.to_string(), - receipts, - }; - } - }; - let mut rejected = Vec::new(); - let mut receipts = Vec::with_capacity(verifications.len()); - for verification in &mut verifications { - let action = &pending_actions[verification.action_index]; - let binding = cell_effect_verification_binding( - &self.slice.snapshot_binding, - std::slice::from_ref(action), - ) - .expect("pending action binding was already computed"); - if matches!(verification.verdict.result, CellEffectMatchResult::Match) { - self.accepted_verifier_bindings.insert(binding); - } else { - let repair_summary = verification - .verdict - .findings - .iter() - .map(|finding| finding.repair_guidance.as_str()) - .collect::>() - .join(" "); - verification.output.receipt.validation_result = "semantic_invalid".into(); - verification.output.receipt.local_validation_error = - Some(repair_summary.chars().take(1_000).collect()); - rejected.extend(verification.verdict.findings.iter().map(|finding| { - CellInterpreterEffectFinding { - subject_id: action.subject_id.clone(), - mismatch_kind: finding.mismatch_kind.clone(), - repair_guidance: finding.repair_guidance.clone(), - } - })); - } - receipts.push(verification.output.receipt.clone()); - } - if rejected.is_empty() { - self.repair_subject_ids.clear(); - ModelAgentToolOutcome::Accepted { - output: CellInterpreterAgentOutput::Appraisal(appraisal), - receipts, - } - } else { - self.repair_subject_ids = rejected - .iter() - .map(|finding| finding.subject_id.clone()) - .collect(); - ModelAgentToolOutcome::Rejected { - finding: CellInterpreterFinding::EffectMismatch { rejected }, - receipts, - } - } - } -} - -#[async_trait] -impl ModelAgentTool for CellInterpreterWorkbench { - type Action = CellInterpreterAgentAction; - type Output = CellInterpreterAgentOutput; - type Finding = CellInterpreterFinding; - - fn action_schema(&self) -> std::result::Result { - let state = if self.draft.is_empty() { - CellInterpreterSchemaState::Initial - } else if self.repair_subject_ids.is_empty() { - return Err("nonterminal Interpreter draft has no repair owner".into()); - } else { - CellInterpreterSchemaState::Repair(&self.repair_subject_ids) - }; - cell_interpreter_agent_schema(&self.appraisal_schema, state) - .map_err(|error| error.to_string()) - } - - async fn invoke( - &mut self, - action: Self::Action, - context: &ModelAgentToolContext, - ) -> ModelAgentToolOutcome { - match action.command { - CellInterpreterAgentCommand::Submit { decisions } => { - if !self.draft.is_empty() { - return ModelAgentToolOutcome::Rejected { - finding: CellInterpreterFinding::SubmitRequiresEmptyDraft { - repair_subject_ids: self.repair_subject_ids.iter().cloned().collect(), - }, - receipts: Vec::new(), - }; - } - self.repair_subject_ids = decisions.keys().cloned().collect(); - self.draft = decisions; - self.compile_draft(&context.source_receipt_ids).await - } - CellInterpreterAgentCommand::UpsertDecision { - subject_id, - decision, - } => { - if !self.active_subject_ids.contains(&subject_id) { - return ModelAgentToolOutcome::Rejected { - finding: CellInterpreterFinding::UnknownDecisionOwner { - subject_id, - allowed_subject_ids: self.active_subject_ids.iter().cloned().collect(), - }, - receipts: Vec::new(), - }; - } - if self.draft.contains_key(&subject_id) - && !self.repair_subject_ids.contains(&subject_id) - { - return ModelAgentToolOutcome::Rejected { - finding: CellInterpreterFinding::DecisionNotRepairable { - subject_id, - repair_subject_ids: self.repair_subject_ids.iter().cloned().collect(), - }, - receipts: Vec::new(), - }; - } - self.draft.insert(subject_id, decision); - self.compile_draft(&context.source_receipt_ids).await - } - } - } -} - -fn required_projection_subject_ids(slice: &PermittedCellSlice) -> BTreeSet { - slice.decision_owner_ids.clone() -} - -fn allowed_constituent_effect_types(subject: &CellConstituentSlice) -> Vec<&'static str> { - match subject.subject_kind { - crate::domain::AgencySubjectKind::Actor => { - let mut types = vec!["actor_activities"]; - if !subject.reachable_destinations.is_empty() { - types.push("actor_move"); - } - types - } - crate::domain::AgencySubjectKind::Institution => vec!["institution"], - crate::domain::AgencySubjectKind::Gestalt => { - let mut types = vec!["gestalt_pressure", "gestalt_activities"]; - if !subject.migration_destinations.is_empty() { - types.push("gestalt_migration"); - } - types - } - } -} - -fn allowed_member_effect_types(member: &CellMemberSlice) -> Vec<&'static str> { - let mut types = vec!["member_activities"]; - if !member.migration_destinations.is_empty() { - types.push("member_migration"); - } - types -} - -#[derive(Clone)] -pub struct CellProjectionEngine { - pub model: Arc, - pub permit: Arc, - pub projector_model: String, - pub persona_model: String, - pub interpreter_model: String, - pub campaign_contract: Option, - pub aggregate_boundaries: Vec, -} - -#[derive(Clone)] -struct CellProjectedMoment { - lived_stream: LivedNarrativeStream, - active_subject_ids: BTreeSet, - projector_receipts: Vec, - causal_receipts: Vec, -} - -impl CellProjectionEngine { - pub async fn execute(&self, slice: PermittedCellSlice) -> Result { - match self.execute_once(slice.clone(), false, None).await { - Ok(bundle) => Ok(bundle), - Err(error) => { - let Some(omission) = error.downcast_ref::() else { - return Err(cell_pipeline_failure(error, Vec::new())); - }; - let mut prior_receipts = omission.stage_receipts.clone(); - let retry_projection = CellProjectedMoment { - lived_stream: omission.lived_stream.clone(), - active_subject_ids: omission.active_subject_ids.clone(), - projector_receipts: omission.projector_receipts.clone(), - causal_receipts: omission.stage_receipts.clone(), - }; - let mut bundle = match self.execute_once(slice, true, Some(retry_projection)).await - { - Ok(bundle) => bundle, - Err(error) => { - return Err(cell_pipeline_failure( - error.context( - "cell Persona supplied no explicit decision after one same-snapshot retry", - ), - prior_receipts, - )); - } - }; - prior_receipts.append(&mut bundle.stage_receipts); - bundle.stage_receipts = distinct_stage_receipts(prior_receipts); - Ok(bundle) - } - } - } - - async fn execute_once( - &self, - slice: PermittedCellSlice, - require_explicit_decision: bool, - projection: Option, - ) -> Result { - let campaign_policy = serde_json::to_string(&serde_json::json!({ - "campaign_contract":self.campaign_contract, - "aggregate_content_boundaries":self.aggregate_boundaries, - }))?; - let CellProjectedMoment { - lived_stream: lived, - active_subject_ids, - projector_receipts, - causal_receipts, - } = if let Some(projection) = projection { - projection - } else { - self.permit - .require(&slice.cell_id, &slice.snapshot_binding, "cell_projector") - .await?; - let projector_context = serde_json::to_string(&cell_projector_context(&slice))?; - let visible_stimulus = slice - .causal_follow_through - .iter() - .map(|focus| { - format!( - "Causal response window for {} [{}]: {}", - focus.responder_subject_id, focus.anchor_reference, focus.summary - ) - }) - .chain( - decision_owner_perceived_events(&slice) - .into_iter() - .map(|event| { - format!( - "Perceived by [{}]: {}", - event - .perceived_by_subject_ids - .iter() - .cloned() - .collect::>() - .join(", "), - event.summary - ) - }), - ) - .collect::>() - .join("\n"); - let mode_guidance = cell_projector_mode_guidance(&slice.mode); - let mode_guidance = format!( - "{mode_guidance} Treat already_committed_posture as an institutional course already in force, not a pressure, option, or fresh decision. Continuing it is holding steady; only a materially different commitment is a new posture choice. Each perceived event names the exact constituents that can perceive it; do not teach it to anyone else. A causal response window means the scheduler selected that exact committed anchor as decision-relevant for that exact responder; render the responder confronting it without prescribing action, emotion, success, or another subject's reply. Only supplied constituents and member_exceptions may own an internal perspective or choice. A person merely mentioned in an event is external observation when absent from those lists: never voice them. Every supplied member_exception was selected because that person has an actionable decision in this horizon. Render each selected person explicitly by name, with only their own footing and choices." - ); - let required_projection_subject_ids = required_projection_subject_ids(&slice); - let word_budget = - (120 + 45 * (slice.constituents.len() + slice.member_exceptions.len())).min(360); - let perspective_limit = slice - .max_actions - .max(required_projection_subject_ids.len()) - .max(1); - let mut projection_schema = serde_json::to_value(schema_for!(CellProjectionProposal))?; - constrain_cell_projection_schema(&mut projection_schema, &slice)?; - let mut projection_request = ModelStageRequest { - stage: "cell_projector".into(), - model: self.projector_model.clone(), - snapshot_binding: slice.snapshot_binding.clone(), - lived_stream: format!( - "\nYou are a private cell Projector. Convert only the permitted typed context and visible stimulus into compact lived narrative segments. Each segment belongs to exactly one supplied subject_id and contains only that subject's perceptions, memories, wants, fears, knowledge, and explicit uncertainty. Mentioned outsiders remain external observations: never give them an internal viewpoint. Campaign policy constrains what may become simulation content, but is never actor knowledge: omit line topics, keep veil topics off-screen, and introduce no ask_first topic. Do not narrativize or reveal the policy itself. Do not choose actions or claim world effects. Omit decorative recap. Return between {} and {perspective_limit} unique segments; do not narrate every ordinary constituent. Include every exact subject ID in REQUIRED PERSPECTIVE OWNERS, because each named member exception or debt focus has an actionable decision that must not disappear inside the aggregate. Put detail_focus_subject_id first when present. Spend any remaining slots only on subjects facing a materially different decision in this horizon.\n\nREQUIRED PERSPECTIVE OWNERS:\n{}\n\nReturn exactly one JSON object matching this stable shape:\n{CELL_PROJECTION_OUTPUT_CONTRACT}\n\nCAMPAIGN POLICY:\n{campaign_policy}\n\nDomain guidance:\n{mode_guidance}\n\nIdentity:\n{}\n\nPermitted typed context:\n{projector_context}\n\nVisible stimulus:\n{visible_stimulus}\n\nUse no more than {word_budget} narrative words across all segments.", - required_projection_subject_ids.len().max(1), - serde_json::to_string(&required_projection_subject_ids)?, - slice.cell_id - ), - output_schema: Some(projection_schema), - source_receipt_ids: slice.source_receipt_ids.clone(), - temperature: Some(0.0), - max_output_tokens: Some(768), - }; - let mut projector_receipts = Vec::new(); - let (projected_narrative, active_subject_ids, projector_receipt) = loop { - let mut projected = - match run_validated_stage(self.model.as_ref(), &projection_request) - .await - .context("cell projector model stage failed") - { - Ok(projected) => projected, - Err(error) => return Err(cell_pipeline_failure(error, projector_receipts)), - }; - let proposal = projected - .structured - .clone() - .ok_or_else(|| anyhow!("cell Projector produced no typed segments")) - .and_then(|value| serde_json::from_value(value).map_err(Into::into)); - match proposal.and_then(|proposal| bind_cell_projection(&slice, proposal)) { - Ok((narrative, active_subject_ids)) => { - let receipt = projected.receipt.clone(); - projector_receipts.push(projected.receipt); - break (narrative, active_subject_ids, receipt); - } - Err(error) if projector_receipts.is_empty() => { - projected.receipt.validation_result = "semantic_invalid".into(); - projected.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - projector_receipts.push(projected.receipt); - projection_request.lived_stream.push_str(&format!( - "\n\nLOCAL VALIDATOR REJECTED THE PREVIOUS SEGMENTS: {error}\nReturn one corrected complete JSON object against the same snapshot and contract." - )); - } - Err(error) => { - projected.receipt.validation_result = "semantic_invalid".into(); - projected.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - projector_receipts.push(projected.receipt); - return Err(cell_pipeline_failure( - anyhow!( - "cell Projector failed perspective binding after one correction: {error}" - ), - projector_receipts, - )); - } - } - }; - let lived_stream = LivedNarrativeStream { - text: format!( - "{}\n\n{}", - cell_scene_boundaries(&slice, &active_subject_ids), - projected_narrative - ), - snapshot_binding: slice.snapshot_binding.clone(), - projector_receipt, - }; - CellProjectedMoment { - lived_stream, - active_subject_ids, - causal_receipts: projector_receipts.clone(), - projector_receipts, - } - }; - self.permit - .require(&slice.cell_id, &slice.snapshot_binding, "cell_persona") - .await - .map_err(|error| cell_pipeline_failure(error, projector_receipts.clone()))?; - let persona_domain_guidance = if require_explicit_decision { - format!( - "{} Your previous response supplied no explicit strategic decision. Respond naturally again from this same lived moment, but make every voiced constituent end with either one concrete present-tense attempt or an explicit choice to hold or wait. Do not invent new perceptions, permissions, contacts, resources, or completed consequences.", - cell_persona_mode_guidance(&slice.mode) - ) - } else { - cell_persona_mode_guidance(&slice.mode).to_owned() - }; - let persona = match run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "cell_persona".into(), - model: self.persona_model.clone(), - snapshot_binding: slice.snapshot_binding.clone(), - lived_stream: build_persona_prompt(&PersonaPrompt { - identity: &slice.cell_id, - lived_stream: &lived.text, - domain_guidance: &persona_domain_guidance, - word_budget: (160 + 30 * slice.constituents.len()).min(320), - }), - output_schema: None, - source_receipt_ids: causal_source_ids(&slice.source_receipt_ids, &causal_receipts), - temperature: Some(0.7), - max_output_tokens: Some(512), - }, - ) - .await - .context("cell Persona model stage failed") - { - Ok(persona) => persona, - Err(error) => return Err(cell_pipeline_failure(error, projector_receipts)), - }; - let mut stage_receipts = projector_receipts.clone(); - stage_receipts.push(persona.receipt.clone()); - self.permit - .require(&slice.cell_id, &slice.snapshot_binding, "cell_interpreter") - .await - .map_err(|error| cell_pipeline_failure(error, stage_receipts.clone()))?; - let interpreter_narrative = format!("{}\n{}", lived.text, persona.narrative); - let visible_slice = bounded_interpreter_slice(&slice, &interpreter_narrative); - let mut appraisal_schema = serde_json::to_value(schema_for!(CellAppraisalProposal)) - .map_err(|error| cell_pipeline_failure(error.into(), stage_receipts.clone()))?; - constrain_cell_proposal_schema(&mut appraisal_schema, &visible_slice, &active_subject_ids) - .map_err(|error| cell_pipeline_failure(error, stage_receipts.clone()))?; - let interpreter_context = serde_json::to_string(&cell_interpreter_context( - &visible_slice, - &active_subject_ids, - )) - .map_err(|error| cell_pipeline_failure(error.into(), stage_receipts.clone()))?; - let permission_guidance = format!( - concat!( - "Emit at most {} exact constituent- or named-member-attributed attempts. Priority is an urgency score from 0 to 100 where higher numbers resolve first. ", - "Every subject in exact_permissions owns one schema-keyed decision slot. Fill that exact slot with one action or one inaction. Use undecided only when the Persona turn supplied no explicit choice or hold; runtime will retry the Persona rather than let the Interpreter invent one. Do not let a voiced constituent vanish during interpretation. ", - "Each action carries an effects object whose exact subject-specific lane keys are supplied by the schema. Across scalar effects and every expanded activity scope, an action has one to four exact effects total. Scalar lanes contain one typed effect. An activities lane is one object keyed by chosen activity kinds; each non-null kind contains an array of one to four separate exact target-and-location scopes. Preserve repeated uses of one activity kind as separate scopes when their targets or locations differ; never union scopes across distinct locations or audiences. Top-level lane names are stable across subjects: use null for a null-only unavailable lane and for any schema-required optional lane or activity key the subject does not use. A non-null lane or activity key absent from its exact schema is structurally unavailable: do not emit it and do not invent a destination. Pressure and migration lanes each have one slot. Preserve every means of one chosen course in one action. With relocation, activities at the exact snapshot location occur before departure and activities at the exact admitted destination occur after arrival; activity effects inside each location phase are an atomic set. Field and array order is not chronology. Never split one subject's single choice into multiple actions. ", - "Use gestalt_activities or member_activities for concrete attempts that do not themselves change pressure. A cohesive Gestalt coordinating its own unnamed internal members uses coordinate with an empty target_subject_ids list; do not invent its containing population, a distant population, or another canonical subject as the target of internal coordination. Cite the smallest exact set of state_references that materially supports each attempt; the permission list is an upper bound, not a checklist to echo. ", - "target_subject_ids and location_ids must come from that exact subject's permissions. activity_targets is the bounded exact set deterministically selected from current relevance plus canonical targets named exactly in the lived stream or Persona turn: each key is an authoritative ID and each value supplies the target's name and current canonical locations. Use an ID only when the Persona addresses that named target, never merely because the ID is permitted. If an addressed name has no supplied canonical target, treat it as an unnamed role and use a targetless local activity when that lane is supported. reachable_destinations maps exact actor-movement destination IDs to names. migration_destinations maps exact population destination IDs to names and locations. When the Persona chooses to go to a canonical target, compare the target's current locations with the acting subject's current location and exact reachable destinations; never guess a destination from an opaque ID. Every activity has at most four unique target_subject_ids; choose the four most causally relevant when more permitted subjects are involved. A member activity uses exactly the member's source_location_id. Internal work is prepare with no targets. A local investigate may have no target and use the exact current location to seek information from the environment or an unnamed ordinary role; asking an unnamed clerk or dock master for facts maps here and records only the inquiry, never a reply or discovery. A local communicate may likewise have no target at the exact current location when the Persona speaks, sends, offers, asks permission, or notifies an unnamed ordinary role; it records only the source's outgoing attempt, never a listener, reply, acceptance, or outcome. Communication with a canonical subject requires that exact target ID. When one utterance addresses canonical subjects and an unnamed public audience, emit one communicate activity with those exact target IDs and place its admitted public reach in public_channels; do not invent a second communicate lane. Never substitute a containing population, related institution, or merely permitted ID for an unnamed role. ", - "Write intended_effect as the affirmative attempted acts, never the purpose, restraint, condition to preserve, hoped-for outcome, or target response. Keep purpose and restraint in intent. Respecting choice, declining coercion, leaving state unchanged, or waiting for another subject does not add a typed effect unless the Persona separately chooses an observable act. Merely waiting, watching, staying, holding position, or remaining ready is attributed inaction, not prepare. prepare requires concrete work on a bounded arrangement, repair, resource, or capability-backed readiness change. Institution posture must be a specific materially new commitment or withholding of at most {} characters. already_committed_posture is state already in force: maintaining, continuing, or restating it is inaction and must not emit an institution action. Gestalt pressure_resolutions copy exact current_pressures; additions are new unresolved constraints, never completed actions. Use only permitted state references. public_channels means durable publication of this attempt through exact allowed_persistent_publication_channels; it is not a perception method or ordinary local speech. Use [] when that exact list is empty. ", - "A population that chooses to board, depart, or relocate together to one supplied migration_destinations key emits gestalt_migration; do not reduce it to prepare. It relocates only that exact population leaf and never implies a named member traveled. A named member who chooses to board, depart, travel, or join a supplied destination emits member_migration; use prepare only while departure remains unchosen. ", - "A population or arena cannot migrate a person. Runtime binds identity and effect owner IDs from subject_id. Do not emit institution_id, gestalt_id, actor_id, or member_id inside effect. An inaction means that exact subject takes no strategic action in this horizon. Record only a subject that explicitly holds, waits without making another attempt, or merely continues already_committed_posture in the Persona turn as an inaction, using its exact subject_id and a concrete reason of at most 160 characters. Waiting for the result of an action, withholding a different possible action, or declining one option after choosing another does not make the chosen action an inaction. Never invent an inaction for an unvoiced subject or use absence of a Persona decision as a reason. Inactions share the same count limit stated for actions. A subject cannot appear in both actions and inactions. When nobody acts, actions is empty and inactions must still contain at least one exact attributed decision from the Persona turn." - ), - slice.max_actions, - crate::domain::MAX_POSTURE_CHARS - ); - let permission_guidance = - format!("{permission_guidance} {CELL_ACTIVITY_CLASSIFICATION_GUIDANCE}"); - let permission_guidance = format!( - "{permission_guidance} A targetless local obstruct at the exact supplied location records attempted interference with unnamed infrastructure, terrain, traffic, or another local feature. It records only the source's attempt—never damage, disruption, or a target response. Never substitute a merely permitted canonical subject for that unnamed local feature." - ); - let permission_guidance = format!( - "{permission_guidance} causal_follow_through assigns a committed anchor to one exact decision owner without prescribing their choice. If that owner acts in response, include the supplied anchor_reference in state_references so the causal basis survives admission. An attributed inaction remains legal and needs no invented effect." - ); - let permission_guidance = format!( - "{permission_guidance} Campaign policy is a hard output boundary, not actor knowledge. Emit no action, inaction rationale, pressure, migration, posture, or activity that introduces a line topic, depicts a veil topic on-screen, or introduces an ask_first topic. Never reveal boundary attribution. CAMPAIGN POLICY: {campaign_policy}" - ); - let instructions = build_interpreter_prompt(&InterpreterPrompt { - identity: &slice.cell_id, - typed_context: &interpreter_context, - lived_stream: &lived.text, - persona_output: &persona.narrative, - output_schema: None, - domain_guidance: &format!( - "{permission_guidance} Operate the private Interpreter workbench. Its current typed action schema is authoritative and exposes only the transition legal now: one complete submit creates the draft, and exact named upsert_decision repairs follow rejection. A rejected submit preserves its draft. Only the deterministic workbench can accept the appraisal." - ), - }); - let mut interpreter_causal_receipts = causal_receipts; - interpreter_causal_receipts.push(persona.receipt.clone()); - let source_receipt_ids = - causal_source_ids(&slice.source_receipt_ids, &interpreter_causal_receipts); - let spec = ModelAgentSpec { - stage: "cell_interpreter".into(), - model: self.interpreter_model.clone(), - snapshot_binding: slice.snapshot_binding.clone(), - instructions, - source_receipt_ids, - temperature: Some(0.0), - max_output_tokens: Some(1_600), - max_steps: active_subject_ids.len().saturating_add(4).clamp(4, 8), - }; - let mut workbench = CellInterpreterWorkbench { - model: self.model.clone(), - permit: self.permit.clone(), - interpreter_model: self.interpreter_model.clone(), - slice: slice.clone(), - active_subject_ids: active_subject_ids.clone(), - lived_stream: lived.text.clone(), - persona_turn: persona.narrative.clone(), - campaign_policy: campaign_policy.clone(), - appraisal_schema, - draft: BTreeMap::new(), - repair_subject_ids: BTreeSet::new(), - accepted_verifier_bindings: BTreeSet::new(), - }; - let run = match run_model_agent(self.model.as_ref(), &spec, &mut workbench).await { - Ok(run) => run, - Err(ModelAgentFailure { message, receipts }) => { - stage_receipts.extend(receipts); - return Err(cell_pipeline_failure( - anyhow!("cell Interpreter agent failed: {message}"), - stage_receipts, - )); - } - }; - stage_receipts.extend(run.receipts); - let appraisal = match run.output { - CellInterpreterAgentOutput::Appraisal(appraisal) => appraisal, - CellInterpreterAgentOutput::MissingPersonaDecision { subject_ids } => { - return Err(anyhow::Error::new(MissingExplicitCellDecision { - cell_id: format!("{} ({})", slice.cell_id, subject_ids.join(", ")), - stage_receipts: distinct_stage_receipts(stage_receipts), - lived_stream: lived, - active_subject_ids, - projector_receipts, - })); - } - }; - self.permit - .require(&slice.cell_id, &slice.snapshot_binding, "cell_terminal") - .await - .map_err(|error| cell_pipeline_failure(error, stage_receipts.clone()))?; - return Ok(CellTerminalBundle { - lived_stream: lived, - persona_output: persona.narrative, - appraisal, - stage_receipts, - }); - } -} - -async fn run_cell_effect_verifier_wave( - model: Arc, - interpreter_model: &str, - slice: &PermittedCellSlice, - lived_stream: &str, - persona_turn: &str, - campaign_policy: &str, - actions: &[crate::domain::CellActionProposal], - source_receipt_ids: &[String], -) -> Result> { - let campaign_policy = serde_json::from_str::(campaign_policy)?; - let verifier_schema = cell_effect_verifier_schema(1)?; - let mut jobs = tokio::task::JoinSet::new(); - for (action_index, action) in actions.iter().enumerate() { - let exact_subject_permission = cell_action_verifier_permission_for_action(slice, action)?; - let coordination_target_contract = coordination_target_contract(&exact_subject_permission); - let verifier_context = serde_json::json!({ - "effect_order_contract":{ - "activity_effects_within_one_location":"unordered_atomic_set", - "cross_location_order":"snapshot_location_activity_then_relocation_then_destination_activity", - "field_order":"not_chronology" - }, - "local_attempt_contract":"A targetless local communicate at the source's exact current location faithfully records speech, an offer, a permission request, or a notice directed to an unnamed ordinary role. A targetless local obstruct there faithfully records attempted interference with unnamed infrastructure, terrain, traffic, or another local feature. Both record only the source's attempt—never a listener, reply, damage, disruption, acceptance, or outcome—and must not be rejected merely because target_subject_ids is empty.", - "spatial_effect_contract":"A prepare, investigate, or other activity may include incidental walking, approaching, queuing, carrying, or repositioning around an unnamed local feature while the source remains inside the effect's supplied canonical location. The activity records the attempt and need not serialize every footstep. Reject omitted movement only when the Persona clearly commits the subject to a different supplied canonical location or population destination; local texture does not create topology or establish arrival.", - "coordination_target_contract":coordination_target_contract, - "exact_subject_permission":exact_subject_permission, - "canonical_locations":slice.canonical_locations, - "lived_stream":lived_stream, - "persona_turn":persona_turn, - "candidate_action":{ - "action_index":0, - "subject_id":action.subject_id, - "intent":action.intent, - "intended_effect":action.intended_effect, - "state_references":action.state_references, - "public_channels":action.public_channels, - "typed_effects":action.effects, - }, - "campaign_policy":campaign_policy, - }); - let request = ModelStageRequest { - stage: "cell_effect_verifier".into(), - model: interpreter_model.to_owned(), - snapshot_binding: cell_effect_verification_binding( - &slice.snapshot_binding, - std::slice::from_ref(action), - )?, - lived_stream: format!( - "{CELL_EFFECT_VERIFIER_INSTRUCTIONS}\n\nCOORDINATION TARGET CONTRACT: coordination_target_contract.internal_population_target_subject_ids is the exact owner-specific target array for internal-population coordination. Preserve it; never apply a Gestalt owner's empty array to a named member.\n\nEFFECT ORDER CONTRACT: Exact activity locations derive the course. Snapshot-location activity precedes relocation; exact-destination activity follows arrival. Distinct activity effects inside one location phase are an unordered atomic set. Serialized field and array order is not chronology and cannot support an effect_reversal verdict.\n\nCONTEXT:\n{}", - serde_json::to_string(&verifier_context)? - ), - output_schema: Some(verifier_schema.clone()), - source_receipt_ids: source_receipt_ids.to_vec(), - temperature: Some(0.0), - max_output_tokens: Some(1_200), - }; - let model = model.clone(); - jobs.spawn(async move { - let output = match run_validated_stage(model.as_ref(), &request).await { - Ok(output) => output, - Err(error) => { - return Err(CellEffectVerifierTaskFailure { - diagnostic: format!( - "cell effect verifier action {action_index} failed: {error}" - ), - completed_stage_receipt: None, - }); - } - }; - let verification = output - .structured - .clone() - .ok_or_else(|| anyhow!("cell effect verifier produced no typed verdict")) - .and_then(|value| serde_json::from_value::(value).map_err(Into::into)) - .and_then(|verification| { - validate_effect_verification(&verification, 1)?; - Ok(verification) - }) - .map_err(|error: anyhow::Error| { - let diagnostic = format!( - "cell effect verifier action {action_index} failed local validation: {error}" - ); - let mut receipt = output.receipt.clone(); - receipt.validation_result = "semantic_invalid".into(); - receipt.local_validation_error = - Some(diagnostic.chars().take(1_000).collect()); - CellEffectVerifierTaskFailure { - diagnostic, - completed_stage_receipt: Some(receipt), - } - })?; - let verdict = verification - .verdicts - .into_iter() - .next() - .expect("one-action verifier schema and validator require one verdict"); - Ok::<_, CellEffectVerifierTaskFailure>(CellActionVerificationRun { - action_index, - output, - verdict, - }) - }); - } - - let mut verified = Vec::with_capacity(actions.len()); - let mut diagnostics = Vec::new(); - let mut failed_stage_receipts = Vec::new(); - while let Some(result) = jobs.join_next().await { - match result { - Ok(Ok(verification)) => verified.push(verification), - Ok(Err(failure)) => { - diagnostics.push(failure.diagnostic); - failed_stage_receipts.extend(failure.completed_stage_receipt); - } - Err(error) => diagnostics.push(format!("cell effect verifier task failed: {error}")), - } - } - if !diagnostics.is_empty() { - return Err(anyhow::Error::new(CellEffectVerifierWaveFailure { - diagnostics, - completed_stage_receipts: verified - .into_iter() - .map(|verification| verification.output.receipt) - .chain(failed_stage_receipts) - .collect(), - })); - } - verified.sort_by_key(|verification| verification.action_index); - Ok(verified) -} - -fn cell_projector_mode_guidance(mode: &crate::domain::SimulationCellMode) -> &'static str { - match mode { - crate::domain::SimulationCellMode::Cohesive => { - "This cell has real collective authority. Render a plural lived perspective from genuinely shared knowledge and capability only; describe constituent and named-member exceptions as separately attributed exceptions. A population cannot decide for a named member." - } - crate::domain::SimulationCellMode::Arena => { - "This cell is an arena, never a person or faction. Render an attributed polyphonic situation. Name each subject before its perspective; never use an unmarked first-person voice or a narrator that belongs to no constituent. This arena may contain simultaneous views from remote locations: state each subject's supplied location, keep remote scenes separate, and never stage shared sight, speech, or response unless exact co-presence or a perceived communication channel establishes it. An activity target is permission to attempt contact, not evidence that contact already exists. Never union secrets, knowledge, resources, intentions, authority, or voice between constituents or named-member exceptions." - } - } -} - -fn cell_persona_mode_guidance(mode: &crate::domain::SimulationCellMode) -> &'static str { - match mode { - crate::domain::SimulationCellMode::Cohesive => { - "Appraise the strategic horizon as a real collective. End this turn with a present-tense choice: describe the concrete attempt the collective now makes, or explicitly choose to hold or wait. An institution continuing its already committed posture is holding steady, not choosing that posture again. Deliberating, asking for a future decision, considering an option, or saying what could be done is intentional inaction unless the choice to act is actually made. Do not invent completed consequences." - } - crate::domain::SimulationCellMode::Arena => { - "Appraise the strategic horizon polyphonically. Name the constituent responsible for every perspective and decision; never speak as the arena or use an unmarked first-person voice. Only subjects already given an attributed internal perspective in the lived stream may choose; people merely observed or mentioned remain external. The lived stream may contain simultaneous remote scenes: preserve every stated location boundary, and never make one constituent see, hear, address, or answer another unless the stream explicitly establishes co-presence or a communication channel. Do not invent an available person, office, route, resource, or response absent from the lived stream. A constituent may choose to seek something unknown, but cannot claim contact with it. For each voiced constituent, end with a present-tense choice: a concrete attempt now, or an explicit choice to hold or wait. An institution continuing its already committed posture is holding steady, not choosing that posture again. Deliberating, asking for a future decision, considering an option, or saying what could be done is inaction unless that constituent actually chooses to act." - } - } -} - -fn validate_effect_verification( - verification: &CellEffectVerification, - action_count: usize, -) -> Result> { - if verification.verdicts.len() != action_count { - return Err(anyhow!( - "cell effect verifier returned {} verdicts for {action_count} actions", - verification.verdicts.len() - )); - } - let mut rejected = Vec::new(); - for (expected_index, verdict) in verification.verdicts.iter().enumerate() { - if verdict.action_index != expected_index { - return Err(anyhow!( - "cell effect verifier returned an incoherent verdict for action {expected_index}" - )); - } - match &verdict.result { - CellEffectMatchResult::Match if verdict.findings.is_empty() => {} - CellEffectMatchResult::Mismatch - if !verdict.findings.is_empty() - && verdict.findings.len() <= 6 - && verdict.findings.iter().all(|finding| { - !finding.repair_guidance.trim().is_empty() - && finding.repair_guidance.trim() == finding.repair_guidance - && finding.repair_guidance.chars().count() <= 240 - }) - && verdict - .findings - .iter() - .map(|finding| &finding.mismatch_kind) - .collect::>() - .len() - == verdict.findings.len() => - { - rejected.push(expected_index); - } - _ => { - return Err(anyhow!( - "cell effect verifier returned an incoherent result or findings set for action {expected_index}" - )); - } - } - } - Ok(rejected) -} - -fn cell_effect_verifier_schema(action_count: usize) -> Result { - if action_count == 0 { - return Err(anyhow!( - "cell effect verifier schema requires at least one action" - )); - } - let mut schema = serde_json::to_value(schema_for!(CellEffectVerification))?; - let verdicts = schema - .pointer_mut("/properties/verdicts") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("cell effect verifier schema has no verdicts property"))?; - verdicts.insert("minItems".into(), serde_json::json!(action_count)); - verdicts.insert("maxItems".into(), serde_json::json!(action_count)); - let verdict = schema - .pointer_mut("/$defs/CellActionEffectVerdict") - .ok_or_else(|| anyhow!("cell effect verifier schema has no verdict definition"))?; - let finding_schema = serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["mismatch_kind", "repair_guidance"], - "properties":{ - "mismatch_kind":{ - "enum":[ - "subject_swap", - "effect_omission", - "effect_reversal", - "target_substitution", - "invented_outcome", - "wrong_effect_kind" - ] - }, - "repair_guidance":{ - "type":"string", - "minLength":1, - "maxLength":240 - } - } - }); - *verdict = serde_json::json!({ - "oneOf":[ - { - "type":"object", - "additionalProperties":false, - "required":["action_index", "result", "findings"], - "properties":{ - "action_index":{ - "type":"integer", - "minimum":0, - "maximum":action_count - 1 - }, - "result":{"const":"match"}, - "findings":{ - "type":"array", - "maxItems":0, - "items":finding_schema.clone() - } - } - }, - { - "type":"object", - "additionalProperties":false, - "required":["action_index", "result", "findings"], - "properties":{ - "action_index":{ - "type":"integer", - "minimum":0, - "maximum":action_count - 1 - }, - "result":{"const":"mismatch"}, - "findings":{ - "type":"array", - "minItems":1, - "maxItems":6, - "items":finding_schema - } - } - } - ] - }); - Ok(schema) -} - -pub fn cell_effect_verification_binding( - cell_snapshot_binding: &str, - actions: &[crate::domain::CellActionProposal], -) -> Result { - let payload = rmp_serde::to_vec_named(actions)?; - Ok(format!( - "{cell_snapshot_binding}:effects:sha256:{:x}", - Sha256::digest(payload) - )) -} - -fn bind_cell_appraisal( - slice: &PermittedCellSlice, - active_subject_ids: &BTreeSet, - proposal: CellAppraisalProposal, -) -> Result { - let actions = proposal - .actions - .into_iter() - .map(|candidate| { - let CellActionCandidate { - subject_id, - intent, - intended_effect, - priority, - state_references, - public_channels, - effects: candidate_effects, - } = candidate; - let member_id = if candidate_effects.member_activities.is_some() - || candidate_effects.member_migration.is_some() - { - Some( - slice - .member_exceptions - .iter() - .find(|member| member.subject_id == subject_id) - .map(|member| member.member_id.clone()) - .ok_or_else(|| { - anyhow!( - "member effect subject {} is not a selected member exception", - subject_id - ) - })?, - ) - } else { - None - }; - let mut effects = Vec::with_capacity(4); - if let Some(effect) = candidate_effects.actor_move { - effects.push(crate::domain::StrategicCellEffect::ActorMove { - actor_id: subject_id.clone(), - destination_id: effect.destination_id, - }); - } - if let Some(effect) = candidate_effects.gestalt_migration { - effects.push(crate::domain::StrategicCellEffect::GestaltMigration { - destination_gestalt_id: effect.destination_gestalt_id, - }); - } - if let Some(effect) = candidate_effects.member_migration { - effects.push(crate::domain::StrategicCellEffect::MemberMigration { - destination_gestalt_id: effect.destination_gestalt_id, - }); - } - if let Some(effect) = candidate_effects.institution { - effects.push(crate::domain::StrategicCellEffect::Institution { - institution_id: subject_id.clone(), - posture: effect.posture, - location_ids: effect.location_ids, - }); - } - if let Some(effect) = candidate_effects.gestalt_pressure { - effects.push(crate::domain::StrategicCellEffect::Gestalt { - gestalt_id: subject_id.clone(), - pressure_additions: effect.pressure_additions, - pressure_resolutions: effect.pressure_resolutions, - }); - } - if let Some(activities) = candidate_effects.gestalt_activities { - for (activity, effect) in activities.into_effects() { - effects.push(crate::domain::StrategicCellEffect::GestaltActivity { - gestalt_id: subject_id.clone(), - activity, - target_subject_ids: effect.target_subject_ids, - location_ids: effect.location_ids, - }); - } - } - if let Some(activities) = candidate_effects.actor_activities { - for (activity, effect) in activities.into_effects() { - effects.push(crate::domain::StrategicCellEffect::ActorActivity { - actor_id: subject_id.clone(), - activity, - target_subject_ids: effect.target_subject_ids, - location_ids: effect.location_ids, - }); - } - } - if let Some(activities) = candidate_effects.member_activities { - for (activity, effect) in activities.into_effects() { - effects.push(crate::domain::StrategicCellEffect::MemberActivity { - member_id: member_id - .clone() - .expect("member effect resolved an exact member"), - activity, - target_subject_ids: effect.target_subject_ids, - location_ids: effect.location_ids, - }); - } - } - if effects.is_empty() || effects.len() > 4 { - return Err(anyhow!( - "action for subject {} requires one to four exact effects", - subject_id - )); - } - Ok(crate::domain::CellActionProposal { - subject_id, - intent, - intended_effect, - priority, - state_references, - public_channels, - effects, - }) - }) - .collect::>>()?; - Ok(crate::domain::CellAppraisal { - schema: "ghostlight.cell_appraisal.v1".into(), - cell_id: slice.cell_id.clone(), - world_revision: slice.world_revision, - resolution_epoch: slice.resolution_epoch, - considered_subject_ids: active_subject_ids.clone(), - actions, - inactions: proposal.inactions, - }) -} - -fn decode_cell_appraisal_proposal( - cell_id: &str, - value: serde_json::Value, -) -> Result { - let decisions = value - .get("decisions") - .and_then(serde_json::Value::as_object) - .ok_or_else(|| anyhow!("cell interpreter proposal has no exact decision map"))?; - let mut actions = Vec::new(); - let mut inactions = Vec::new(); - for (subject_id, decision) in decisions { - let decision = decision - .as_object() - .ok_or_else(|| anyhow!("decision for subject {subject_id} is not an object"))?; - match ( - decision.get("action"), - decision.get("inaction"), - decision.get("undecided"), - ) { - (Some(action), None, None) => { - let action: CellActionCandidate = serde_json::from_value(action.clone())?; - if action.subject_id != *subject_id { - return Err(anyhow!( - "decision key {subject_id} does not match action owner {}", - action.subject_id - )); - } - actions.push(action); - } - (None, Some(inaction), None) => { - let inaction: crate::domain::CellInaction = - serde_json::from_value(inaction.clone())?; - if inaction.subject_id != *subject_id { - return Err(anyhow!( - "decision key {subject_id} does not match inaction owner {}", - inaction.subject_id - )); - } - inactions.push(inaction); - } - (None, None, Some(_)) => { - return Err(anyhow!( - "cell {cell_id} decision for subject {subject_id} remained undecided" - )); - } - _ => { - return Err(anyhow!( - "decision for subject {subject_id} must contain exactly one decision kind" - )); - } - } - } - Ok(CellAppraisalProposal { actions, inactions }) -} - -fn validate_cell_appraisal( - slice: &PermittedCellSlice, - appraisal: &crate::domain::CellAppraisal, -) -> Result<()> { - if appraisal.schema != "ghostlight.cell_appraisal.v1" - || appraisal.cell_id != slice.cell_id - || appraisal.world_revision != slice.world_revision - || appraisal.resolution_epoch != slice.resolution_epoch - { - return Err(anyhow!( - "appraisal has a stale or incomplete runtime binding" - )); - } - if appraisal.actions.is_empty() && appraisal.inactions.is_empty() { - return Err(anyhow!( - "an appraisal with no actions requires one exact attributed inaction" - )); - } - let permitted_subject_ids = slice - .constituents - .iter() - .map(|subject| subject.subject_id.as_str()) - .chain( - slice - .member_exceptions - .iter() - .map(|member| member.subject_id.as_str()), - ) - .collect::>(); - if appraisal.considered_subject_ids.is_empty() - || appraisal.considered_subject_ids.len() > slice.max_actions - || appraisal - .considered_subject_ids - .iter() - .any(|subject_id| !permitted_subject_ids.contains(subject_id.as_str())) - { - return Err(anyhow!( - "appraisal considered subjects are empty, over quota, or outside this cell's exact decision owners" - )); - } - let mut action_subject_ids = BTreeSet::new(); - for action in &appraisal.actions { - if !appraisal - .considered_subject_ids - .contains(&action.subject_id) - { - return Err(anyhow!( - "action subject {} was not an exact projected decision owner", - action.subject_id - )); - } - if !action_subject_ids.insert(action.subject_id.as_str()) { - return Err(anyhow!( - "subject {} has duplicate strategic actions; combine every chosen movement and activity means into one composed action", - action.subject_id - )); - } - } - let mut inaction_subject_ids = BTreeSet::new(); - for inaction in &appraisal.inactions { - if inaction.reason.trim().is_empty() { - return Err(anyhow!( - "inaction for subject {} requires a non-empty reason", - inaction.subject_id - )); - } - if inaction.reason.chars().count() > 240 { - return Err(anyhow!( - "inaction reason for subject {} is {} characters but permits at most 240", - inaction.subject_id, - inaction.reason.chars().count() - )); - } - if !permitted_subject_ids.contains(inaction.subject_id.as_str()) { - return Err(anyhow!( - "inaction subject {} is outside this cell's exact constituents and member exceptions", - inaction.subject_id - )); - } - if !appraisal - .considered_subject_ids - .contains(&inaction.subject_id) - { - return Err(anyhow!( - "inaction subject {} was not an exact projected decision owner", - inaction.subject_id - )); - } - if action_subject_ids.contains(inaction.subject_id.as_str()) { - return Err(anyhow!( - "subject {} appears in both actions and inactions; retain exactly one of those decisions", - inaction.subject_id - )); - } - if !inaction_subject_ids.insert(inaction.subject_id.as_str()) { - return Err(anyhow!( - "subject {} has duplicate attributed inactions; retain exactly one", - inaction.subject_id - )); - } - } - for action in &appraisal.actions { - validate_cell_action(slice, action)?; - } - let decided_subject_ids = action_subject_ids - .into_iter() - .chain(inaction_subject_ids) - .collect::>(); - let missing = appraisal - .considered_subject_ids - .iter() - .map(String::as_str) - .filter(|subject_id| !decided_subject_ids.contains(subject_id)) - .collect::>(); - if !missing.is_empty() { - return Err(anyhow!( - "appraisal omitted explicit strategic decisions for projected subjects {missing:?}" - )); - } - Ok(()) -} - -fn validate_cell_action( - slice: &PermittedCellSlice, - action: &crate::domain::CellActionProposal, -) -> Result<()> { - if action.intent.trim().is_empty() || action.intended_effect.trim().is_empty() { - return Err(anyhow!( - "action for subject {} requires non-empty intent and intended_effect", - action.subject_id - )); - } - let required_causal_references = slice - .causal_follow_through - .iter() - .filter(|focus| focus.responder_subject_id == action.subject_id) - .map(|focus| focus.anchor_reference.as_str()) - .collect::>(); - if !required_causal_references.is_empty() - && action - .state_references - .iter() - .all(|reference| !required_causal_references.contains(reference.as_str())) - { - return Err(anyhow!( - "action for causal responder {} omits its exact scheduler anchor {:?}", - action.subject_id, - required_causal_references - )); - } - if let Some(subject) = slice - .constituents - .iter() - .find(|value| value.subject_id == action.subject_id) - { - validate_action_permissions( - action, - &subject.permitted_state_references, - &subject.information_channels, - )?; - validate_effect_bundle(&action.effects)?; - let prospective_location = action.effects.iter().find_map(|effect| match effect { - crate::domain::StrategicCellEffect::ActorMove { destination_id, .. } => { - Some(destination_id.as_str()) - } - crate::domain::StrategicCellEffect::GestaltMigration { - destination_gestalt_id, - } => subject - .migration_destinations - .get(destination_gestalt_id) - .map(|destination| destination.location_id.as_str()), - _ => None, - }); - for effect in &action.effects { - validate_constituent_effect(subject, effect, prospective_location)?; - } - return Ok(()); - } - let Some(member) = slice - .member_exceptions - .iter() - .find(|value| value.subject_id == action.subject_id) - else { - return Err(anyhow!("action is attributed outside the cell")); - }; - validate_action_permissions( - action, - &member.permitted_state_references, - &member.information_channels, - )?; - validate_effect_bundle(&action.effects)?; - let prospective_location = action.effects.iter().find_map(|effect| match effect { - crate::domain::StrategicCellEffect::MemberMigration { - destination_gestalt_id, - } => member - .migration_destinations - .get(destination_gestalt_id) - .map(|destination| destination.location_id.as_str()), - _ => None, - }); - for effect in &action.effects { - match effect { - crate::domain::StrategicCellEffect::MemberActivity { - member_id, - activity, - target_subject_ids, - location_ids, - } => { - let unique_targets = target_subject_ids.iter().collect::>(); - let needs_target = !activity.allows_targetless_local_attempt(); - let activity_location = location_ids.first().map(String::as_str); - if member_id != &member.member_id - || target_subject_ids.len() > 4 - || unique_targets.len() != target_subject_ids.len() - || target_subject_ids - .iter() - .any(|target| !member.activity_targets.contains_key(target)) - || (needs_target && target_subject_ids.is_empty()) - || location_ids.len() != 1 - || (activity_location != Some(member.source_location_id.as_str()) - && activity_location != prospective_location) - { - return Err(anyhow!( - "named member {} proposed {:?} toward {:?} at {:?}; exact allowed targets are {:?}, current location is {}, and a paired migration may establish {:?}", - member.member_id, - activity, - target_subject_ids, - location_ids, - member.activity_targets.keys().collect::>(), - member.source_location_id, - prospective_location - )); - } - } - crate::domain::StrategicCellEffect::MemberMigration { - destination_gestalt_id, - } if member - .migration_destinations - .contains_key(destination_gestalt_id) => {} - _ => { - return Err(anyhow!( - "action for named member {} exceeds exact personal authority; effects={:?}; allowed destination gestalt IDs={:?}", - member.member_id, - action.effects, - member.migration_destinations.keys().collect::>() - )); - } - } - } - Ok(()) -} - -fn validate_effect_bundle(effects: &[crate::domain::StrategicCellEffect]) -> Result<()> { - if effects.is_empty() || effects.len() > 4 { - return Err(anyhow!( - "a strategic action requires one to four exact effects" - )); - } - let mut lanes = BTreeSet::new(); - for (index, effect) in effects.iter().enumerate() { - if effects[..index].contains(effect) { - return Err(anyhow!( - "a strategic action cannot repeat an exact typed effect" - )); - } - let lane = match effect { - crate::domain::StrategicCellEffect::GestaltActivity { .. } - | crate::domain::StrategicCellEffect::ActorActivity { .. } - | crate::domain::StrategicCellEffect::MemberActivity { .. } => None, - _ => Some(effect.lane()), - }; - if lane.is_some_and(|lane| !lanes.insert(lane)) { - return Err(anyhow!( - "one strategic action may use each scalar effect lane at most once" - )); - } - } - Ok(()) -} - -fn validate_active_decision_owners( - active_subject_ids: &BTreeSet, - appraisal: &crate::domain::CellAppraisal, -) -> Result<()> { - if appraisal.considered_subject_ids != *active_subject_ids { - return Err(anyhow!( - "appraisal decision owners do not match the exact projected perspectives" - )); - } - let inactive = appraisal - .actions - .iter() - .map(|action| action.subject_id.as_str()) - .chain( - appraisal - .inactions - .iter() - .map(|inaction| inaction.subject_id.as_str()), - ) - .filter(|subject_id| !active_subject_ids.contains(*subject_id)) - .collect::>(); - if !inactive.is_empty() { - return Err(anyhow!( - "appraisal assigned decisions to inactive unprojected subjects {inactive:?}" - )); - } - Ok(()) -} - -fn validate_constituent_effect( - subject: &CellConstituentSlice, - effect: &crate::domain::StrategicCellEffect, - prospective_location: Option<&str>, -) -> Result<()> { - match effect { - crate::domain::StrategicCellEffect::Institution { - institution_id, - posture, - location_ids, - } => { - if subject.subject_kind != crate::domain::AgencySubjectKind::Institution - || institution_id != &subject.subject_id - { - return Err(anyhow!( - "subject {} has kind {:?} and may not emit an institution effect for {}", - subject.subject_id, - subject.subject_kind, - institution_id - )); - } - if location_ids - .iter() - .any(|location| !subject.location_ids.contains(location)) - { - return Err(anyhow!( - "institution {} used locations {:?}; exact allowed locations are {:?}", - subject.subject_id, - location_ids, - subject.location_ids - )); - } - let current = subject.current_posture.as_deref().ok_or_else(|| { - anyhow!( - "institution {} is missing its exact current posture", - subject.subject_id - ) - })?; - if posture.trim().is_empty() { - return Err(anyhow!( - "institution {} proposed an empty posture", - subject.subject_id - )); - } - if posture.chars().count() > crate::domain::MAX_POSTURE_CHARS { - return Err(anyhow!( - "institution {} proposed a posture of {} characters; the exact maximum is {}", - subject.subject_id, - posture.chars().count(), - crate::domain::MAX_POSTURE_CHARS - )); - } - if current.trim().eq_ignore_ascii_case(posture.trim()) { - return Err(anyhow!( - "institution {} proposed posture {:?}, but its exact current posture is {:?}; emit a specific different commitment or choose inaction", - subject.subject_id, - posture, - current - )); - } - } - crate::domain::StrategicCellEffect::Gestalt { - gestalt_id, - pressure_additions, - pressure_resolutions, - } => { - if subject.subject_kind != crate::domain::AgencySubjectKind::Gestalt - || gestalt_id != &subject.subject_id - { - return Err(anyhow!( - "subject {} has kind {:?} and may not emit a gestalt effect for {}", - subject.subject_id, - subject.subject_kind, - gestalt_id - )); - } - crate::resolution::validate_gestalt_pressure_transition( - &subject.pressures, - pressure_additions, - pressure_resolutions, - ) - .map_err(|error| { - anyhow!( - "gestalt {} proposed additions {:?} and resolutions {:?} against exact current pressures {:?}: {}", - subject.subject_id, - pressure_additions, - pressure_resolutions, - subject.pressures, - error - ) - })?; - } - crate::domain::StrategicCellEffect::GestaltActivity { - gestalt_id, - activity, - target_subject_ids, - location_ids, - } => { - let unique_targets = target_subject_ids.iter().collect::>(); - let unique_locations = location_ids.iter().collect::>(); - let needs_target = activity.requires_explicit_target_for_gestalt(); - if needs_target && target_subject_ids.is_empty() { - return Err(anyhow!( - "gestalt {} activity {:?} requires one or more exact target IDs; no anonymous or unsupplied target can be encoded. Remove the action unless the Persona explicitly attempted one of {:?}", - subject.subject_id, - activity, - subject.activity_targets.keys().collect::>() - )); - } - if subject.subject_kind != crate::domain::AgencySubjectKind::Gestalt - || gestalt_id != &subject.subject_id - || target_subject_ids.len() > 4 - || unique_targets.len() != target_subject_ids.len() - || target_subject_ids - .iter() - .any(|target| !subject.activity_targets.contains_key(target)) - || location_ids.len() > 4 - || unique_locations.len() != location_ids.len() - || location_ids.iter().any(|location| { - !subject.location_ids.contains(location) - && Some(location.as_str()) != prospective_location - }) - { - return Err(anyhow!( - "gestalt {} proposed {:?} toward {:?} at {:?}; exact allowed targets (choose at most four unique IDs) are {:?} and exact locations (choose at most four unique IDs) are {:?}", - subject.subject_id, - activity, - target_subject_ids, - location_ids, - subject.activity_targets.keys().collect::>(), - subject.location_ids - )); - } - } - crate::domain::StrategicCellEffect::GestaltMigration { - destination_gestalt_id, - } => { - if subject.subject_kind != crate::domain::AgencySubjectKind::Gestalt - || !subject - .migration_destinations - .contains_key(destination_gestalt_id) - { - return Err(anyhow!( - "gestalt {} may not migrate to {}; exact allowed population destinations are {:?}", - subject.subject_id, - destination_gestalt_id, - subject.migration_destinations.keys().collect::>() - )); - } - } - crate::domain::StrategicCellEffect::ActorMove { - actor_id, - destination_id, - } => { - if subject.subject_kind != crate::domain::AgencySubjectKind::Actor - || actor_id != &subject.subject_id - || !subject.reachable_destinations.contains_key(destination_id) - { - return Err(anyhow!( - "subject {} has kind {:?}; actor movement requested for {} to {:?}, while exact reachable destinations are {:?}", - subject.subject_id, - subject.subject_kind, - actor_id, - destination_id, - subject.reachable_destinations - )); - } - } - crate::domain::StrategicCellEffect::ActorActivity { - actor_id, - activity, - target_subject_ids, - location_ids, - } => { - let unique_targets = target_subject_ids.iter().collect::>(); - let needs_target = !activity.allows_targetless_local_attempt(); - if subject.subject_kind != crate::domain::AgencySubjectKind::Actor - || actor_id != &subject.subject_id - || target_subject_ids.len() > 4 - || unique_targets.len() != target_subject_ids.len() - || target_subject_ids - .iter() - .any(|target| !subject.activity_targets.contains_key(target)) - || (needs_target && target_subject_ids.is_empty()) - || location_ids.len() != 1 - || (!subject.location_ids.contains(&location_ids[0]) - && Some(location_ids[0].as_str()) != prospective_location) - { - return Err(anyhow!( - "actor {} proposed {:?} toward {:?} at {:?}; exact allowed targets are {:?} and exact locations are {:?}", - subject.subject_id, - activity, - target_subject_ids, - location_ids, - subject.activity_targets.keys().collect::>(), - subject.location_ids - )); - } - } - crate::domain::StrategicCellEffect::MemberMigration { .. } => { - return Err(anyhow!( - "constituent {} is not a named member and may not emit member_migration", - subject.subject_id - )); - } - crate::domain::StrategicCellEffect::MemberActivity { .. } => { - return Err(anyhow!( - "constituent {} is not a named member and may not emit member_activity", - subject.subject_id - )); - } - } - Ok(()) -} - -fn validate_action_permissions( - action: &crate::domain::CellActionProposal, - permitted_state_references: &BTreeSet, - information_channels: &BTreeSet, -) -> Result<()> { - let invalid_references = action - .state_references - .iter() - .filter(|reference| !permitted_state_references.contains(*reference)) - .collect::>(); - let invalid_channels = action - .public_channels - .iter() - .filter(|channel| !information_channels.contains(*channel)) - .collect::>(); - if !invalid_references.is_empty() || !invalid_channels.is_empty() { - return Err(anyhow!( - "action for subject {} borrowed forbidden state references {:?} or information channels {:?}", - action.subject_id, - invalid_references, - invalid_channels - )); - } - Ok(()) -} - -fn constrain_cell_proposal_schema( - schema: &mut serde_json::Value, - slice: &PermittedCellSlice, - active_subject_ids: &BTreeSet, -) -> Result<()> { - let action_candidate = schema - .pointer("/$defs/CellActionCandidate") - .cloned() - .ok_or_else(|| anyhow!("cell appraisal schema has no action candidate"))?; - let exact_subject_actions = slice - .constituents - .iter() - .filter(|subject| active_subject_ids.contains(&subject.subject_id)) - .map(|subject| { - Ok(( - subject.subject_id.clone(), - exact_cell_action_schema( - action_candidate.clone(), - &subject.subject_id, - exact_constituent_effect_bundle_schema(subject), - &subject.permitted_state_references, - &subject.information_channels, - )?, - )) - }) - .chain( - slice - .member_exceptions - .iter() - .filter(|member| active_subject_ids.contains(&member.subject_id)) - .map(|member| { - Ok(( - member.subject_id.clone(), - exact_cell_action_schema( - action_candidate.clone(), - &member.subject_id, - exact_member_effect_bundle_schema(member), - &member.permitted_state_references, - &member.information_channels, - )?, - )) - }), - ) - .collect::>>()?; - if exact_subject_actions.is_empty() { - return Err(anyhow!( - "cell proposal schema requires at least one exact decision owner" - )); - } - if exact_subject_actions.len() > slice.max_actions { - return Err(anyhow!("cell proposal schema exceeds its decision budget")); - } - let mut decision_properties = serde_json::Map::new(); - let mut required_subjects = Vec::new(); - for (subject_id, action_schema) in exact_subject_actions { - required_subjects.push(subject_id.clone()); - decision_properties.insert( - subject_id.clone(), - serde_json::json!({ - "anyOf":[ - { - "type":"object", - "additionalProperties":false, - "required":["action"], - "properties":{"action":action_schema} - }, - { - "type":"object", - "additionalProperties":false, - "required":["inaction"], - "properties":{"inaction":{ - "type":"object", - "additionalProperties":false, - "required":["subject_id","reason"], - "properties":{ - "subject_id":{"type":"string","const":subject_id}, - "reason":{"type":"string","minLength":1,"maxLength":240} - } - }} - }, - { - "type":"object", - "additionalProperties":false, - "required":["undecided"], - "properties":{"undecided":{ - "type":"object", - "additionalProperties":false, - "required":["reason"], - "properties":{"reason":{"type":"string","minLength":1,"maxLength":240}} - }} - } - ] - }), - ); - } - *schema = serde_json::json!({ - "$schema":"https://json-schema.org/draft/2020-12/schema", - "type":"object", - "additionalProperties":false, - "required":["decisions"], - "properties":{ - "decisions":{ - "type":"object", - "additionalProperties":false, - "required":required_subjects, - "properties":decision_properties - } - } - }); - Ok(()) -} - -enum CellInterpreterSchemaState<'a> { - Initial, - Repair(&'a BTreeSet), -} - -fn cell_interpreter_agent_schema( - appraisal_schema: &serde_json::Value, - state: CellInterpreterSchemaState<'_>, -) -> Result { - let decisions_schema = appraisal_schema - .pointer("/properties/decisions") - .cloned() - .ok_or_else(|| anyhow!("cell appraisal schema has no exact decisions map"))?; - let decision_properties = decisions_schema - .get("properties") - .and_then(serde_json::Value::as_object) - .ok_or_else(|| anyhow!("cell appraisal schema has no exact decision owners"))?; - let commands = match state { - CellInterpreterSchemaState::Initial => vec![serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["kind","decisions"], - "properties":{ - "kind":{"const":"submit"}, - "decisions":decisions_schema - } - })], - CellInterpreterSchemaState::Repair(repair_subject_ids) => { - if repair_subject_ids.is_empty() { - return Err(anyhow!("Interpreter repair schema requires a subject")); - } - repair_subject_ids - .iter() - .map(|subject_id| { - let decision_schema = decision_properties.get(subject_id).ok_or_else(|| { - anyhow!("Interpreter repair subject {subject_id} has no decision schema") - })?; - Ok(serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["kind","subject_id","decision"], - "properties":{ - "kind":{"const":"upsert_decision"}, - "subject_id":{"const":subject_id}, - "decision":decision_schema - } - })) - }) - .collect::>>()? - } - }; - Ok(serde_json::json!({ - "$schema":"https://json-schema.org/draft/2020-12/schema", - "type":"object", - "additionalProperties":false, - "required":["command"], - "properties":{ - "command":{"oneOf":commands} - } - })) -} - -fn exact_cell_action_schema( - mut action_schema: serde_json::Value, - subject_id: &str, - effect_schema: serde_json::Value, - permitted_state_references: &BTreeSet, - information_channels: &BTreeSet, -) -> Result { - let properties = action_schema - .pointer_mut("/properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("cell action candidate schema has no properties"))?; - properties.insert( - "subject_id".into(), - serde_json::json!({"type":"string","const":subject_id}), - ); - properties.insert( - "priority".into(), - serde_json::json!({"type":"integer","minimum":0,"maximum":100}), - ); - properties.insert( - "state_references".into(), - exact_string_array_schema( - permitted_state_references, - 0, - permitted_state_references.len(), - ), - ); - properties.insert( - "public_channels".into(), - exact_string_array_schema(information_channels, 0, 8), - ); - properties.insert("effects".into(), effect_schema); - Ok(action_schema) -} - -fn exact_constituent_effect_bundle_schema(subject: &CellConstituentSlice) -> serde_json::Value { - let activity_target_ids = subject - .activity_targets - .keys() - .cloned() - .collect::>(); - let activity_location_ids = subject - .location_ids - .iter() - .cloned() - .chain(subject.reachable_destinations.keys().cloned()) - .chain( - subject - .migration_destinations - .values() - .map(|destination| destination.location_id.clone()), - ) - .collect::>(); - let mut properties = null_cell_effect_lane_properties(); - match subject.subject_kind { - crate::domain::AgencySubjectKind::Institution => { - properties.insert( - "institution".into(), - nullable_effect_schema(serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["posture","location_ids"], - "properties":{ - "posture":{"type":"string","minLength":1,"maxLength":crate::domain::MAX_POSTURE_CHARS}, - "location_ids":exact_string_array_schema(&subject.location_ids, 0, 4) - } - })), - ); - } - crate::domain::AgencySubjectKind::Gestalt => { - properties.insert( - "gestalt_pressure".into(), - nullable_effect_schema(serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["pressure_additions","pressure_resolutions"], - "properties":{ - "pressure_additions":{"type":"array","uniqueItems":true,"maxItems":4,"items":{"type":"string"}}, - "pressure_resolutions":exact_string_slice_array_schema(&subject.pressures, 0, 4) - } - })), - ); - properties.insert( - "gestalt_activities".into(), - exact_activity_effects_schema( - &activity_target_ids, - &activity_location_ids, - 0, - true, - ), - ); - if !subject.migration_destinations.is_empty() { - properties.insert( - "gestalt_migration".into(), - nullable_effect_schema(exact_migration_effect_schema( - subject.migration_destinations.keys(), - )), - ); - } - } - crate::domain::AgencySubjectKind::Actor => { - if !subject.reachable_destinations.is_empty() { - properties.insert( - "actor_move".into(), - nullable_effect_schema(serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["destination_id"], - "properties":{"destination_id":{"type":"string","enum":subject.reachable_destinations.keys().collect::>()}} - })), - ); - } - properties.insert( - "actor_activities".into(), - exact_activity_effects_schema( - &activity_target_ids, - &activity_location_ids, - 1, - false, - ), - ); - } - } - serde_json::json!({ - "type":"object", - "additionalProperties":false, - "minProperties":1, - "properties":properties - }) -} - -fn exact_member_effect_bundle_schema(member: &CellMemberSlice) -> serde_json::Value { - let activity_target_ids = member - .activity_targets - .keys() - .cloned() - .collect::>(); - let activity_location_ids = std::iter::once(member.source_location_id.clone()) - .chain( - member - .migration_destinations - .values() - .map(|destination| destination.location_id.clone()), - ) - .collect::>(); - let mut properties = null_cell_effect_lane_properties(); - properties.insert( - "member_activities".into(), - exact_activity_effects_schema(&activity_target_ids, &activity_location_ids, 1, false), - ); - if !member.migration_destinations.is_empty() { - properties.insert( - "member_migration".into(), - nullable_effect_schema(exact_migration_effect_schema( - member.migration_destinations.keys(), - )), - ); - } - serde_json::json!({ - "type":"object", - "additionalProperties":false, - "minProperties":1, - "properties":properties - }) -} - -fn nullable_effect_schema(effect: serde_json::Value) -> serde_json::Value { - serde_json::json!({"anyOf":[effect,{"type":"null"}]}) -} - -fn null_cell_effect_lane_properties() -> serde_json::Map { - [ - "institution", - "gestalt_pressure", - "gestalt_activities", - "gestalt_migration", - "actor_move", - "actor_activities", - "member_activities", - "member_migration", - ] - .into_iter() - .map(|lane| (lane.to_owned(), serde_json::json!({"type":"null"}))) - .collect() -} - -fn exact_migration_effect_schema<'a>( - destinations: impl Iterator, -) -> serde_json::Value { - serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["destination_gestalt_id"], - "properties":{ - "destination_gestalt_id":{"type":"string","enum":destinations.collect::>()} - } - }) -} - -fn exact_activity_scope_schema( - target_ids: &BTreeSet, - location_ids: &BTreeSet, - minimum_locations: usize, - minimum_targets: usize, -) -> serde_json::Value { - serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["target_subject_ids","location_ids"], - "properties":{ - "target_subject_ids":exact_string_array_schema(target_ids, minimum_targets, 4), - "location_ids":exact_string_array_schema(location_ids, minimum_locations, if minimum_locations == 1 { 1 } else { 4 }) - } - }) -} - -fn exact_activity_effects_schema( - target_ids: &BTreeSet, - location_ids: &BTreeSet, - minimum_locations: usize, - allow_internal_coordination: bool, -) -> serde_json::Value { - let local_scope = exact_activity_scope_schema(target_ids, location_ids, minimum_locations, 0); - let relational_scope = - exact_activity_scope_schema(target_ids, location_ids, minimum_locations, 1); - let repeated = |scope| { - nullable_effect_schema(serde_json::json!({ - "type":"array", - "minItems":1, - "maxItems":4, - "items":scope - })) - }; - let mut properties: serde_json::Map = serde_json::Map::from_iter([ - ("prepare".into(), repeated(local_scope.clone())), - ("investigate".into(), repeated(local_scope.clone())), - ("obstruct".into(), repeated(local_scope.clone())), - ("communicate".into(), repeated(local_scope.clone())), - ]); - if allow_internal_coordination { - properties.insert("coordinate".into(), repeated(local_scope)); - } else if !target_ids.is_empty() { - properties.insert("coordinate".into(), repeated(relational_scope.clone())); - } - if !target_ids.is_empty() { - properties.insert("recruit".into(), repeated(relational_scope.clone())); - properties.insert("trade".into(), repeated(relational_scope)); - } - serde_json::json!({ - "type":"object", - "additionalProperties":false, - "minProperties":1, - "properties":properties - }) -} - -fn exact_string_array_schema( - values: &BTreeSet, - min_items: usize, - max_items: usize, -) -> serde_json::Value { - if values.is_empty() { - serde_json::json!({ - "type":"array", - "minItems":min_items, - "maxItems":0, - "items":{"type":"string"} - }) - } else { - serde_json::json!({ - "type":"array", - "uniqueItems":true, - "minItems":min_items, - "maxItems":max_items, - "items":{"type":"string","enum":values} - }) - } -} - -fn exact_string_slice_array_schema( - values: &[String], - min_items: usize, - max_items: usize, -) -> serde_json::Value { - exact_string_array_schema(&values.iter().cloned().collect(), min_items, max_items) -} - -fn constrain_interpreter_schema( - schema: &mut serde_json::Value, - slice: &PermittedActorSlice, -) -> Result<()> { - let allowed_references = allowed_actor_references(slice); - let world_action = schema - .pointer_mut("/$defs/WorldActionProposal/properties") - .and_then(|value| value.as_object_mut()) - .ok_or_else(|| anyhow!("Persona proposal schema has no world action properties"))?; - world_action.insert( - "actor_id".into(), - serde_json::json!({"const":slice.actor_id}), - ); - world_action.insert( - "state_references".into(), - serde_json::json!({"type":"array","items":{"type":"string","enum":allowed_references}}), - ); - let relationship_updates = schema - .pointer_mut("/$defs/ActorStateDelta/properties/relationship_updates") - .and_then(|value| value.as_object_mut()) - .ok_or_else(|| anyhow!("Persona proposal schema has no relationship updates"))?; - relationship_updates.insert( - "propertyNames".into(), - serde_json::json!({"enum":slice.perceived_actors.keys().collect::>()}), - ); - let memories_add = schema - .pointer_mut("/$defs/ActorStateDelta/properties/memories_add") - .and_then(|value| value.as_object_mut()) - .ok_or_else(|| anyhow!("Persona proposal schema has no memory additions"))?; - memories_add.insert("maxItems".into(), serde_json::json!(0)); - let identity_adoption = schema - .pointer_mut("/$defs/ActorStateDelta/properties/identity_adoption") - .ok_or_else(|| anyhow!("Persona proposal schema has no identity adoption"))?; - *identity_adoption = - serde_json::json!({"type":["string","null"],"minLength":1,"maxLength":160}); - if matches!(slice.subject_kind, PersonaSubjectKind::CohesiveGestalt) { - for field in [ - "memories_add", - "conditions_add", - "conditions_remove", - "goals_add", - ] { - let value = schema - .pointer_mut(&format!("/$defs/ActorStateDelta/properties/{field}")) - .ok_or_else(|| anyhow!("Persona proposal schema has no {field}"))?; - *value = serde_json::json!({"type":"array","maxItems":0,"items":{"type":"string"}}); - } - *schema - .pointer_mut("/$defs/ActorStateDelta/properties/relationship_updates") - .ok_or_else(|| anyhow!("Persona proposal schema has no relationship updates"))? = - serde_json::json!({"type":"object","maxProperties":0,"additionalProperties":false}); - *schema - .pointer_mut("/$defs/ActorStateDelta/properties/identity_adoption") - .ok_or_else(|| anyhow!("Persona proposal schema has no identity adoption"))? = - serde_json::json!({"type":"null"}); - } - let root = schema - .as_object_mut() - .ok_or_else(|| anyhow!("Persona proposal schema is not an object"))?; - let properties = root - .get_mut("properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("Persona proposal schema has no root properties"))?; - properties.insert( - "speech".into(), - serde_json::json!({"type":["string","null"],"minLength":1,"maxLength":1000}), - ); - properties.insert( - "deliberate_silence".into(), - serde_json::json!({"type":"boolean"}), - ); - if matches!(slice.subject_kind, PersonaSubjectKind::CohesiveGestalt) { - properties.insert( - "world_actions".into(), - serde_json::json!({"type":"array","maxItems":0,"items":{"$ref":"#/$defs/WorldActionProposal"}}), - ); - } - root.entry("allOf") - .or_insert_with(|| serde_json::json!([])) - .as_array_mut() - .ok_or_else(|| anyhow!("Persona proposal schema allOf is not an array"))? - .push(serde_json::json!({ - "anyOf":[ - {"required":["speech"],"properties":{"speech":{"type":"string","minLength":1,"maxLength":1000}}}, - {"required":["speech","private_delta"],"properties":{ - "speech":{"type":"null"}, - "private_delta":{"properties":{"identity_adoption":{"type":"null"}}} - }} - ] - })); - if matches!( - slice.interaction_role, - ActorInteractionRole::DirectResponseExpected - ) { - root.entry("allOf") - .or_insert_with(|| serde_json::json!([])) - .as_array_mut() - .ok_or_else(|| anyhow!("Persona proposal schema allOf is not an array"))? - .push(serde_json::json!({ - "anyOf":[ - {"required":["speech"],"properties":{"speech":{"type":"string","minLength":1,"maxLength":1000}}}, - {"required":["deliberate_silence"],"properties":{"deliberate_silence":{"const":true}}} - ] - })); - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - domain::{ - AgencySubjectKind, SimulationCellMode, StrategicActivityKind, StrategicCellEffect, - }, - model::{FixtureModel, ModelStageRequest}, - }; - use std::sync::Mutex; - use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; - use tokio::sync::Barrier; - - #[test] - fn interpreter_composes_distinct_activity_means_but_rejects_duplicates() { - let first_activity = StrategicCellEffect::ActorActivity { - actor_id: "actor:director".into(), - activity: StrategicActivityKind::Investigate, - target_subject_ids: vec![], - location_ids: vec!["clinic".into()], - }; - let second_activity = StrategicCellEffect::ActorActivity { - actor_id: "actor:director".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["institution:garrison".into()], - location_ids: vec!["clinic".into()], - }; - let movement = StrategicCellEffect::ActorMove { - actor_id: "actor:director".into(), - destination_id: "garrison".into(), - }; - - assert!( - validate_effect_bundle(&[movement.clone(), first_activity.clone()]).is_ok(), - "different orthogonal lanes must remain composable" - ); - assert!( - validate_effect_bundle(&[first_activity.clone(), second_activity]).is_ok(), - "one strategic choice may preserve several distinct means" - ); - assert!( - validate_effect_bundle(&[first_activity.clone(), first_activity]) - .unwrap_err() - .to_string() - .contains("cannot repeat an exact typed effect") - ); - } - - struct CorrectingCellModel { - interpreter_calls: AtomicUsize, - saw_rejected_appraisal: AtomicBool, - } - - #[async_trait] - impl ModelPort for CorrectingCellModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - match request.stage.as_str() { - "cell_projector" => { - assert!( - request - .lived_stream - .contains("between 1 and 1 unique segments") - ); - assert!( - request - .lived_stream - .contains("Put detail_focus_subject_id first") - ); - Ok(serde_json::json!({ - "segments":[{ - "subject_id":"faction-06", - "narrative":"The public deadline is visible, and the mandate remains ours to review." - }] - }) - .to_string()) - } - "cell_persona" => { - assert!( - request - .lived_stream - .contains("At location forum: Faction Six.") - ); - assert!( - request - .lived_stream - .contains("Only these projected perspectives may speak, choose") - ); - Ok( - "Faction Six will publish a bounded position using its bulletin access." - .into(), - ) - } - "cell_interpreter" => { - let call = self.interpreter_calls.fetch_add(1, Ordering::SeqCst); - let action_schema = request - .output_schema - .as_ref() - .expect("Interpreter step has a tool-owned schema"); - let action_schema_text = serde_json::to_string(action_schema).unwrap(); - assert!( - request - .lived_stream - .contains("local communicate may likewise have no target") - ); - assert!( - request - .lived_stream - .contains("chooses to board, depart, travel, or join") - ); - assert!( - request.lived_stream.contains( - "Never substitute a containing population, related institution" - ) - ); - assert!(request.lived_stream.contains("unvoiced subject")); - assert!(request.lived_stream.contains("at most 160 characters")); - assert!(request.lived_stream.contains( - "Merely inspecting a handcart, regulator, record, route, patient" - )); - assert!(request.lived_stream.contains("is investigate, not prepare")); - if call == 0 { - assert!(action_schema_text.contains("submit")); - assert!(!action_schema_text.contains("upsert_decision")); - return Ok(serde_json::json!({ - "command":{ - "kind":"submit", - "decisions":{"faction-06":{"action":{ - "subject_id":"faction-06", - "intent":"continue weighing the position", - "intended_effect":"retain the posture already in force", - "priority":5, - "state_references":["institution:faction-06"], - "public_channels":["public bulletin"], - "effects":{"institution":{"posture":"weighing whether to publish a position","location_ids":["forum"]}} - }}} - } - }) - .to_string()); - } - let repeated = serde_json::json!({ - "command":{ - "kind":"upsert_decision", - "subject_id":"faction-06", - "decision":{"action":{ - "subject_id":"faction-06", - "intent":"continue weighing the position", - "intended_effect":"retain the posture already in force", - "priority":5, - "state_references":["institution:faction-06"], - "public_channels":["public bulletin"], - "effects":{"institution":{ - "posture":"weighing whether to publish a position", - "location_ids":["forum"] - }} - }} - } - }); - assert!( - jsonschema::validator_for(action_schema) - .unwrap() - .is_valid(&repeated), - "the correction schema must admit the exact rejected owner" - ); - assert!(!action_schema_text.contains("submit")); - assert!(action_schema_text.contains("upsert_decision")); - assert!(!action_schema_text.contains("inspect_draft")); - self.saw_rejected_appraisal.store( - request.lived_stream.contains("local_validation") - && request - .lived_stream - .contains("weighing whether to publish a position") - && request.lived_stream.contains("faction-06"), - Ordering::SeqCst, - ); - Ok(serde_json::json!({ - "command":{ - "kind":"upsert_decision", - "subject_id":"faction-06", - "decision":{"action":{ - "subject_id":"faction-06", - "intent":"publish a position", - "intended_effect":"state its bounded institutional posture", - "priority":5, - "state_references":["institution:faction-06"], - "public_channels":["public bulletin"], - "effects":{"institution":{"posture":"published a bounded position","location_ids":["forum"]}} - }} - } - }).to_string()) - } - "cell_effect_verifier" => { - assert!(request.lived_stream.contains("JSON object")); - assert!(request.lived_stream.contains("exact_subject_permission")); - assert!( - request - .lived_stream - .contains("\"reachable_destinations\":{}") - ); - assert!( - request - .lived_stream - .contains("targetless local communicate") - ); - assert!(request.lived_stream.contains("incidental walking")); - assert!( - request - .lived_stream - .contains("reject member_activity that reduces that commitment") - ); - Ok(serde_json::json!({ - "verdicts":[{ - "action_index":0, - "result":"match", - "findings":[] - }] - }) - .to_string()) - } - stage => Err(anyhow!("unexpected fixture stage {stage}")), - } - } - - fn provider(&self) -> &'static str { - "correcting-cell-fixture" - } - } - - fn fixture_cell_slice() -> PermittedCellSlice { - PermittedCellSlice { - cell_id: "cell:test".into(), - mode: SimulationCellMode::Arena, - world_revision: 4, - resolution_epoch: 2, - snapshot_binding: "campaign:4:2".into(), - constituents: vec![CellConstituentSlice { - subject_id: "faction-06".into(), - subject_kind: AgencySubjectKind::Institution, - name: "Faction Six".into(), - collective_authority_id: None, - location_ids: BTreeSet::from(["forum".into()]), - knowledge: BTreeSet::from(["the public deadline".into()]), - capabilities: BTreeSet::new(), - resources: BTreeSet::from(["bulletin access".into()]), - information_channels: BTreeSet::from(["public bulletin".into()]), - permitted_state_references: BTreeSet::from(["institution:faction-06".into()]), - reachable_destinations: BTreeMap::new(), - migration_destinations: BTreeMap::new(), - activity_targets: BTreeMap::new(), - goals: vec!["publish a position".into()], - relationships: BTreeMap::new(), - memories: vec![], - current_posture: Some("weighing whether to publish a position".into()), - pressures: vec!["the vote is near".into()], - }], - member_exceptions: vec![], - shared_knowledge: BTreeSet::new(), - shared_capabilities: BTreeSet::new(), - perceived_events: vec![CellPerceivedEventSlice { - event_id: "event:vote".into(), - summary: "The final vote is public.".into(), - perceived_by_subject_ids: BTreeSet::from(["house-a".into(), "house-b".into()]), - }], - causal_follow_through: vec![], - world_clock_pressure: vec!["vote 5/6".into()], - canonical_locations: BTreeMap::from([("forum".into(), "Forum".into())]), - detail_focus_subject_id: Some("faction-06".into()), - decision_owner_ids: BTreeSet::from(["faction-06".into()]), - max_actions: 1, - source_receipt_ids: vec![], - } - } - - struct MissingDecisionRetryModel { - projector_calls: AtomicUsize, - persona_calls: AtomicUsize, - interpreter_calls: AtomicUsize, - saw_retry_guidance: AtomicBool, - request_sources: Mutex)>>, - } - - #[async_trait] - impl ModelPort for MissingDecisionRetryModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.request_sources - .lock() - .unwrap() - .push((request.stage.clone(), request.source_receipt_ids.clone())); - match request.stage.as_str() { - "cell_projector" => { - self.projector_calls.fetch_add(1, Ordering::SeqCst); - Ok(serde_json::json!({ - "segments":[{ - "subject_id":"faction-06", - "narrative":"The deadline is visible, but the institution has not yet chosen a new course." - }] - }) - .to_string()) - } - "cell_persona" => { - let call = self.persona_calls.fetch_add(1, Ordering::SeqCst); - if call == 0 { - return Ok( - "Faction Six weighs the deadline and its existing posture.".into() - ); - } - self.saw_retry_guidance.store( - request - .lived_stream - .contains("previous response supplied no explicit strategic decision"), - Ordering::SeqCst, - ); - Ok("Faction Six explicitly chooses to hold its existing posture for this horizon.".into()) - } - "cell_interpreter" => { - let call = self.interpreter_calls.fetch_add(1, Ordering::SeqCst); - if call == 0 { - return Ok(serde_json::json!({ - "command":{ - "kind":"submit", - "decisions":{"faction-06":{"undecided":{ - "reason":"The Persona supplied no explicit action or hold." - }}} - } - }) - .to_string()); - } - Ok(serde_json::json!({ - "command":{ - "kind":"submit", - "decisions":{"faction-06":{"inaction":{ - "subject_id":"faction-06", - "reason":"Faction Six explicitly holds its existing posture for this horizon." - }}} - } - }) - .to_string()) - } - stage => Err(anyhow!("unexpected fixture stage {stage}")), - } - } - - fn provider(&self) -> &'static str { - "missing-decision-retry-fixture" - } - } - - #[tokio::test] - async fn missing_persona_decision_retries_the_lived_turn_not_the_interpreter_invention() { - let model = Arc::new(MissingDecisionRetryModel { - projector_calls: AtomicUsize::new(0), - persona_calls: AtomicUsize::new(0), - interpreter_calls: AtomicUsize::new(0), - saw_retry_guidance: AtomicBool::new(false), - request_sources: Mutex::new(Vec::new()), - }); - let engine = CellProjectionEngine { - model: model.clone(), - permit: Arc::new(AllowAllPermit), - projector_model: "flash".into(), - persona_model: "flash".into(), - interpreter_model: "flash".into(), - campaign_contract: None, - aggregate_boundaries: vec![], - }; - - let output = engine.execute(fixture_cell_slice()).await.unwrap(); - - assert_eq!(model.projector_calls.load(Ordering::SeqCst), 1); - assert_eq!(model.persona_calls.load(Ordering::SeqCst), 2); - assert_eq!(model.interpreter_calls.load(Ordering::SeqCst), 2); - assert!(model.saw_retry_guidance.load(Ordering::SeqCst)); - assert!(output.appraisal.actions.is_empty()); - assert_eq!(output.appraisal.inactions.len(), 1); - assert_eq!(output.appraisal.inactions[0].subject_id, "faction-06"); - assert_eq!(output.stage_receipts.len(), 5); - assert!( - output - .stage_receipts - .iter() - .all(|receipt| receipt.validation_result == "valid") - ); - let receipt_ids = output - .stage_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - let request_sources = model.request_sources.lock().unwrap(); - let persona_sources = request_sources - .iter() - .filter(|(stage, _)| stage == "cell_persona") - .map(|(_, sources)| sources) - .collect::>(); - let interpreter_sources = request_sources - .iter() - .filter(|(stage, _)| stage == "cell_interpreter") - .map(|(_, sources)| sources) - .collect::>(); - assert!(persona_sources[0].contains(&receipt_ids[0])); - assert!(interpreter_sources[0].contains(&receipt_ids[0])); - assert!(interpreter_sources[0].contains(&receipt_ids[1])); - assert!(persona_sources[1].contains(&receipt_ids[0])); - assert!(persona_sources[1].contains(&receipt_ids[1])); - assert!(persona_sources[1].contains(&receipt_ids[2])); - assert!(interpreter_sources[1].contains(&receipt_ids[3])); - } - - #[tokio::test] - async fn cell_semantic_retry_receives_the_rejected_appraisal() { - let model = Arc::new(CorrectingCellModel { - interpreter_calls: AtomicUsize::new(0), - saw_rejected_appraisal: AtomicBool::new(false), - }); - let engine = CellProjectionEngine { - model: model.clone(), - permit: Arc::new(AllowAllPermit), - projector_model: "flash".into(), - persona_model: "flash".into(), - interpreter_model: "flash".into(), - campaign_contract: None, - aggregate_boundaries: vec![], - }; - let output = engine.execute(fixture_cell_slice()).await.unwrap(); - assert!(model.saw_rejected_appraisal.load(Ordering::SeqCst)); - assert_eq!(output.stage_receipts.len(), 5); - assert_eq!( - output.stage_receipts[2].validation_result, - "semantic_invalid" - ); - assert!(matches!( - output.appraisal.actions[0].effects[0], - StrategicCellEffect::Institution { .. } - )); - } - - struct SemanticallyCorrectingCellModel { - interpreter_calls: AtomicUsize, - verifier_calls: AtomicUsize, - saw_verifier_rejection: AtomicBool, - } - - #[async_trait] - impl ModelPort for SemanticallyCorrectingCellModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - match request.stage.as_str() { - "cell_projector" => Ok(serde_json::json!({ - "segments":[{ - "subject_id":"faction-06", - "narrative":"The deadline is visible, but evidence for an immediate release is absent." - }] - }) - .to_string()), - "cell_persona" => Ok( - "We will withhold the reserve commitment until the public count is verified, and notify the ward clerks of the delay." - .into(), - ), - "cell_interpreter" => { - let call = self.interpreter_calls.fetch_add(1, Ordering::SeqCst); - if call > 0 { - self.saw_verifier_rejection.store( - request.lived_stream.contains("effect_mismatch") - && request.lived_stream.contains("releases the reserve"), - Ordering::SeqCst, - ); - assert!(request - .lived_stream - .contains("Preserve the Persona's exact withholding decision")); - assert!(request - .lived_stream - .contains("include the explicit notice to ward clerks")); - } - let decision = serde_json::json!({"action":{ - "subject_id":"faction-06", - "intent":"state the reserve decision", - "intended_effect":if call == 0 { - "release the reserve immediately" - } else { - "withhold release pending a verified count and notify the ward clerks" - }, - "priority":5, - "state_references":["institution:faction-06"], - "public_channels":["public bulletin"], - "effects":{"institution":{ - "posture":if call == 0 { - "releases the reserve immediately" - } else { - "withhold reserve pending a verified public count; notify ward clerks of the delay" - }, - "location_ids":["forum"] - }} - }}); - Ok(if call == 0 { - serde_json::json!({ - "command":{ - "kind":"submit", - "decisions":{"faction-06":decision} - } - }) - } else { - serde_json::json!({ - "command":{ - "kind":"upsert_decision", - "subject_id":"faction-06", - "decision":decision - } - }) - }.to_string()) - } - "cell_effect_verifier" => { - assert!( - request - .lived_stream - .contains("reject any effect that substitutes a containing population") - ); - assert!(request - .lived_stream - .contains("sole map of canonical subjects, locations, and destinations")); - assert!(request.lived_stream.contains("exact_subject_permission")); - assert!(request - .lived_stream - .contains("empty target list is intentional")); - assert!(request.lived_stream.contains("At location forum")); - let call = self.verifier_calls.fetch_add(1, Ordering::SeqCst); - Ok(serde_json::json!({ - "verdicts":[{ - "action_index":0, - "result":if call > 0 { "match" } else { "mismatch" }, - "findings":if call > 0 { - Vec::::new() - } else { - vec![ - serde_json::json!({ - "mismatch_kind":"effect_reversal", - "repair_guidance":"Preserve the Persona's exact withholding decision rather than reversing it into release." - }), - serde_json::json!({ - "mismatch_kind":"effect_omission", - "repair_guidance":"Rewrite the posture compactly to include the explicit notice to ward clerks as well as the withholding decision." - }) - ] - } - }] - }) - .to_string()) - } - stage => Err(anyhow!("unexpected fixture stage {stage}")), - } - } - - fn provider(&self) -> &'static str { - "semantic-correction-fixture" - } - } - - #[tokio::test] - async fn effect_verifier_delivers_multiple_findings_to_one_bounded_correction() { - let model = Arc::new(SemanticallyCorrectingCellModel { - interpreter_calls: AtomicUsize::new(0), - verifier_calls: AtomicUsize::new(0), - saw_verifier_rejection: AtomicBool::new(false), - }); - let output = CellProjectionEngine { - model: model.clone(), - permit: Arc::new(AllowAllPermit), - projector_model: "flash".into(), - persona_model: "flash".into(), - interpreter_model: "flash".into(), - campaign_contract: None, - aggregate_boundaries: vec![], - } - .execute(fixture_cell_slice()) - .await - .unwrap(); - assert!(model.saw_verifier_rejection.load(Ordering::SeqCst)); - assert_eq!(model.interpreter_calls.load(Ordering::SeqCst), 2); - assert_eq!(model.verifier_calls.load(Ordering::SeqCst), 2); - assert_eq!(output.stage_receipts.len(), 6); - assert_eq!(output.stage_receipts[3].stage, "cell_effect_verifier"); - assert_eq!( - output.stage_receipts[3].validation_result, - "semantic_invalid" - ); - let StrategicCellEffect::Institution { posture, .. } = - &output.appraisal.actions[0].effects[0] - else { - panic!("corrected effect changed type") - }; - assert!(posture.contains("notify ward clerks")); - } - - struct CachingVerifierModel { - calls: AtomicUsize, - faction_seven_calls: AtomicUsize, - } - - #[async_trait] - impl ModelPort for CachingVerifierModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - assert_eq!(request.stage, "cell_effect_verifier"); - self.calls.fetch_add(1, Ordering::SeqCst); - if request.lived_stream.contains("steady-seven") { - self.faction_seven_calls.fetch_add(1, Ordering::SeqCst); - } - let mismatch = request.lived_stream.contains("reverse-six"); - Ok(serde_json::json!({ - "verdicts":[{ - "action_index":0, - "result":if mismatch { "mismatch" } else { "match" }, - "findings":if mismatch { - vec![serde_json::json!({ - "mismatch_kind":"effect_reversal", - "repair_guidance":"Preserve Faction Six's stated withholding rather than reversing it." - })] - } else { - Vec::::new() - } - }] - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "caching-verifier-fixture" - } - } - - fn institution_decision( - subject_id: &str, - intended_effect: &str, - posture: &str, - state_reference: &str, - ) -> serde_json::Value { - serde_json::json!({"action":{ - "subject_id":subject_id, - "intent":"state a bounded institutional course", - "intended_effect":intended_effect, - "priority":50, - "state_references":[state_reference], - "public_channels":["public bulletin"], - "effects":{"institution":{"posture":posture,"location_ids":["forum"]}} - }}) - } - - fn test_appraisal_schema( - slice: &PermittedCellSlice, - active_subject_ids: &BTreeSet, - narrative: &str, - ) -> serde_json::Value { - let visible_slice = bounded_interpreter_slice(slice, narrative); - let mut schema = serde_json::to_value(schema_for!(CellAppraisalProposal)).unwrap(); - constrain_cell_proposal_schema(&mut schema, &visible_slice, active_subject_ids).unwrap(); - schema - } - - #[tokio::test] - async fn interpreter_workbench_reuses_unchanged_valid_effect_verification() { - let mut slice = fixture_cell_slice(); - let mut second = slice.constituents[0].clone(); - second.subject_id = "faction-07".into(); - second.name = "Faction Seven".into(); - second.permitted_state_references = BTreeSet::from(["institution:faction-07".into()]); - second.current_posture = Some("observing the count".into()); - slice.constituents.push(second); - slice.decision_owner_ids.insert("faction-07".into()); - slice.max_actions = 2; - let active_subject_ids = slice.decision_owner_ids.clone(); - let model = Arc::new(CachingVerifierModel { - calls: AtomicUsize::new(0), - faction_seven_calls: AtomicUsize::new(0), - }); - let appraisal_schema = test_appraisal_schema( - &slice, - &active_subject_ids, - "Faction Six withholds; Faction Seven publishes.", - ); - let mut workbench = CellInterpreterWorkbench { - model: model.clone(), - permit: Arc::new(AllowAllPermit), - interpreter_model: "flash".into(), - slice, - active_subject_ids, - lived_stream: "At location forum: Faction Six and Faction Seven.".into(), - persona_turn: "Faction Six withholds; Faction Seven publishes.".into(), - campaign_policy: "{}".into(), - appraisal_schema, - draft: BTreeMap::new(), - repair_subject_ids: BTreeSet::new(), - accepted_verifier_bindings: BTreeSet::new(), - }; - let context = ModelAgentToolContext { - source_receipt_ids: vec!["persona:one".into()], - current_model_receipt: None, - }; - let initial_schema = workbench.action_schema().unwrap(); - let initial_schema_text = serde_json::to_string(&initial_schema).unwrap(); - assert!(initial_schema_text.contains("submit")); - assert!(!initial_schema_text.contains("upsert_decision")); - let first = workbench - .invoke( - CellInterpreterAgentAction { - command: CellInterpreterAgentCommand::Submit { - decisions: BTreeMap::from([ - ( - "faction-06".into(), - institution_decision( - "faction-06", - "reverse-six", - "release immediately", - "institution:faction-06", - ), - ), - ( - "faction-07".into(), - institution_decision( - "faction-07", - "steady-seven", - "publish the verified count", - "institution:faction-07", - ), - ), - ]), - }, - }, - &context, - ) - .await; - assert!(matches!( - first, - ModelAgentToolOutcome::Rejected { - finding: CellInterpreterFinding::EffectMismatch { .. }, - .. - } - )); - assert_eq!(model.calls.load(Ordering::SeqCst), 2); - assert_eq!(model.faction_seven_calls.load(Ordering::SeqCst), 1); - let repair_schema = workbench.action_schema().unwrap(); - let repair_schema_text = serde_json::to_string(&repair_schema).unwrap(); - assert!(!repair_schema_text.contains("submit")); - assert!(repair_schema_text.contains("upsert_decision")); - assert!(repair_schema_text.contains("faction-06")); - assert!(!repair_schema_text.contains("inspect_activity_targets")); - assert!( - !jsonschema::validator_for(&repair_schema) - .unwrap() - .is_valid(&serde_json::json!({ - "command":{ - "kind":"upsert_decision", - "subject_id":"faction-07", - "decision":{"inaction":{ - "subject_id":"faction-07", - "reason":"This accepted owner is not repairable." - }} - } - })) - ); - assert!(!repair_schema_text.contains("inspect_draft")); - assert!(!repair_schema_text.contains("remove_decision")); - - let wholesale_resubmit = workbench - .invoke( - CellInterpreterAgentAction { - command: CellInterpreterAgentCommand::Submit { - decisions: BTreeMap::new(), - }, - }, - &context, - ) - .await; - assert!(matches!( - wholesale_resubmit, - ModelAgentToolOutcome::Rejected { - finding: CellInterpreterFinding::SubmitRequiresEmptyDraft { .. }, - .. - } - )); - let unrelated_repair = workbench - .invoke( - CellInterpreterAgentAction { - command: CellInterpreterAgentCommand::UpsertDecision { - subject_id: "faction-07".into(), - decision: institution_decision( - "faction-07", - "rewrite-seven", - "replace the already accepted course", - "institution:faction-07", - ), - }, - }, - &context, - ) - .await; - assert!(matches!( - unrelated_repair, - ModelAgentToolOutcome::Rejected { - finding: CellInterpreterFinding::DecisionNotRepairable { .. }, - .. - } - )); - assert_eq!(model.calls.load(Ordering::SeqCst), 2); - - let second = workbench - .invoke( - CellInterpreterAgentAction { - command: CellInterpreterAgentCommand::UpsertDecision { - subject_id: "faction-06".into(), - decision: institution_decision( - "faction-06", - "withhold-six", - "withhold pending the verified count", - "institution:faction-06", - ), - }, - }, - &context, - ) - .await; - assert!(matches!( - second, - ModelAgentToolOutcome::Accepted { - output: CellInterpreterAgentOutput::Appraisal(_), - .. - } - )); - assert_eq!(model.calls.load(Ordering::SeqCst), 3); - assert_eq!( - model.faction_seven_calls.load(Ordering::SeqCst), - 1, - "the unchanged accepted action must not repay its semantic verifier" - ); - } - - #[tokio::test] - async fn interpreter_repair_keeps_other_unadmitted_owners_repairable() { - let mut slice = fixture_cell_slice(); - let mut second = slice.constituents[0].clone(); - second.subject_id = "faction-07".into(); - second.name = "Faction Seven".into(); - second.permitted_state_references = BTreeSet::from(["institution:faction-07".into()]); - slice.constituents.push(second); - slice.decision_owner_ids.insert("faction-07".into()); - slice.max_actions = 2; - let active_subject_ids = slice.decision_owner_ids.clone(); - let appraisal_schema = test_appraisal_schema( - &slice, - &active_subject_ids, - "Both factions hold for the count.", - ); - let mut workbench = CellInterpreterWorkbench { - model: Arc::new(CachingVerifierModel { - calls: AtomicUsize::new(0), - faction_seven_calls: AtomicUsize::new(0), - }), - permit: Arc::new(AllowAllPermit), - interpreter_model: "flash".into(), - slice, - active_subject_ids, - lived_stream: "At location forum: Faction Six and Faction Seven.".into(), - persona_turn: "Both factions hold for the count.".into(), - campaign_policy: "{}".into(), - appraisal_schema, - draft: BTreeMap::from([ - ( - "faction-06".into(), - serde_json::json!({"inaction":{ - "subject_id":"faction-06", - "reason":"" - }}), - ), - ( - "faction-07".into(), - serde_json::json!({"inaction":{ - "subject_id":"faction-07", - "reason":"" - }}), - ), - ]), - repair_subject_ids: BTreeSet::from(["faction-06".into(), "faction-07".into()]), - accepted_verifier_bindings: BTreeSet::new(), - }; - let outcome = workbench - .invoke( - CellInterpreterAgentAction { - command: CellInterpreterAgentCommand::UpsertDecision { - subject_id: "faction-06".into(), - decision: serde_json::json!({"inaction":{ - "subject_id":"faction-06", - "reason":"Faction Six deliberately holds for the verified count." - }}), - }, - }, - &ModelAgentToolContext { - source_receipt_ids: vec!["persona:one".into()], - current_model_receipt: None, - }, - ) - .await; - - assert!(matches!( - outcome, - ModelAgentToolOutcome::Rejected { - finding: CellInterpreterFinding::LocalValidation { .. }, - .. - } - )); - let repair_schema_text = - serde_json::to_string(&workbench.action_schema().unwrap()).unwrap(); - assert!(repair_schema_text.contains("faction-07")); - assert!(!repair_schema_text.contains("submit")); - } - - #[test] - fn empty_cell_appraisal_requires_exact_attributed_inaction() { - let mut slice = fixture_cell_slice(); - let mut appraisal = bind_cell_appraisal( - &slice, - &BTreeSet::from(["faction-06".into()]), - CellAppraisalProposal { - actions: vec![], - inactions: vec![crate::domain::CellInaction { - subject_id: "faction-06".into(), - reason: "The institution deliberately holds its current position.".into(), - }], - }, - ) - .unwrap(); - validate_cell_appraisal(&slice, &appraisal).unwrap(); - appraisal.inactions[0].reason = " ".into(); - let error = validate_cell_appraisal(&slice, &appraisal).unwrap_err(); - assert!( - error - .to_string() - .contains("inaction for subject faction-06 requires a non-empty reason") - ); - - appraisal.inactions[0].reason = "The institution holds.".into(); - appraisal.actions.push(crate::domain::CellActionProposal { - subject_id: "faction-06".into(), - intent: "publish a new position".into(), - intended_effect: "adopt a bounded commitment".into(), - priority: 50, - state_references: vec!["institution:faction-06".into()], - public_channels: vec!["public bulletin".into()], - effects: vec![StrategicCellEffect::Institution { - institution_id: "faction-06".into(), - posture: "publishing a bounded new commitment".into(), - location_ids: vec!["forum".into()], - }], - }); - assert!( - validate_cell_appraisal(&slice, &appraisal) - .unwrap_err() - .to_string() - .contains("subject faction-06 appears in both actions and inactions") - ); - - appraisal.inactions.clear(); - slice.max_actions = 2; - appraisal.actions.push(appraisal.actions[0].clone()); - assert!( - validate_cell_appraisal(&slice, &appraisal) - .unwrap_err() - .to_string() - .contains("subject faction-06 has duplicate strategic actions") - ); - } - - #[test] - fn every_projected_decision_owner_requires_an_action_or_explicit_inaction() { - let mut slice = fixture_cell_slice(); - let mut second = slice.constituents[0].clone(); - second.subject_id = "faction-07".into(); - second.name = "Faction Seven".into(); - second.permitted_state_references = BTreeSet::from(["institution:faction-07".into()]); - slice.constituents.push(second); - slice.max_actions = 2; - let active = BTreeSet::from(["faction-06".into(), "faction-07".into()]); - let mut appraisal = bind_cell_appraisal( - &slice, - &active, - CellAppraisalProposal { - actions: vec![], - inactions: vec![crate::domain::CellInaction { - subject_id: "faction-06".into(), - reason: "Faction Six explicitly holds its current course.".into(), - }], - }, - ) - .unwrap(); - - let error = validate_cell_appraisal(&slice, &appraisal).unwrap_err(); - assert!(error.to_string().contains("faction-07")); - - appraisal.inactions.push(crate::domain::CellInaction { - subject_id: "faction-07".into(), - reason: "Faction Seven explicitly waits for the vote count.".into(), - }); - validate_cell_appraisal(&slice, &appraisal).unwrap(); - validate_active_decision_owners(&active, &appraisal).unwrap(); - } - - #[test] - fn compact_cell_prompt_contract_is_valid_json() { - let mut schema = serde_json::to_value(schema_for!(CellAppraisalProposal)).unwrap(); - constrain_cell_proposal_schema( - &mut schema, - &fixture_cell_slice(), - &BTreeSet::from(["faction-06".into()]), - ) - .unwrap(); - let schema_text = serde_json::to_string(&schema).unwrap(); - assert!(schema_text.contains("\"maxLength\":240")); - assert!(schema.get("$defs").is_none()); - assert!(!schema_text.contains("\"$ref\"")); - assert!(schema.pointer("/properties/decisions").is_some()); - assert!(schema.pointer("/properties/actions").is_none()); - assert!(schema.pointer("/properties/inactions").is_none()); - let initial_schema = - cell_interpreter_agent_schema(&schema, CellInterpreterSchemaState::Initial).unwrap(); - let initial_schema_text = serde_json::to_string(&initial_schema).unwrap(); - assert_eq!(initial_schema["type"], "object"); - assert!(initial_schema.get("oneOf").is_none()); - assert!( - initial_schema - .pointer("/properties/command/oneOf") - .is_some() - ); - assert!(initial_schema_text.contains("submit")); - assert!(!initial_schema_text.contains("upsert_decision")); - assert!(!initial_schema_text.contains("inspect_activity_targets")); - assert!(!initial_schema_text.contains("inspect_draft")); - assert!(!initial_schema_text.contains("remove_decision")); - assert!(initial_schema_text.contains("\"maxLength\":240")); - assert!( - jsonschema::validator_for(&initial_schema) - .unwrap() - .is_valid(&serde_json::json!({ - "command":{ - "kind":"submit", - "decisions":{ - "faction-06":{ - "inaction":{ - "subject_id":"faction-06", - "reason":"Faction Six deliberately waits for the count." - } - } - } - } - })) - ); - assert!( - !jsonschema::validator_for(&initial_schema) - .unwrap() - .is_valid(&serde_json::json!({ - "command":{ - "kind":"submit", - "decisions":{}, - "decision":{"inaction":{"reason":"illegal mixed payload"}} - } - })) - ); - let mut provider_schema = initial_schema; - crate::model_connector::project_strict_responses_schema(&mut provider_schema).unwrap(); - assert_eq!(provider_schema["type"], "object"); - assert!( - provider_schema - .pointer("/properties/command/anyOf") - .is_some() - ); - assert!( - jsonschema::validator_for(&provider_schema) - .unwrap() - .is_valid(&serde_json::json!({ - "command":{ - "kind":"submit", - "decisions":{ - "faction-06":{ - "inaction":{ - "subject_id":"faction-06", - "reason":"Faction Six deliberately waits for the count." - } - } - } - } - })) - ); - let repair_subject_ids = BTreeSet::from(["faction-06".to_owned()]); - let repair_schema = cell_interpreter_agent_schema( - &schema, - CellInterpreterSchemaState::Repair(&repair_subject_ids), - ) - .unwrap(); - let repair_schema_text = serde_json::to_string(&repair_schema).unwrap(); - assert!(repair_schema_text.contains("upsert_decision")); - assert!(!repair_schema_text.contains("submit")); - assert!( - jsonschema::validator_for(&repair_schema) - .unwrap() - .is_valid(&serde_json::json!({ - "command":{ - "kind":"upsert_decision", - "subject_id":"faction-06", - "decision":{ - "inaction":{ - "subject_id":"faction-06", - "reason":"Faction Six deliberately waits for the count." - } - } - } - })) - ); - let mut provider_repair_schema = repair_schema; - crate::model_connector::project_strict_responses_schema(&mut provider_repair_schema) - .unwrap(); - assert!( - jsonschema::validator_for(&provider_repair_schema) - .unwrap() - .is_valid(&serde_json::json!({ - "command":{ - "kind":"upsert_decision", - "subject_id":"faction-06", - "decision":{ - "inaction":{ - "subject_id":"faction-06", - "reason":"Faction Six deliberately waits for the count." - } - } - } - })) - ); - assert_eq!( - exact_constituent_effect_bundle_schema(&fixture_cell_slice().constituents[0]) - .pointer("/properties/institution/anyOf/0/properties/posture/maxLength"), - Some(&serde_json::json!(crate::domain::MAX_POSTURE_CHARS)) - ); - } - - fn add_many_activity_targets(slice: &mut PermittedCellSlice, count: usize) { - slice.constituents[0].subject_kind = AgencySubjectKind::Actor; - slice.constituents[0].activity_targets = (0..count) - .map(|index| { - ( - format!("target:{index:04}"), - CellActivityTargetSlice { - name: format!("Target {index:04}"), - locations: BTreeMap::from([("forum".into(), "Forum".into())]), - }, - ) - }) - .collect(); - } - - #[test] - fn projector_context_is_bounded_by_decision_owners_not_cell_population() { - let mut slice = fixture_cell_slice(); - add_many_activity_targets(&mut slice, 1_000); - for index in 0..500 { - let mut inactive = slice.constituents[0].clone(); - inactive.subject_id = format!("inactive:{index:04}"); - inactive.name = format!("Inactive {index:04}"); - inactive.activity_targets.clear(); - slice.constituents.push(inactive); - } - slice.perceived_events.push(CellPerceivedEventSlice { - event_id: "event:crowded".into(), - summary: "A public count reaches the forum.".into(), - perceived_by_subject_ids: slice - .constituents - .iter() - .map(|subject| subject.subject_id.clone()) - .collect(), - }); - - let context = cell_projector_context(&slice); - assert_eq!(context["represented_constituent_count"], 501); - assert_eq!(context["constituents"].as_array().unwrap().len(), 1); - assert_eq!( - context["constituents"][0]["activity_targets"] - .as_object() - .unwrap() - .len(), - INITIAL_ACTIVITY_TARGET_LIMIT - ); - assert_eq!( - context["perceived_events"][0]["perceived_by_subject_ids"] - .as_array() - .unwrap() - .len(), - 1 - ); - assert!(serde_json::to_vec(&context).unwrap().len() < 64_000); - } - - #[test] - fn interpreter_projects_exact_narrative_targets_without_expanding_authority() { - let mut slice = fixture_cell_slice(); - add_many_activity_targets(&mut slice, 1_000); - let active_subject_ids = slice.decision_owner_ids.clone(); - let initial_schema = test_appraisal_schema(&slice, &active_subject_ids, "ordinary work"); - let initial_schema = serde_json::to_string(&initial_schema).unwrap(); - assert!(!initial_schema.contains("target:0999")); - let false_prefix = bounded_interpreter_slice(&slice, "Target 09990 remains absent."); - assert!( - !false_prefix.constituents[0] - .activity_targets - .contains_key("target:0999") - ); - let visible_slice = bounded_interpreter_slice( - &slice, - "Faction Six addresses Target 0999. Tell Target 0999 to attend.", - ); - let projected_targets = &visible_slice.constituents[0].activity_targets; - assert!(projected_targets.contains_key("target:0999")); - assert!(projected_targets.len() <= INITIAL_ACTIVITY_TARGET_LIMIT + 1); - let projected_schema = test_appraisal_schema( - &slice, - &active_subject_ids, - "Faction Six addresses Target 0999. Tell Target 0999 to attend.", - ); - let projected_schema = serde_json::to_string(&projected_schema).unwrap(); - assert!(projected_schema.contains("target:0999")); - assert!(projected_schema.len() < 64_000); - assert_eq!( - slice.constituents[0].activity_targets.len(), - 1_000, - "narrative projection must not truncate or rewrite canonical permission" - ); - } - - #[test] - fn cell_schema_keeps_unavailable_effect_lanes_null_only() { - let mut slice = fixture_cell_slice(); - let actor_id = "relationship-anchor:reed".to_owned(); - { - let actor = &mut slice.constituents[0]; - actor.subject_id = actor_id.clone(); - actor.subject_kind = AgencySubjectKind::Actor; - actor.name = "Reed".into(); - actor.permitted_state_references = - BTreeSet::from(["subject:relationship-anchor:reed".into()]); - actor.information_channels.clear(); - actor.current_posture = None; - actor.reachable_destinations.clear(); - actor.migration_destinations.clear(); - actor.activity_targets = BTreeMap::from([( - "inst_zhestokost".into(), - CellActivityTargetSlice { - name: "Zhestokost".into(), - locations: BTreeMap::from([("forum".into(), "Forum".into())]), - }, - )]); - } - slice.detail_focus_subject_id = Some(actor_id.clone()); - let active = BTreeSet::from([actor_id]); - let mut schema = serde_json::to_value(schema_for!(CellAppraisalProposal)).unwrap(); - constrain_cell_proposal_schema(&mut schema, &slice, &active).unwrap(); - let validator = jsonschema::validator_for(&schema).unwrap(); - let action = |effects| { - serde_json::json!({ - "decisions":{"relationship-anchor:reed":{"action":{ - "subject_id":"relationship-anchor:reed", - "intent":"keep the patients together", - "intended_effect":"make one bounded local attempt", - "priority":80, - "state_references":["subject:relationship-anchor:reed"], - "public_channels":[], - "effects":effects - }}} - }) - }; - - assert!(validator.is_valid(&action(serde_json::json!({ - "actor_activities":{"prepare":[{ - "target_subject_ids":[], - "location_ids":["forum"] - }]} - })))); - assert!(!validator.is_valid(&serde_json::json!({"decisions":{}}))); - let mut conflicting_decision = action(serde_json::json!({ - "actor_activities":{"prepare":[{ - "target_subject_ids":[], - "location_ids":["forum"] - }]} - })); - conflicting_decision - .pointer_mut("/decisions/relationship-anchor:reed") - .and_then(serde_json::Value::as_object_mut) - .unwrap() - .insert( - "inaction".into(), - serde_json::json!({ - "subject_id":"relationship-anchor:reed", - "reason":"Reed explicitly waits." - }), - ); - assert!( - !validator.is_valid(&conflicting_decision), - "one exact subject slot cannot encode both action and inaction" - ); - assert!(validator.is_valid(&action(serde_json::json!({ - "actor_activities":{ - "investigate":[{ - "target_subject_ids":[], - "location_ids":["forum"] - }], - "prepare":[{ - "target_subject_ids":[], - "location_ids":["forum"] - }] - } - })))); - assert!(!validator.is_valid(&action(serde_json::json!({ - "actor_activities":{ - "investigate":[{ - "target_subject_ids":[], - "location_ids":["forum"] - }], - "invented_duplicate_investigate":{ - "target_subject_ids":["inst_zhestokost"], - "location_ids":["forum"] - } - } - })))); - assert!(!validator.is_valid(&action(serde_json::json!({ - "actor_move":{"destination_id":"forum"} - })))); - assert!(!validator.is_valid(&action(serde_json::json!({ - "gestalt_migration":{"destination_gestalt_id":"loc_water_ice_rail_corridor"} - })))); - assert!(!validator.is_valid(&action(serde_json::json!({ - "actor_activities":{"coordinate":[{ - "target_subject_ids":[], - "location_ids":["forum"] - }]} - })))); - assert!(validator.is_valid(&action(serde_json::json!({ - "actor_activities":{"obstruct":[{ - "target_subject_ids":[], - "location_ids":["forum"] - }]} - })))); - assert!(validator.is_valid(&action(serde_json::json!({ - "actor_activities":{"coordinate":[{ - "target_subject_ids":["inst_zhestokost"], - "location_ids":["forum"] - }]} - })))); - assert!(!validator.is_valid(&action(serde_json::json!({ - "actor_activities":{"coordinate":[{ - "target_subject_ids":["invented-target"], - "location_ids":["forum"] - }]} - })))); - assert!(!validator.is_valid(&action(serde_json::json!({ - "actor_activities":{"prepare":[{ - "target_subject_ids":[], - "location_ids":["invented-location"] - }]} - })))); - assert_eq!( - allowed_constituent_effect_types(&slice.constituents[0]), - vec!["actor_activities"] - ); - let strict_shaped_action = action(serde_json::json!({ - "institution":null, - "gestalt_pressure":null, - "gestalt_activities":null, - "gestalt_migration":null, - "actor_move":null, - "actor_activities":{ - "prepare":[{ - "target_subject_ids":[], - "location_ids":["forum"] - }], - "coordinate":null, - "investigate":null, - "recruit":null, - "obstruct":null, - "trade":null, - "communicate":null - }, - "member_activities":null, - "member_migration":null - })); - assert!( - validator.is_valid(&strict_shaped_action), - "the canonical return-path schema must accept the strict provider projection" - ); - let mut strict_schema = schema; - crate::model_connector::project_strict_responses_schema(&mut strict_schema).unwrap(); - let strict_effect_properties = strict_schema - .pointer("/properties/decisions/properties/relationship-anchor:reed/anyOf/0/properties/action/properties/effects/properties") - .and_then(serde_json::Value::as_object) - .unwrap(); - assert_eq!(strict_effect_properties.len(), 8); - let strict_validator = jsonschema::validator_for(&strict_schema).unwrap(); - assert!(strict_validator.is_valid(&strict_shaped_action)); - let mut unauthorized_move = strict_shaped_action; - *unauthorized_move - .pointer_mut("/decisions/relationship-anchor:reed/action/effects/actor_move") - .unwrap() = serde_json::json!({"destination_id":"forum"}); - assert!(!strict_validator.is_valid(&unauthorized_move)); - } - - #[test] - fn interpreter_context_disambiguates_target_location_from_reachable_destination() { - let mut slice = fixture_cell_slice(); - let actor = &mut slice.constituents[0]; - actor.subject_id = "clinic-director".into(); - actor.subject_kind = AgencySubjectKind::Actor; - actor.location_ids = BTreeSet::from(["junction".into()]); - actor.current_posture = None; - actor.reachable_destinations = - BTreeMap::from([("garrison".into(), "Garrison Outpost".into())]); - actor.activity_targets = BTreeMap::from([( - "reed".into(), - CellActivityTargetSlice { - name: "Reed".into(), - locations: BTreeMap::from([("junction".into(), "Kostolom Junction".into())]), - }, - )]); - let context = cell_interpreter_context(&slice, &BTreeSet::from(["clinic-director".into()])); - - assert_eq!( - context.pointer("/exact_permissions/0/reachable_destinations/garrison"), - Some(&serde_json::json!("Garrison Outpost")) - ); - assert_eq!( - context.pointer("/exact_permissions/0/activity_targets/reed/name"), - Some(&serde_json::json!("Reed")) - ); - assert_eq!( - context.pointer("/exact_permissions/0/activity_targets/reed/locations/junction"), - Some(&serde_json::json!("Kostolom Junction")) - ); - } - - #[test] - fn cell_schema_does_not_reject_a_large_exact_reference_slice() { - let mut slice = fixture_cell_slice(); - let subject_id = slice.constituents[0].subject_id.clone(); - slice.constituents[0].permitted_state_references = (0..21) - .map(|index| format!("reference:{index:02}")) - .collect(); - let active = BTreeSet::from([subject_id]); - let mut schema = serde_json::to_value(schema_for!(CellAppraisalProposal)).unwrap(); - constrain_cell_proposal_schema(&mut schema, &slice, &active).unwrap(); - let validator = jsonschema::validator_for(&schema).unwrap(); - let exact_references = slice.constituents[0] - .permitted_state_references - .iter() - .cloned() - .collect::>(); - let subject_id = slice.constituents[0].subject_id.clone(); - let appraisal = serde_json::json!({ - "decisions":{(subject_id.clone()):{"action":{ - "subject_id":subject_id, - "intent":"hold the exact supplied footing", - "intended_effect":"prepare locally", - "priority":80, - "state_references":exact_references, - "public_channels":[], - "effects":{"institution":{ - "posture":"withhold action pending an exact count", - "location_ids":[] - }} - }}} - }); - - assert!(validator.is_valid(&appraisal)); - } - - #[test] - fn exact_empty_string_arrays_remain_valid_strict_response_schemas() { - let schema = exact_string_array_schema(&BTreeSet::new(), 0, 8); - assert_eq!(schema["maxItems"], 0); - assert_eq!(schema["items"]["type"], "string"); - assert!( - jsonschema::validator_for(&schema) - .unwrap() - .is_valid(&serde_json::json!([])) - ); - } - - #[test] - fn effect_verifier_binding_changes_with_the_exact_action_bundle() { - let first = crate::domain::CellActionProposal { - subject_id: "faction-06".into(), - intent: "withhold the reserve".into(), - intended_effect: "wait for a verified count".into(), - priority: 1, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::Institution { - institution_id: "faction-06".into(), - posture: "withholding pending verification".into(), - location_ids: vec!["forum".into()], - }], - }; - let mut second = first.clone(); - second.intended_effect = "release immediately".into(); - assert_eq!( - cell_effect_verification_binding("snapshot", std::slice::from_ref(&first)).unwrap(), - cell_effect_verification_binding("snapshot", std::slice::from_ref(&first)).unwrap() - ); - assert_ne!( - cell_effect_verification_binding("snapshot", &[first]).unwrap(), - cell_effect_verification_binding("snapshot", &[second]).unwrap() - ); - } - - #[test] - fn effect_verifier_separates_direct_contact_from_publication_authority() { - assert!(CELL_EFFECT_VERIFIER_INSTRUCTIONS.contains( - "An exact activity_targets entry is sufficient authority to attempt direct communication" - )); - assert!(CELL_EFFECT_VERIFIER_INSTRUCTIONS.contains( - "allowed_persistent_publication_channels governs only durable public publication" - )); - assert!(CELL_EFFECT_VERIFIER_INSTRUCTIONS.contains( - "apply only coordination_target_contract.rule for this exact attributed subject" - )); - assert!(CELL_EFFECT_VERIFIER_INSTRUCTIONS.contains( - "Communication can therefore be faithfully combined with restraint without implying coordinate" - )); - assert!(CELL_EFFECT_VERIFIER_INSTRUCTIONS.contains( - "Reject effect omission only when the Persona explicitly undertakes another observable act" - )); - assert!(CELL_EFFECT_VERIFIER_INSTRUCTIONS.contains( - "target_subject_ids names the canonical addressees and candidate_action.public_channels names the simultaneous public reach" - )); - assert!( - CELL_EFFECT_VERIFIER_INSTRUCTIONS - .contains("Do not demand a second targetless communicate for that same utterance") - ); - assert!(CELL_EFFECT_VERIFIER_INSTRUCTIONS.contains( - "A matching current-location name denotes that place or its unnamed local public" - )); - let mut slice = fixture_cell_slice(); - slice.canonical_locations = BTreeMap::from([("yard".into(), "Thornweald Assembly".into())]); - let permission = cell_action_verifier_permission(&slice, "faction-06").unwrap(); - assert!(permission.get("canonical_locations").is_none()); - assert!( - permission["activity_targets"] - .as_object() - .unwrap() - .is_empty() - ); - let unauthorized = validate_constituent_effect( - &slice.constituents[0], - &StrategicCellEffect::Institution { - institution_id: "faction-06".into(), - posture: "moving the public deadline to the assembly".into(), - location_ids: vec!["yard".into()], - }, - None, - ) - .unwrap_err(); - assert!(unauthorized.to_string().contains("exact allowed locations")); - } - - #[test] - fn effect_verifier_distinguishes_member_coordination_from_gestalt_coordination() { - let member = coordination_target_contract(&serde_json::json!({ - "subject_kind":"gestalt_member", - "source_gestalt_id":"raincross-households" - })); - assert_eq!( - member.get("internal_population_target_subject_ids"), - Some(&serde_json::json!(["raincross-households"])) - ); - assert!( - member["rule"] - .as_str() - .unwrap() - .contains("targeting exactly raincross-households") - ); - - let qualified_member = coordination_target_contract(&serde_json::json!({ - "subject_kind":"gestalt_member", - "source_gestalt_id":"gestalt:raincross-households" - })); - assert_eq!( - qualified_member.get("internal_population_target_subject_ids"), - Some(&serde_json::json!(["gestalt:raincross-households"])) - ); - - let gestalt = coordination_target_contract(&serde_json::json!({ - "subject_kind":"gestalt" - })); - assert_eq!( - gestalt.get("internal_population_target_subject_ids"), - Some(&serde_json::json!([])) - ); - assert!(gestalt["rule"].as_str().unwrap().contains("targetless")); - } - - #[test] - fn effect_verifier_requires_one_ordered_verdict_per_action() { - let verification = CellEffectVerification { - verdicts: vec![ - CellActionEffectVerdict { - action_index: 0, - result: CellEffectMatchResult::Match, - findings: Vec::new(), - }, - CellActionEffectVerdict { - action_index: 1, - result: CellEffectMatchResult::Mismatch, - findings: vec![CellEffectMismatchFinding { - mismatch_kind: CellEffectMismatchKind::TargetSubstitution, - repair_guidance: "Remove the substituted target and retain only the exact addressed subject." - .into(), - }], - }, - ], - }; - assert_eq!( - validate_effect_verification(&verification, 2).unwrap(), - vec![1] - ); - - let mut missing_guidance = verification.clone(); - missing_guidance.verdicts[1].findings[0] - .repair_guidance - .clear(); - assert!( - validate_effect_verification(&missing_guidance, 2) - .unwrap_err() - .to_string() - .contains("findings set") - ); - - let mut duplicate = verification; - duplicate.verdicts[1].action_index = 0; - assert!( - validate_effect_verification(&duplicate, 2) - .unwrap_err() - .to_string() - .contains("action 1") - ); - } - - #[test] - fn effect_verifier_schema_binds_the_exact_batch_size() { - let schema = cell_effect_verifier_schema(4).unwrap(); - assert_eq!( - schema.pointer("/properties/verdicts/minItems"), - Some(&serde_json::json!(4)) - ); - assert_eq!( - schema.pointer("/properties/verdicts/maxItems"), - Some(&serde_json::json!(4)) - ); - assert!( - schema - .pointer("/$defs/CellActionEffectVerdict/oneOf/0/properties/findings/items") - .is_some(), - "even a zero-length findings branch needs an items schema at the provider boundary" - ); - let validator = jsonschema::validator_for(&schema).unwrap(); - let faithful = serde_json::json!({ - "verdicts":[ - {"action_index":0,"result":"match","findings":[]}, - {"action_index":1,"result":"mismatch","findings":[{"mismatch_kind":"target_substitution","repair_guidance":"Use the exact addressed subject."}]}, - {"action_index":2,"result":"match","findings":[]}, - {"action_index":3,"result":"match","findings":[]} - ] - }); - assert!(validator.is_valid(&faithful)); - - let long_but_semantically_coherent_guidance = serde_json::json!({ - "verdicts":[ - {"action_index":0,"result":"mismatch","findings":[{"mismatch_kind":"wrong_effect_kind","repair_guidance":"The Persona chose a concrete journey, so preserve that exact decision with the supplied migration effect rather than downgrading it to coordination; if no supplied effect can represent the destination, remove this action and let the world retain the attributed choice without committing an invented route."}]}, - {"action_index":1,"result":"match","findings":[]}, - {"action_index":2,"result":"match","findings":[]}, - {"action_index":3,"result":"match","findings":[]} - ] - }); - assert!(!validator.is_valid(&long_but_semantically_coherent_guidance)); - - let incoherent = serde_json::json!({ - "verdicts":[ - {"action_index":0,"result":"match","findings":[{"mismatch_kind":"invented_outcome","repair_guidance":"Do not claim this succeeded."}]}, - {"action_index":1,"result":"match","findings":[]}, - {"action_index":2,"result":"match","findings":[]}, - {"action_index":3,"result":"match","findings":[]} - ] - }); - assert!(!validator.is_valid(&incoherent)); - } - - struct ParallelActionVerifierModel { - barrier: Arc, - prompts: Arc>>, - } - - #[async_trait] - impl ModelPort for ParallelActionVerifierModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - assert_eq!(request.stage, "cell_effect_verifier"); - self.prompts - .lock() - .unwrap() - .push(request.lived_stream.clone()); - self.barrier.wait().await; - Ok(serde_json::json!({ - "verdicts":[{ - "action_index":0, - "result":"match", - "findings":[] - }] - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "parallel-action-verifier-fixture" - } - } - - #[tokio::test] - async fn effect_verifier_wave_is_parallel_and_subject_scoped() { - let mut slice = fixture_cell_slice(); - let mut second = slice.constituents[0].clone(); - second.subject_id = "faction-07".into(); - second.name = "Faction Seven".into(); - second.permitted_state_references = BTreeSet::from(["institution:faction-07".into()]); - second.current_posture = Some("holding a separate position".into()); - slice.constituents.push(second); - let actions = [ - crate::domain::CellActionProposal { - subject_id: "faction-06".into(), - intent: "publish its position".into(), - intended_effect: "state a bounded commitment".into(), - priority: 10, - state_references: vec!["institution:faction-06".into()], - public_channels: vec!["public bulletin".into()], - effects: vec![StrategicCellEffect::Institution { - institution_id: "faction-06".into(), - posture: "publishing a bounded position".into(), - location_ids: vec!["forum".into()], - }], - }, - crate::domain::CellActionProposal { - subject_id: "faction-07".into(), - intent: "publish its separate position".into(), - intended_effect: "state a distinct bounded commitment".into(), - priority: 9, - state_references: vec!["institution:faction-07".into()], - public_channels: vec!["public bulletin".into()], - effects: vec![StrategicCellEffect::Institution { - institution_id: "faction-07".into(), - posture: "publishing a separate bounded position".into(), - location_ids: vec!["forum".into()], - }], - }, - ]; - let prompts = Arc::new(Mutex::new(Vec::new())); - let model = Arc::new(ParallelActionVerifierModel { - barrier: Arc::new(Barrier::new(2)), - prompts: prompts.clone(), - }); - - let verified = tokio::time::timeout( - std::time::Duration::from_secs(2), - run_cell_effect_verifier_wave( - model, - "flash", - &slice, - "Two separately attributed perspectives are active.", - "Each institution chooses its own public statement.", - "{}", - &actions, - &[], - ), - ) - .await - .expect("parallel verifier wave deadlocked") - .unwrap(); - - assert_eq!( - verified - .iter() - .map(|result| result.action_index) - .collect::>(), - vec![0, 1] - ); - for verification in &verified { - assert_eq!( - verification.output.receipt.snapshot_binding, - cell_effect_verification_binding( - &slice.snapshot_binding, - std::slice::from_ref(&actions[verification.action_index]) - ) - .unwrap() - ); - } - for prompt in prompts.lock().unwrap().iter() { - assert!(prompt.contains( - "Snapshot-location activity precedes relocation; exact-destination activity follows arrival" - )); - assert!(prompt.contains( - "\"cross_location_order\":\"snapshot_location_activity_then_relocation_then_destination_activity\"" - )); - assert!(prompt.contains("\"field_order\":\"not_chronology\"")); - let context: serde_json::Value = serde_json::from_str( - prompt - .split("CONTEXT:\n") - .nth(1) - .expect("verifier prompt contains one context document"), - ) - .unwrap(); - assert_eq!(context["canonical_locations"]["forum"], "Forum"); - assert!( - context["exact_subject_permission"] - .get("canonical_locations") - .is_none() - ); - } - let prompts = prompts.lock().unwrap(); - assert_eq!(prompts.len(), 2); - let first = prompts - .iter() - .find(|prompt| prompt.contains("faction-06")) - .unwrap(); - let second = prompts - .iter() - .find(|prompt| prompt.contains("faction-07")) - .unwrap(); - assert!(!first.contains("faction-07")); - assert!(!second.contains("faction-06")); - assert!(first.contains("exact_subject_permission")); - assert!(first.contains("\"state_references\":[\"institution:faction-06\"]")); - assert!(first.contains("\"public_channels\":[\"public bulletin\"]")); - assert!(!first.contains("exact_typed_permissions")); - } - - #[test] - fn gestalt_pressure_shape_is_rejected_before_the_world_wave() { - let mut slice = fixture_cell_slice(); - let subject = &mut slice.constituents[0]; - subject.subject_id = "crowd".into(); - subject.subject_kind = AgencySubjectKind::Gestalt; - subject.permitted_state_references = BTreeSet::from(["gestalt:crowd".into()]); - let appraisal = bind_cell_appraisal( - &slice, - &BTreeSet::from(["crowd".into()]), - CellAppraisalProposal { - actions: vec![CellActionCandidate { - subject_id: "crowd".into(), - intent: "respond to the pressure".into(), - intended_effect: "change the collective situation".into(), - priority: 1, - state_references: vec!["gestalt:crowd".into()], - public_channels: vec![], - effects: CellEffectBundleCandidate { - gestalt_pressure: Some(CellGestaltPressureEffectCandidate { - pressure_additions: vec![], - pressure_resolutions: vec![], - }), - ..Default::default() - }, - }], - inactions: vec![], - }, - ) - .unwrap(); - assert!( - validate_cell_appraisal(&slice, &appraisal) - .unwrap_err() - .to_string() - .contains("must change one to four markers") - ); - } - - #[test] - fn gestalt_activity_requires_an_exact_permitted_target_and_location() { - let mut slice = fixture_cell_slice(); - let subject = &mut slice.constituents[0]; - subject.subject_id = "refugees".into(); - subject.subject_kind = AgencySubjectKind::Gestalt; - subject.permitted_state_references = BTreeSet::from(["gestalt:refugees".into()]); - subject.activity_targets = BTreeMap::from([( - "dockers".into(), - CellActivityTargetSlice { - name: "Dockers".into(), - locations: BTreeMap::from([("forum".into(), "Forum".into())]), - }, - )]); - let valid = StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees".into(), - activity: crate::domain::StrategicActivityKind::Coordinate, - target_subject_ids: vec!["dockers".into()], - location_ids: vec!["forum".into()], - }; - validate_constituent_effect(subject, &valid, None).unwrap(); - - let internal_coordination = StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees".into(), - activity: crate::domain::StrategicActivityKind::Coordinate, - target_subject_ids: vec![], - location_ids: vec!["forum".into()], - }; - validate_constituent_effect(subject, &internal_coordination, None).unwrap(); - - let invented_target = StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees".into(), - activity: crate::domain::StrategicActivityKind::Coordinate, - target_subject_ids: vec!["unseen-ministry".into()], - location_ids: vec!["forum".into()], - }; - assert!( - validate_constituent_effect(subject, &invented_target, None) - .unwrap_err() - .to_string() - .contains("exact allowed targets") - ); - - let targetless_obstruction = StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees".into(), - activity: crate::domain::StrategicActivityKind::Obstruct, - target_subject_ids: vec![], - location_ids: vec!["forum".into()], - }; - validate_constituent_effect(subject, &targetless_obstruction, None).unwrap(); - - let internal_preparation = StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees".into(), - activity: crate::domain::StrategicActivityKind::Prepare, - target_subject_ids: vec![], - location_ids: vec!["forum".into()], - }; - validate_constituent_effect(subject, &internal_preparation, None).unwrap(); - - let local_investigation = StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees".into(), - activity: crate::domain::StrategicActivityKind::Investigate, - target_subject_ids: vec![], - location_ids: vec!["forum".into()], - }; - validate_constituent_effect(subject, &local_investigation, None).unwrap(); - - let local_communication = StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees".into(), - activity: crate::domain::StrategicActivityKind::Communicate, - target_subject_ids: vec![], - location_ids: vec!["forum".into()], - }; - validate_constituent_effect(subject, &local_communication, None).unwrap(); - } - - #[test] - fn gestalt_migration_is_bound_to_the_exact_population_destination() { - let mut slice = fixture_cell_slice(); - let subject = &mut slice.constituents[0]; - subject.subject_id = "refugees".into(); - subject.subject_kind = AgencySubjectKind::Gestalt; - subject.migration_destinations = BTreeMap::from([( - "harbor-neighbors".into(), - CellMigrationDestinationSlice { - population_name: "Harbor Neighbors".into(), - location_id: "south-harbor".into(), - location_name: "South Harbor".into(), - }, - )]); - let valid = StrategicCellEffect::GestaltMigration { - destination_gestalt_id: "harbor-neighbors".into(), - }; - validate_constituent_effect(subject, &valid, None).unwrap(); - - let invented = StrategicCellEffect::GestaltMigration { - destination_gestalt_id: "palace-court".into(), - }; - assert!( - validate_constituent_effect(subject, &invented, None) - .unwrap_err() - .to_string() - .contains("exact allowed population destinations") - ); - } - - #[test] - fn named_member_activity_stays_attributed_to_the_person() { - let mut slice = fixture_cell_slice(); - slice.member_exceptions.push(CellMemberSlice { - subject_id: "member:mira".into(), - member_id: "mira".into(), - name: "Mira".into(), - source_gestalt_id: "refugees".into(), - source_location_id: "forum".into(), - knowledge: BTreeSet::new(), - capabilities: BTreeSet::new(), - resources: BTreeSet::new(), - information_channels: BTreeSet::new(), - permitted_state_references: BTreeSet::from(["member:mira".into()]), - migration_destinations: BTreeMap::new(), - activity_targets: BTreeMap::from([( - "refugees".into(), - CellActivityTargetSlice { - name: "Refugee Convoy".into(), - locations: BTreeMap::from([("forum".into(), "Forum".into())]), - }, - )]), - goals: vec![], - pressures: vec![], - relationships: BTreeMap::new(), - memories: vec![], - }); - let appraisal = bind_cell_appraisal( - &slice, - &BTreeSet::from(["member:mira".into()]), - CellAppraisalProposal { - actions: vec![CellActionCandidate { - subject_id: "member:mira".into(), - intent: "offer to help repair the shelter".into(), - intended_effect: "make the offer to the refugees".into(), - priority: 70, - state_references: vec!["member:mira".into()], - public_channels: vec![], - effects: CellEffectBundleCandidate { - member_activities: Some(CellActivitySetCandidate { - communicate: Some(vec![CellActivityScopeCandidate { - target_subject_ids: vec!["refugees".into()], - location_ids: vec!["forum".into()], - }]), - ..Default::default() - }), - ..Default::default() - }, - }], - inactions: vec![], - }, - ) - .unwrap(); - validate_cell_appraisal(&slice, &appraisal).unwrap(); - - let mut targetless_coordination = appraisal.clone(); - let StrategicCellEffect::MemberActivity { - activity, - target_subject_ids, - .. - } = &mut targetless_coordination.actions[0].effects[0] - else { - unreachable!() - }; - *activity = crate::domain::StrategicActivityKind::Coordinate; - target_subject_ids.clear(); - assert!(validate_cell_appraisal(&slice, &targetless_coordination).is_err()); - - let mut stolen = appraisal; - let StrategicCellEffect::MemberActivity { member_id, .. } = - &mut stolen.actions[0].effects[0] - else { - unreachable!() - }; - *member_id = "somebody-else".into(); - assert!(validate_cell_appraisal(&slice, &stolen).is_err()); - } - - #[test] - fn canonical_actor_activity_stays_attributed_to_the_actor() { - let mut slice = fixture_cell_slice(); - let subject = &mut slice.constituents[0]; - subject.subject_id = "actor:liaison".into(); - subject.subject_kind = AgencySubjectKind::Actor; - subject.name = "Liaison".into(); - subject.collective_authority_id = None; - subject.location_ids = BTreeSet::from(["forum".into()]); - subject.permitted_state_references = BTreeSet::from(["subject:actor:liaison".into()]); - subject.activity_targets = BTreeMap::from([( - "clinic".into(), - CellActivityTargetSlice { - name: "Clinic".into(), - locations: BTreeMap::from([("forum".into(), "Forum".into())]), - }, - )]); - subject.current_posture = None; - - let appraisal = bind_cell_appraisal( - &slice, - &BTreeSet::from(["actor:liaison".into()]), - CellAppraisalProposal { - actions: vec![CellActionCandidate { - subject_id: "actor:liaison".into(), - intent: "ask the clinic for its shortage count".into(), - intended_effect: "send the request without inventing a reply".into(), - priority: 70, - state_references: vec!["subject:actor:liaison".into()], - public_channels: vec![], - effects: CellEffectBundleCandidate { - actor_activities: Some(CellActivitySetCandidate { - communicate: Some(vec![CellActivityScopeCandidate { - target_subject_ids: vec!["clinic".into()], - location_ids: vec!["forum".into()], - }]), - ..Default::default() - }), - ..Default::default() - }, - }], - inactions: vec![], - }, - ) - .unwrap(); - validate_cell_appraisal(&slice, &appraisal).unwrap(); - assert!(matches!( - &appraisal.actions[0].effects[0], - StrategicCellEffect::ActorActivity { actor_id, .. } if actor_id == "actor:liaison" - )); - - let wrong_lane = bind_cell_appraisal( - &slice, - &BTreeSet::from(["actor:liaison".into()]), - CellAppraisalProposal { - actions: vec![CellActionCandidate { - subject_id: "actor:liaison".into(), - intent: "ask the clinic for its shortage count".into(), - intended_effect: "send the request without inventing a reply".into(), - priority: 70, - state_references: vec!["subject:actor:liaison".into()], - public_channels: vec![], - effects: CellEffectBundleCandidate { - member_activities: Some(CellActivitySetCandidate { - communicate: Some(vec![CellActivityScopeCandidate { - target_subject_ids: vec!["clinic".into()], - location_ids: vec!["forum".into()], - }]), - ..Default::default() - }), - ..Default::default() - }, - }], - inactions: vec![], - }, - ) - .unwrap_err(); - assert!( - wrong_lane - .to_string() - .contains("is not a selected member exception") - ); - } - - #[test] - fn actor_can_compose_exact_travel_and_destination_activity() { - let mut slice = fixture_cell_slice(); - let subject = &mut slice.constituents[0]; - subject.subject_id = "actor:director".into(); - subject.subject_kind = AgencySubjectKind::Actor; - subject.name = "Clinic Director".into(); - subject.collective_authority_id = None; - subject.location_ids = BTreeSet::from(["garrison".into()]); - subject.reachable_destinations = - BTreeMap::from([("encampment".into(), "Refugee Encampment".into())]); - subject.permitted_state_references = - BTreeSet::from(["subject:actor:director".into(), "location:garrison".into()]); - subject.activity_targets = BTreeMap::from([ - ( - "workers".into(), - CellActivityTargetSlice { - name: "Kiln Hands".into(), - locations: BTreeMap::from([("garrison".into(), "Garrison".into())]), - }, - ), - ( - "board".into(), - CellActivityTargetSlice { - name: "Water Board".into(), - locations: BTreeMap::from([("encampment".into(), "Refugee Encampment".into())]), - }, - ), - ]); - subject.current_posture = None; - - let proposal = bind_cell_appraisal( - &slice, - &BTreeSet::from(["actor:director".into()]), - CellAppraisalProposal { - actions: vec![CellActionCandidate { - subject_id: "actor:director".into(), - intent: "travel to the encampment and ask what supplies are needed".into(), - intended_effect: "arrive there and make the request without inventing a reply" - .into(), - priority: 70, - state_references: vec!["subject:actor:director".into()], - public_channels: vec![], - effects: CellEffectBundleCandidate { - actor_move: Some(CellActorMoveEffectCandidate { - destination_id: "encampment".into(), - }), - actor_activities: Some(CellActivitySetCandidate { - communicate: Some(vec![ - CellActivityScopeCandidate { - target_subject_ids: vec!["workers".into()], - location_ids: vec!["garrison".into()], - }, - CellActivityScopeCandidate { - target_subject_ids: vec!["board".into()], - location_ids: vec!["encampment".into()], - }, - ]), - ..Default::default() - }), - ..Default::default() - }, - }], - inactions: vec![], - }, - ) - .unwrap(); - validate_cell_appraisal(&slice, &proposal).unwrap(); - assert_eq!(proposal.actions[0].effects.len(), 3); - - let mut omitted_travel = proposal; - omitted_travel.actions[0].effects.remove(0); - assert!(validate_cell_appraisal(&slice, &omitted_travel).is_err()); - } - - #[test] - fn repeated_institution_posture_reports_the_exact_missing_change() { - let slice = fixture_cell_slice(); - let error = validate_constituent_effect( - &slice.constituents[0], - &StrategicCellEffect::Institution { - institution_id: "faction-06".into(), - posture: "weighing whether to publish a position".into(), - location_ids: vec!["forum".into()], - }, - None, - ) - .unwrap_err(); - assert!(error.to_string().contains("exact current posture")); - assert!( - error - .to_string() - .contains("weighing whether to publish a position") - ); - let projector_context = cell_projector_context(&slice); - assert_eq!( - projector_context["constituents"][0]["already_committed_posture"], - "weighing whether to publish a position" - ); - assert!(projector_context["constituents"][0]["current_posture"].is_null()); - assert_eq!( - projector_context["constituents"][0]["pressures"][0], - "the vote is near" - ); - - validate_constituent_effect( - &slice.constituents[0], - &StrategicCellEffect::Institution { - institution_id: "faction-06".into(), - posture: "x".repeat(crate::domain::MAX_POSTURE_CHARS), - location_ids: vec!["forum".into()], - }, - None, - ) - .unwrap(); - let error = validate_constituent_effect( - &slice.constituents[0], - &StrategicCellEffect::Institution { - institution_id: "faction-06".into(), - posture: "x".repeat(crate::domain::MAX_POSTURE_CHARS + 1), - location_ids: vec!["forum".into()], - }, - None, - ) - .unwrap_err(); - assert!(error.to_string().contains("exact maximum is 460")); - } - - struct CausalFixtureModel { - request_sources: Mutex)>>, - } - - #[async_trait] - impl ModelPort for CausalFixtureModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.request_sources - .lock() - .unwrap() - .push((request.stage.clone(), request.source_receipt_ids.clone())); - FixtureModel.run(request).await - } - - fn provider(&self) -> &'static str { - "causal-fixture" - } - } - - #[tokio::test] - async fn persona_receives_only_projected_stream() { - let model = Arc::new(CausalFixtureModel { - request_sources: Mutex::new(Vec::new()), - }); - let engine = PersonaProjectionEngine { - model: model.clone(), - permit: Arc::new(AllowAllPermit), - projector_model: "flash".into(), - persona_model: "pro".into(), - interpreter_model: "flash".into(), - }; - let slice = PermittedActorSlice { - actor_id: "npc".into(), - location_id: "room".into(), - subject_kind: PersonaSubjectKind::IndividualActor, - snapshot_binding: "campaign:1".into(), - interaction_role: ActorInteractionRole::PresentObserver, - identity_experience: vec!["A tired navigator".into()], - reserved_public_identities: BTreeSet::new(), - memories: vec!["Proposed the eastern trail evacuation at dusk.".into()], - recent_self_authored_turns: vec![ - "At world revision 3, your committed public response was exactly: Use the eastern trail.".into(), - ], - perceived_events: vec![], - perceived_actors: std::collections::BTreeMap::from([( - "player".into(), - "Player".into(), - )]), - relationships: vec![], - goals: vec![], - knowledge: vec![], - capabilities: vec![], - pressures: vec![], - affordances: vec![], - source_receipt_ids: vec![], - }; - let guidance = actor_interpreter_guidance(&slice); - assert!(guidance.contains("other actor retains agency")); - assert!(guidance.contains("requested response remains unresolved")); - let grounded = ground_actor_lived_stream(&slice, "The crowd turns toward you."); - assert!(grounded.contains("Your active self-identity: A tired navigator")); - assert!(grounded.contains("What you remember experiencing or being told")); - assert!(grounded.contains("Proposed the eastern trail evacuation at dusk.")); - assert!(grounded.contains("Use the eastern trail.")); - assert!(grounded.contains("does not prove that the content")); - assert!(grounded.contains("not omniscient proof")); - let result = engine.execute(slice).await.unwrap(); - assert_eq!(result.stage_receipts.len(), 3); - assert_eq!(result.proposals.reaction_priority, 0); - let receipt_ids = result - .stage_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - let request_sources = model.request_sources.lock().unwrap(); - let persona_sources = request_sources - .iter() - .find(|(stage, _)| stage == "persona") - .map(|(_, sources)| sources) - .unwrap(); - let interpreter_sources = request_sources - .iter() - .find(|(stage, _)| stage == "interpreter") - .map(|(_, sources)| sources) - .unwrap(); - assert!(persona_sources.contains(&receipt_ids[0])); - assert!(interpreter_sources.contains(&receipt_ids[0])); - assert!(interpreter_sources.contains(&receipt_ids[1])); - } - - #[test] - fn persona_identity_adoption_must_be_spoken_exactly() { - let mut slice = PermittedActorSlice { - actor_id: "npc".into(), - location_id: "room".into(), - subject_kind: PersonaSubjectKind::IndividualActor, - snapshot_binding: "campaign:1".into(), - interaction_role: ActorInteractionRole::DirectResponseExpected, - identity_experience: vec!["You are an unnamed patient.".into()], - reserved_public_identities: BTreeSet::new(), - memories: vec![], - recent_self_authored_turns: vec![], - perceived_events: vec!["The player asks your name.".into()], - perceived_actors: BTreeMap::from([("player".into(), "Player".into())]), - relationships: vec![], - goals: vec![], - knowledge: vec![], - capabilities: vec![], - pressures: vec![], - affordances: vec![], - source_receipt_ids: vec![], - }; - let mut proposals = PersonaProposalBundle { - private_delta: crate::domain::ActorStateDelta { - identity_adoption: Some("Taren".into()), - ..Default::default() - }, - speech: Some("Call me Rook.".into()), - deliberate_silence: false, - reaction_priority: 0, - world_actions: vec![], - }; - assert!( - validate_actor_proposals(&slice, &proposals) - .unwrap_err() - .to_string() - .contains("exact spoken handle") - ); - proposals.speech = Some("My name is Taren.".into()); - validate_actor_proposals(&slice, &proposals).unwrap(); - slice.reserved_public_identities.insert(" tArEn ".into()); - assert!( - validate_actor_proposals(&slice, &proposals) - .unwrap_err() - .to_string() - .contains("established peer identity") - ); - } - - #[test] - fn actor_interpreter_schema_forbids_silent_identity_adoption() { - let slice = PermittedActorSlice { - actor_id: "npc".into(), - location_id: "room".into(), - subject_kind: PersonaSubjectKind::IndividualActor, - snapshot_binding: "campaign:1".into(), - interaction_role: ActorInteractionRole::PresentObserver, - identity_experience: vec!["You are an unnamed patient.".into()], - reserved_public_identities: BTreeSet::new(), - memories: vec![], - recent_self_authored_turns: vec![], - perceived_events: vec!["A regulator is inspected.".into()], - perceived_actors: BTreeMap::from([("player".into(), "Player".into())]), - relationships: vec![], - goals: vec![], - knowledge: vec![], - capabilities: vec![], - pressures: vec![], - affordances: vec![], - source_receipt_ids: vec![], - }; - let mut schema = serde_json::to_value(schema_for!(PersonaProposalBundle)).unwrap(); - constrain_interpreter_schema(&mut schema, &slice).unwrap(); - let validator = jsonschema::validator_for(&schema).unwrap(); - let silent_adoption = serde_json::to_value(PersonaProposalBundle { - private_delta: crate::domain::ActorStateDelta { - identity_adoption: Some("Taren".into()), - ..Default::default() - }, - speech: None, - deliberate_silence: false, - reaction_priority: 0, - world_actions: vec![], - }) - .unwrap(); - assert!(!validator.is_valid(&silent_adoption)); - } - - struct CorrectingActorModel { - interpreter_calls: AtomicUsize, - saw_rejected_interpretation: AtomicBool, - } - - #[async_trait] - impl ModelPort for CorrectingActorModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - match request.stage.as_str() { - "projector" => Ok("The player asks you to identify yourself.".into()), - "persona" => Ok("My name is Taren.".into()), - "interpreter" => { - let correction = self.interpreter_calls.fetch_add(1, Ordering::SeqCst) > 0; - if correction { - self.saw_rejected_interpretation.store( - request - .lived_stream - .contains("PREVIOUS_REJECTED_INTERPRETATION") - && request.lived_stream.contains("Rook") - && request.lived_stream.contains("exact spoken handle"), - Ordering::SeqCst, - ); - } - Ok(serde_json::to_string(&PersonaProposalBundle { - private_delta: crate::domain::ActorStateDelta { - identity_adoption: Some( - if correction { "Taren" } else { "Rook" }.into(), - ), - ..Default::default() - }, - speech: Some("My name is Taren.".into()), - deliberate_silence: false, - reaction_priority: 10, - world_actions: vec![], - })?) - } - stage => Err(anyhow!("unexpected fixture stage {stage}")), - } - } - - fn provider(&self) -> &'static str { - "correcting-actor-fixture" - } - } - - #[tokio::test] - async fn actor_semantic_retry_preserves_same_snapshot_and_receipts() { - let model = Arc::new(CorrectingActorModel { - interpreter_calls: AtomicUsize::new(0), - saw_rejected_interpretation: AtomicBool::new(false), - }); - let engine = PersonaProjectionEngine { - model: model.clone(), - permit: Arc::new(AllowAllPermit), - projector_model: "flash".into(), - persona_model: "pro".into(), - interpreter_model: "flash".into(), - }; - let output = engine - .execute(PermittedActorSlice { - actor_id: "npc".into(), - location_id: "room".into(), - subject_kind: PersonaSubjectKind::IndividualActor, - snapshot_binding: "campaign:1:revision:4".into(), - interaction_role: ActorInteractionRole::DirectResponseExpected, - identity_experience: vec!["You are an unnamed patient.".into()], - reserved_public_identities: BTreeSet::new(), - memories: vec![], - recent_self_authored_turns: vec![], - perceived_events: vec!["The player asks your name.".into()], - perceived_actors: BTreeMap::from([("player".into(), "Player".into())]), - relationships: vec![], - goals: vec![], - knowledge: vec![], - capabilities: vec![], - pressures: vec![], - affordances: vec![], - source_receipt_ids: vec![], - }) - .await - .unwrap(); - assert!(model.saw_rejected_interpretation.load(Ordering::SeqCst)); - assert_eq!(output.stage_receipts.len(), 4); - assert_eq!( - output.stage_receipts[2].validation_result, - "semantic_invalid" - ); - assert_eq!( - output.proposals.private_delta.identity_adoption.as_deref(), - Some("Taren") - ); - } - - #[test] - fn cell_guidance_preserves_attribution_and_ends_on_a_decision() { - let arena_projector = cell_projector_mode_guidance(&SimulationCellMode::Arena); - let arena_persona = cell_persona_mode_guidance(&SimulationCellMode::Arena); - let cohesive_persona = cell_persona_mode_guidance(&SimulationCellMode::Cohesive); - assert!(arena_projector.contains("Name each subject")); - assert!(arena_projector.contains("never use an unmarked first-person voice")); - assert!(arena_projector.contains("remote locations")); - assert!(arena_projector.contains("never stage shared sight, speech, or response")); - assert!(arena_persona.contains("Name the constituent")); - assert!(arena_persona.contains("present-tense choice")); - assert!(arena_persona.contains("simultaneous remote scenes")); - assert!(arena_persona.contains("preserve every stated location boundary")); - assert!(arena_persona.contains("merely observed or mentioned remain external")); - assert!(arena_persona.contains("cannot claim contact")); - assert!(cohesive_persona.contains("present-tense choice")); - assert!(cohesive_persona.contains("asking for a future decision")); - } - - #[test] - fn cell_priority_schema_uses_a_bounded_higher_wins_score() { - let mut schema = serde_json::to_value(schema_for!(CellAppraisalProposal)).unwrap(); - constrain_cell_proposal_schema( - &mut schema, - &fixture_cell_slice(), - &BTreeSet::from(["faction-06".into()]), - ) - .unwrap(); - assert_eq!( - schema.pointer("/properties/decisions/properties/faction-06/anyOf/0/properties/action/properties/priority/minimum"), - Some(&serde_json::json!(0)) - ); - assert_eq!( - schema.pointer("/properties/decisions/properties/faction-06/anyOf/0/properties/action/properties/priority/maximum"), - Some(&serde_json::json!(100)) - ); - } - - #[test] - fn activity_schema_omits_relation_dependent_choices_without_an_exact_target() { - let no_target = exact_activity_effects_schema( - &BTreeSet::new(), - &BTreeSet::from(["village".into()]), - 0, - false, - ); - let no_target_properties = no_target["properties"].as_object().unwrap(); - assert_eq!( - no_target_properties - .keys() - .map(String::as_str) - .collect::>(), - BTreeSet::from(["communicate", "investigate", "obstruct", "prepare"]) - ); - - let exact_target = exact_activity_effects_schema( - &BTreeSet::from(["refugee-convoy".into()]), - &BTreeSet::from(["village".into()]), - 0, - false, - ); - let exact_target_properties = exact_target["properties"].as_object().unwrap(); - assert!(exact_target_properties.contains_key("coordinate")); - assert!(exact_target_properties.contains_key("recruit")); - assert!(exact_target_properties.contains_key("trade")); - } - - #[test] - fn cohesive_gestalt_activity_can_coordinate_its_own_unnamed_members() { - let schema = exact_activity_effects_schema( - &BTreeSet::new(), - &BTreeSet::from(["village".into()]), - 0, - true, - ); - let validator = jsonschema::validator_for(&schema).unwrap(); - - assert!(validator.is_valid(&serde_json::json!({ - "coordinate":[{ - "target_subject_ids":[], - "location_ids":["village"] - }] - }))); - assert!(!validator.is_valid(&serde_json::json!({ - "coordinate":[{ - "target_subject_ids":["unadmitted-external-population"], - "location_ids":["village"] - }] - }))); - } - - #[test] - fn cell_projection_binds_exact_unique_perspective_owners_into_prose() { - let slice = fixture_cell_slice(); - let (narrative, active_subject_ids) = bind_cell_projection( - &slice, - CellProjectionProposal { - segments: vec![CellPerspectiveSegment { - subject_id: "faction-06".into(), - narrative: "The deadline presses against our undecided mandate.".into(), - }], - }, - ) - .unwrap(); - assert!(narrative.contains("Faction Six — at forum")); - assert!(narrative.contains("Faction Six's grounded agency")); - assert!(narrative.contains("No distinct travel destination is presently established")); - assert!(narrative.contains("No named distant person or body is presently available")); - assert!( - narrative - .contains("established channels for publishing an attempt are: public bulletin") - ); - assert!(!narrative.contains("faction-06")); - assert_eq!(active_subject_ids, BTreeSet::from(["faction-06".into()])); - - let invented = bind_cell_projection( - &slice, - CellProjectionProposal { - segments: vec![CellPerspectiveSegment { - subject_id: "mentioned-outsider".into(), - narrative: "I take over the scene.".into(), - }], - }, - ) - .unwrap_err(); - assert!(invented.to_string().contains("invented or duplicated")); - - let mut duplicate_slice = slice.clone(); - duplicate_slice.max_actions = 2; - let duplicate = bind_cell_projection( - &duplicate_slice, - CellProjectionProposal { - segments: vec![ - CellPerspectiveSegment { - subject_id: "faction-06".into(), - narrative: "First voice.".into(), - }, - CellPerspectiveSegment { - subject_id: "faction-06".into(), - narrative: "Second voice.".into(), - }, - ], - }, - ) - .unwrap_err(); - assert!(duplicate.to_string().contains("invented or duplicated")); - } - - #[test] - fn projected_actor_receives_exact_lived_travel_and_contact_footing() { - let mut slice = fixture_cell_slice(); - let actor = &mut slice.constituents[0]; - actor.subject_kind = AgencySubjectKind::Actor; - actor.name = "Clinic Director".into(); - actor.information_channels.clear(); - actor.reachable_destinations = - BTreeMap::from([("junction".into(), "Kostolom Junction".into())]); - actor.activity_targets = BTreeMap::from([( - "commander".into(), - CellActivityTargetSlice { - name: "Commander Voss".into(), - locations: BTreeMap::from([("junction".into(), "Kostolom Junction".into())]), - }, - )]); - let (narrative, _) = bind_cell_projection( - &slice, - CellProjectionProposal { - segments: vec![CellPerspectiveSegment { - subject_id: "faction-06".into(), - narrative: "The clinic's needs still press for an answer.".into(), - }], - }, - ) - .unwrap(); - - assert!(narrative.contains("choose to travel to are: Kostolom Junction")); - assert!(narrative.contains("try to reach are: Commander Voss at Kostolom Junction")); - assert!(narrative.contains("Somewhere else would first require finding a route")); - assert!(narrative.contains("no established channel for publishing this attempt")); - } - - #[test] - fn projected_subjects_are_the_only_persona_and_interpreter_decision_owners() { - let mut slice = fixture_cell_slice(); - let mut inactive = slice.constituents[0].clone(); - inactive.subject_id = "faction-07".into(); - inactive.name = "Faction Seven".into(); - slice.constituents.push(inactive); - slice.max_actions = 2; - let active = BTreeSet::from(["faction-06".into()]); - - let boundaries = cell_scene_boundaries(&slice, &active); - assert!(boundaries.contains("Faction Six")); - assert!(!boundaries.contains("Faction Seven")); - let context = cell_interpreter_context(&slice, &active); - let projector_context = cell_projector_context(&slice); - assert_eq!(projector_context["canonical_locations"]["forum"], "Forum"); - assert_eq!(context["canonical_locations"]["forum"], "Forum"); - assert_eq!(context["exact_permissions"].as_array().unwrap().len(), 1); - assert_eq!(context["exact_permissions"][0]["subject_id"], "faction-06"); - - let mut schema = serde_json::to_value(schema_for!(CellAppraisalProposal)).unwrap(); - constrain_cell_proposal_schema(&mut schema, &slice, &active).unwrap(); - assert_eq!( - schema - .pointer("/properties/decisions/properties/faction-06/anyOf/0/properties/action/properties/subject_id/const") - .unwrap(), - &serde_json::json!("faction-06") - ); - } - - #[test] - fn cell_projection_must_include_the_debt_selected_subject() { - let mut slice = fixture_cell_slice(); - let mut other = slice.constituents[0].clone(); - other.subject_id = "faction-07".into(); - other.name = "Faction Seven".into(); - slice.constituents.push(other); - slice.detail_focus_subject_id = Some("faction-06".into()); - let error = bind_cell_projection( - &slice, - CellProjectionProposal { - segments: vec![CellPerspectiveSegment { - subject_id: "faction-07".into(), - narrative: "Our own horizon remains quiet.".into(), - }], - }, - ) - .unwrap_err(); - assert!(error.to_string().contains("required perspective owner")); - } - - #[test] - fn cell_projection_cannot_erase_a_selected_member_exception() { - let mut slice = fixture_cell_slice(); - slice.max_actions = 2; - slice.decision_owner_ids.insert("member:mira".into()); - slice.member_exceptions.push(CellMemberSlice { - subject_id: "member:mira".into(), - member_id: "mira".into(), - name: "Mira".into(), - source_gestalt_id: "refugees".into(), - source_location_id: "forum".into(), - knowledge: BTreeSet::new(), - capabilities: BTreeSet::new(), - resources: BTreeSet::new(), - information_channels: BTreeSet::new(), - permitted_state_references: BTreeSet::from(["member:mira".into()]), - migration_destinations: BTreeMap::new(), - activity_targets: BTreeMap::new(), - goals: vec!["choose whether to leave".into()], - pressures: vec!["the final ferry is boarding".into()], - relationships: BTreeMap::new(), - memories: vec![], - }); - - let error = bind_cell_projection( - &slice, - CellProjectionProposal { - segments: vec![CellPerspectiveSegment { - subject_id: "faction-06".into(), - narrative: "The institution watches the ferry clock.".into(), - }], - }, - ) - .unwrap_err(); - - assert!(error.to_string().contains("member:mira")); - } -} - -fn allowed_actor_references(slice: &PermittedActorSlice) -> Vec { - slice - .capabilities - .iter() - .map(|value| format!("capability:{value}")) - .chain( - slice - .knowledge - .iter() - .map(|value| format!("knowledge:{value}")), - ) - .chain( - slice - .affordances - .iter() - .map(|value| format!("equipment:{value}")), - ) - .chain(std::iter::once(format!("location:{}", slice.location_id))) - .collect() -} diff --git a/crates/ghostlight-dungeon/src/registry.rs b/crates/ghostlight-dungeon/src/registry.rs deleted file mode 100644 index 312c8cd..0000000 --- a/crates/ghostlight-dungeon/src/registry.rs +++ /dev/null @@ -1,1821 +0,0 @@ -use crate::{ - consumer::{ - ExternalProposalAcknowledgement, ExternalProposalList, ExternalProposalListRequest, - ExternalProposalReceipt, ExternalProposalStatus, ExternalSubjectAuthority, - ExternalWorldProposal, WorldNewspaperRequest, WorldSeed, WorldSeedAdmission, - WorldSeedAdmissionReceipt, WorldSeedAdmissionRequest, WorldSeedProducerKind, - validate_authority_key, validate_seed_admission, - }, - domain::{Campaign, CampaignLifecycleReceipt, VaultEvidenceReceipt}, - kernel::WorldKernel, - model::{ModelPort, ModelStageReceipt}, - persistence::CampaignStore, - session_zero::PublishedSessionZeroSeed, -}; -use anyhow::{Result, anyhow}; -use chrono::Utc; -use std::{ - collections::BTreeMap, - fs, - path::{Path, PathBuf}, - sync::Arc, -}; -use tokio::sync::RwLock; -use uuid::Uuid; - -#[derive(Clone)] -pub struct CampaignRuntime { - pub store: CampaignStore, - pub kernel: WorldKernel, -} - -#[derive(Clone)] -pub struct CampaignRegistry { - root: PathBuf, - runtimes: Arc>>, -} - -impl CampaignRegistry { - pub fn new(root: impl AsRef) -> Result { - let root = root.as_ref().to_path_buf(); - fs::create_dir_all(&root)?; - Ok(Self { - root, - runtimes: Arc::new(RwLock::new(BTreeMap::new())), - }) - } - - pub async fn load_existing(&self) -> Result<()> { - let mut found = BTreeMap::new(); - for entry in fs::read_dir(&self.root)? { - let entry = entry?; - let Ok(id) = Uuid::parse_str(&entry.file_name().to_string_lossy()) else { - continue; - }; - let path = entry.path().join("campaign.cc"); - if !path.is_file() { - continue; - } - let store = CampaignStore::open(path)?; - let keys = store.keys("campaign.v1")?; - if keys.len() != 1 { - return Err(anyhow!("campaign store must contain exactly one campaign")); - } - if keys[0] != id.to_string() { - return Err(anyhow!("campaign directory and stored id disagree")); - } - let (row, mut campaign) = store - .load::("campaign.v1", &keys[0])? - .ok_or_else(|| anyhow!("campaign row vanished during migration"))?; - let before = campaign.clone(); - let normalized_member_identities = - crate::resolution::normalize_legacy_gestalt_member_identities(&mut campaign)?; - crate::resolution::ensure_agency_profiles(&mut campaign); - if campaign != before { - let previous_resolution_epoch = campaign.resolution_policy.resolution_epoch; - campaign.resolution_policy.resolution_epoch = - previous_resolution_epoch.saturating_add(1); - campaign.resolution_cover = None; - store.append_resolution_control( - &row, - &campaign, - &crate::domain::ResolutionControlReceipt { - schema: "ghostlight.resolution_control_receipt.v1".into(), - campaign_id: campaign.id, - world_revision: campaign.revision, - previous_resolution_epoch, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - provider_configuration_epoch: campaign - .resolution_policy - .provider_configuration_epoch, - operation: if normalized_member_identities { - "normalize_gestalt_member_identity".into() - } else { - "migrate_flat_agency_state".into() - }, - active_cell_budget: campaign.resolution_policy.active_cell_budget, - pin_ids: campaign.resolution_pins.keys().cloned().collect(), - committed_at: Utc::now(), - }, - )?; - } - found.insert( - id, - CampaignRuntime { - kernel: WorldKernel::start(store.clone()), - store, - }, - ); - } - *self.runtimes.write().await = found; - Ok(()) - } - - pub async fn runtime(&self, id: Uuid) -> Result { - self.runtimes - .read() - .await - .get(&id) - .cloned() - .ok_or_else(|| anyhow!("campaign runtime is not loaded")) - } - - pub async fn list(&self) -> Vec { - self.runtimes.read().await.keys().copied().collect() - } - - #[doc(hidden)] - pub async fn create_unadmitted_fixture( - &self, - campaign: Campaign, - evidence: Vec, - model_receipts: Vec, - ) -> Result { - self.create_with_lifecycle(campaign, evidence, model_receipts, None) - .await - } - - pub async fn publish_session_zero( - &self, - mut campaign: Campaign, - evidence: Vec, - model_receipts: Vec, - publication: PublishedSessionZeroSeed, - ) -> Result { - crate::resolution::ensure_agency_profiles(&mut campaign); - crate::compiler::validate_campaign_seed(&campaign)?; - if publication - .membership - .controlled_actor_ids() - .iter() - .any(|actor_id| { - !campaign.actors.contains_key(actor_id) - || campaign - .agency_profiles - .get(actor_id) - .is_none_or(|profile| profile.simulation_eligible) - }) - { - return Err(anyhow!( - "every campaign member must bind an existing human-protected actor" - )); - } - let seed = WorldSeed::from_campaign(&campaign)?; - let admission = WorldSeedAdmission { - schema: "ghostlight.world_seed_admission.v1".into(), - campaign_id: campaign.id, - producer_id: format!("session-zero:{}", publication.session_zero_id), - producer_kind: WorldSeedProducerKind::Compiler, - seed_digest: seed.digest()?, - idempotency_key: publication.approved_seed_digest.clone(), - external_subjects: Vec::new(), - }; - self.admit_seed( - seed, - admission, - "", - evidence, - model_receipts, - Some(publication), - ) - .await - .map(|(runtime, _)| runtime) - } - - pub async fn admit_world_seed( - &self, - request: WorldSeedAdmissionRequest, - ) -> Result<(CampaignRuntime, WorldSeedAdmissionReceipt)> { - if request.schema != "ghostlight.world_seed_admission_request.v1" { - return Err(anyhow!("world seed admission request schema is invalid")); - } - self.admit_seed( - request.seed, - request.admission, - &request.authority_key, - Vec::new(), - Vec::new(), - None, - ) - .await - } - - async fn admit_seed( - &self, - seed: WorldSeed, - admission: WorldSeedAdmission, - authority_key: &str, - evidence: Vec, - model_receipts: Vec, - publication: Option, - ) -> Result<(CampaignRuntime, WorldSeedAdmissionReceipt)> { - let campaign = validate_seed_admission(&seed, &admission, authority_key)?; - let receipt = WorldSeedAdmissionReceipt { - schema: "ghostlight.world_seed_admission_receipt.v1".into(), - campaign_id: campaign.id, - producer_id: admission.producer_id.clone(), - seed_digest: admission.seed_digest.clone(), - idempotency_key: admission.idempotency_key.clone(), - admitted_subject_ids: admission - .external_subjects - .iter() - .map(|item| item.subject_id.clone()) - .collect(), - admitted_at: Utc::now(), - }; - if let Some(existing) = self.open_existing_admission(&admission).await? { - return Ok(existing); - } - let directory = self.root.join(campaign.id.to_string()); - if directory.exists() { - return Err(anyhow!( - "campaign directory belongs to another admitted seed" - )); - } - let staging = self - .root - .join(format!(".creating-{}-{}", campaign.id, Uuid::new_v4())); - fs::create_dir(&staging)?; - let prepared = (|| -> Result<()> { - let store = CampaignStore::open(staging.join("campaign.cc"))?; - store.create_admitted_campaign( - &campaign, - &evidence, - &model_receipts, - &admission, - &receipt, - publication.as_ref(), - )?; - drop(store); - fs::rename(&staging, &directory)?; - Ok(()) - })(); - if let Err(error) = prepared { - cleanup_staging_directory(&self.root, &staging); - return Err(error); - } - let store = CampaignStore::open(directory.join("campaign.cc"))?; - let runtime = CampaignRuntime { - kernel: WorldKernel::start(store.clone()), - store, - }; - self.runtimes - .write() - .await - .insert(campaign.id, runtime.clone()); - Ok((runtime, receipt)) - } - - async fn open_existing_admission( - &self, - admission: &WorldSeedAdmission, - ) -> Result> { - let runtime = if let Ok(runtime) = self.runtime(admission.campaign_id).await { - Some(runtime) - } else { - let directory = self.root.join(admission.campaign_id.to_string()); - if !directory.exists() { - None - } else { - let store = CampaignStore::open(directory.join("campaign.cc"))?; - Some(CampaignRuntime { - kernel: WorldKernel::start(store.clone()), - store, - }) - } - }; - let Some(runtime) = runtime else { - return Ok(None); - }; - let stored = runtime - .store - .load::( - "world_seed_admission.v1", - &admission.campaign_id.to_string(), - )? - .map(|(_, value)| value); - let stored_receipt = runtime - .store - .load::( - "world_seed_admission_receipt.v1", - &admission.campaign_id.to_string(), - )? - .map(|(_, value)| value); - match (stored, stored_receipt) { - (Some(stored), Some(receipt)) if stored == *admission => { - self.runtimes - .write() - .await - .insert(admission.campaign_id, runtime.clone()); - Ok(Some((runtime, receipt))) - } - _ => Err(anyhow!("campaign id is already admitted from another seed")), - } - } - - pub async fn apply_external_subject_snapshot( - &self, - snapshot: crate::consumer::ExternalSubjectSnapshot, - ) -> Result { - let runtime = self.runtime(snapshot.campaign_id).await?; - match runtime - .kernel - .command(crate::domain::WorldCommand::ApplyExternalSubjectSnapshot { snapshot }) - .await - .map_err(|error| anyhow!(error.to_string()))? - { - crate::kernel::CommandResult::ExternalSnapshotCommitted { receipt, .. } => Ok(receipt), - _ => Err(anyhow!( - "kernel returned the wrong external snapshot result" - )), - } - } - - pub async fn list_external_proposals( - &self, - request: ExternalProposalListRequest, - ) -> Result { - if request.schema != "ghostlight.external_proposal_list_request.v1" { - return Err(anyhow!("external proposal list request schema is invalid")); - } - let runtime = self.runtime(request.campaign_id).await?; - let (_, authority) = runtime - .store - .load::( - "external_subject_authority.v1", - &request.authority_id, - )? - .ok_or_else(|| anyhow!("external subject authority is unknown"))?; - if authority.campaign_id != request.campaign_id || authority.owner_id != request.owner_id { - return Err(anyhow!( - "external proposal request does not match its authority" - )); - } - validate_authority_key(&authority, &request.authority_key)?; - let receipts = runtime - .store - .load_all::("external_proposal_receipt.v1")?; - let acknowledged: std::collections::BTreeSet<_> = receipts - .into_iter() - .map(|receipt| receipt.proposal_id) - .collect(); - let proposals = runtime - .store - .load_all::("external_world_proposal.v1")? - .into_iter() - .filter(|proposal| { - proposal.authority_id == request.authority_id - && !acknowledged.contains(&proposal.id) - }) - .collect(); - Ok(ExternalProposalList { - schema: "ghostlight.external_proposal_list.v1".into(), - campaign_id: request.campaign_id, - authority_id: request.authority_id, - proposals, - }) - } - - pub async fn compose_world_newspaper( - &self, - request: WorldNewspaperRequest, - model: &dyn ModelPort, - ) -> Result { - if request.schema != "ghostlight.world_newspaper_request.v3" - || request.max_articles == 0 - || request.max_articles > 6 - || request.editorial_voice.trim().is_empty() - || request.editorial_voice.trim() != request.editorial_voice - || request.editorial_voice.chars().count() > 600 - { - return Err(anyhow!("world newspaper request is invalid")); - } - let runtime = self.runtime(request.campaign_id).await?; - let (_, authority) = runtime - .store - .load::( - "external_subject_authority.v1", - &request.authority_id, - )? - .ok_or_else(|| anyhow!("external subject authority is unknown"))?; - if authority.campaign_id != request.campaign_id || authority.owner_id != request.owner_id { - return Err(anyhow!( - "world newspaper request does not match its authority" - )); - } - validate_authority_key(&authority, &request.authority_key)?; - let campaign = runtime - .store - .load::("campaign.v1", &request.campaign_id.to_string())? - .ok_or_else(|| anyhow!("campaign is missing"))? - .1; - crate::newspaper::advance_world_newspaper( - model, - &campaign, - request.title, - request.editorial_voice, - &request.newsroom, - usize::from(request.max_articles), - &runtime.store, - ) - .await - } - - pub async fn acknowledge_external_proposal( - &self, - acknowledgement: ExternalProposalAcknowledgement, - ) -> Result { - if acknowledgement.schema != "ghostlight.external_proposal_acknowledgement.v1" - || acknowledgement.status == ExternalProposalStatus::Pending - || acknowledgement.idempotency_key.trim().is_empty() - || acknowledgement.result_summary.trim().is_empty() - || acknowledgement.result_summary.chars().count() > 1000 - { - return Err(anyhow!("external proposal acknowledgement is invalid")); - } - let runtime = self.runtime(acknowledgement.campaign_id).await?; - let (_, authority) = runtime - .store - .load::( - "external_subject_authority.v1", - &acknowledgement.authority_id, - )? - .ok_or_else(|| anyhow!("external subject authority is unknown"))?; - if authority.owner_id != acknowledgement.owner_id { - return Err(anyhow!( - "external acknowledgement does not match its authority" - )); - } - validate_authority_key(&authority, &acknowledgement.authority_key)?; - let (_, proposal) = runtime - .store - .load::( - "external_world_proposal.v1", - &acknowledgement.proposal_id, - )? - .ok_or_else(|| anyhow!("external proposal is unknown"))?; - if proposal.authority_id != acknowledgement.authority_id - || proposal.campaign_id != acknowledgement.campaign_id - { - return Err(anyhow!("external proposal belongs to another authority")); - } - runtime - .store - .record_external_proposal_receipt(&ExternalProposalReceipt { - schema: "ghostlight.external_proposal_receipt.v1".into(), - campaign_id: acknowledgement.campaign_id, - authority_id: acknowledgement.authority_id, - proposal_id: acknowledgement.proposal_id, - idempotency_key: acknowledgement.idempotency_key, - status: acknowledgement.status, - result_summary: acknowledgement.result_summary, - acknowledged_at: acknowledgement.acknowledged_at, - }) - } - - async fn create_with_lifecycle( - &self, - mut campaign: Campaign, - evidence: Vec, - model_receipts: Vec, - additional_lifecycle: Option, - ) -> Result { - crate::resolution::ensure_agency_profiles(&mut campaign); - if self.runtimes.read().await.contains_key(&campaign.id) { - return Err(anyhow!("campaign already exists")); - } - let directory = self.root.join(campaign.id.to_string()); - if directory.exists() { - return Err(anyhow!("campaign directory already exists")); - } - let staging = self - .root - .join(format!(".creating-{}-{}", campaign.id, Uuid::new_v4())); - fs::create_dir(&staging)?; - let prepared = (|| -> Result<()> { - let store = CampaignStore::open(staging.join("campaign.cc"))?; - WorldKernel::initialize_campaign( - &store, - crate::domain::WorldCommand::CreateCampaign { - campaign: campaign.clone(), - evidence_receipts: evidence, - model_stage_receipts: model_receipts, - }, - ) - .map_err(|error| anyhow!(error.to_string()))?; - if let Some(receipt) = &additional_lifecycle { - store.insert( - "campaign_lifecycle_receipt.v1", - "ghostlight.campaign_lifecycle_receipt.v1", - &format!("{}:{}", receipt.campaign_id, receipt.operation), - receipt, - )?; - } - drop(store); - fs::rename(&staging, &directory)?; - Ok(()) - })(); - if let Err(error) = prepared { - cleanup_staging_directory(&self.root, &staging); - return Err(error); - } - let store = match CampaignStore::open(directory.join("campaign.cc")) { - Ok(store) => store, - Err(error) => { - let _ = fs::rename(&directory, &staging); - cleanup_staging_directory(&self.root, &staging); - return Err(error); - } - }; - let kernel = WorldKernel::start(store.clone()); - let runtime = CampaignRuntime { store, kernel }; - self.runtimes - .write() - .await - .insert(campaign.id, runtime.clone()); - Ok(runtime) - } - - pub async fn fork(&self, source_id: Uuid, name: String) -> Result { - let name = validated_branch_name(name)?; - let source = self.runtime(source_id).await?; - let key = source_id.to_string(); - let (_, parent) = source - .store - .load::("campaign.v1", &key)? - .ok_or_else(|| anyhow!("source campaign vanished"))?; - let mut evidence = Vec::new(); - for id in source.store.keys("vault_evidence_receipt.v1")? { - if let Some((_, receipt)) = source - .store - .load::("vault_evidence_receipt.v1", &id)? - { - evidence.push(receipt); - } - } - let model_receipts = source - .store - .load_all::("persona_stage_receipt.v1")?; - let parent_revision = parent.revision; - let mut fork = parent; - fork.id = Uuid::new_v4(); - fork.name = name; - fork.revision = 0; - fork.pending_world_proposals.clear(); - fork.resolution_policy.resolution_epoch = - fork.resolution_policy.resolution_epoch.saturating_add(1); - fork.resolution_cover = None; - let runtime = self - .create_with_lifecycle( - fork.clone(), - evidence, - model_receipts, - Some(CampaignLifecycleReceipt { - schema: "ghostlight.campaign_lifecycle_receipt.v1".into(), - campaign_id: fork.id, - operation: "fork".into(), - parent_campaign_id: Some(source_id), - parent_revision: Some(parent_revision), - created_at: Utc::now(), - }), - ) - .await?; - Ok(runtime) - } - - pub async fn reset(&self, source_id: Uuid, name: String) -> Result { - let name = validated_branch_name(name)?; - let source = self.runtime(source_id).await?; - let (_, mut seed) = source - .store - .load::("campaign_seed.v1", &source_id.to_string())? - .ok_or_else(|| anyhow!("campaign has no approved seed"))?; - let parent_revision = source - .store - .load::("campaign.v1", &source_id.to_string())? - .ok_or_else(|| anyhow!("source campaign vanished"))? - .1 - .revision; - seed.id = Uuid::new_v4(); - seed.name = name; - seed.revision = 0; - seed.pending_world_proposals.clear(); - let mut evidence = Vec::new(); - for id in source.store.keys("vault_evidence_receipt.v1")? { - if let Some((_, receipt)) = source - .store - .load::("vault_evidence_receipt.v1", &id)? - { - evidence.push(receipt); - } - } - let model_receipts = source - .store - .load_all::("persona_stage_receipt.v1")?; - let runtime = self - .create_with_lifecycle( - seed.clone(), - evidence, - model_receipts, - Some(CampaignLifecycleReceipt { - schema: "ghostlight.campaign_lifecycle_receipt.v1".into(), - campaign_id: seed.id, - operation: "reset".into(), - parent_campaign_id: Some(source_id), - parent_revision: Some(parent_revision), - created_at: Utc::now(), - }), - ) - .await?; - Ok(runtime) - } - - pub async fn export( - &self, - campaign_id: Uuid, - exports_root: impl AsRef, - ) -> Result { - let runtime = self.runtime(campaign_id).await?; - fs::create_dir_all(exports_root.as_ref())?; - let path = exports_root.as_ref().join(format!( - "{}-{}-{}.cc", - campaign_id, - Utc::now().format("%Y%m%dT%H%M%S%.3fZ"), - Uuid::new_v4() - )); - runtime.store.snapshot_to(&path)?; - Ok(path) - } -} - -fn cleanup_staging_directory(root: &Path, staging: &Path) { - let safe = staging.parent() == Some(root) - && staging - .file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.starts_with(".creating-")); - if safe && staging.exists() { - let _ = fs::remove_dir_all(staging); - } -} - -fn validated_branch_name(name: String) -> Result { - let name = name.trim(); - if name.is_empty() || name.chars().count() > 80 || name.chars().any(char::is_control) { - return Err(anyhow!( - "campaign name must contain 1 to 80 visible characters" - )); - } - Ok(name.to_owned()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::domain::{ActorState, BranchOrigin, Location, WorldCommitReceipt}; - use crate::model::ModelStageRequest; - use crate::session_zero::{ - ApprovedCampaignBrief, CampaignContract, CampaignDmPersona, CampaignGovernance, - CampaignMember, CampaignMembership, CharacterDraft, - }; - use async_trait::async_trait; - use std::collections::{BTreeMap, BTreeSet}; - - struct RegistryNewspaperModel; - - struct RejectingRegistryNewspaperModel; - - fn last_transcript_value(stream: &str, prefix: &str) -> Option { - let start = stream.match_indices(prefix).last()?.0 + prefix.len(); - let tail = stream.get(start..)?; - Some(tail.split('"').next()?.to_owned()) - } - - fn registry_newspaper_narrative_response(request: &ModelStageRequest) -> Result { - if let Some(candidate_digest) = - last_transcript_value(&request.lived_stream, "\"candidate_digest\":\"") - { - return Ok(serde_json::json!({ - "command":{ - "tool":"commit_agenda", - "candidate_digest":candidate_digest, - } - }) - .to_string()); - } - let Some(citation) = last_transcript_value(&request.lived_stream, "\"record_id\":\"") - else { - return Ok(serde_json::json!({ - "command":{ - "tool":"query_public_records", - "terms":[], - "match_terms":"all", - "entity_names":[], - "assertion_statuses":[], - "channels":[], - "order":"newest", - "cursor":null, - "limit":24 - } - }) - .to_string()); - }; - Ok(serde_json::json!({ - "command":{ - "tool":"propose_agenda", - "issue_shape":"special_issue", - "issue_shape_rationale":"The court accusation is the single public rupture in this edition.", - "dominant_throughline":"The inner court has converted an audit dispute into a public crisis of accusation and arithmetic.", - "reader_stake":"Readers depend on whether the court can distinguish an allegation from a judgment.", - "story_pitches":[{ - "lead":true, - "section":"Front Page", - "journalist_id":"aven-tarl", - "narrative_function":"lead_chronology", - "context_role":"owns_issue_chronology", - "assignment_reason":"Aven's court beat and taste for status absurdity fit the accusation.", - "citations":[citation], - "focus_citation":citation, - "narrative_claim":"The singular accusation against three auditors is itself the scandal.", - "tension":"The court's wording collapses three people into one accused figure.", - "public_question":"What process can answer an accusation framed this way?", - "conflict_axis":null - }] - } - }) - .to_string()) - } - - fn registry_newspaper_editor_response(_request: &ModelStageRequest) -> Result { - Ok(serde_json::json!({ - "tool":"file_story", - "headline":"Court Auditors Face a Singular Accusation", - "deck":"The inner court has turned a granary inquiry into a question of witchcraft and arithmetic.", - "dateline":"Room", - "paragraphs":[ - "The inner court has accused three granary auditors of being one witch in a long coat, placing the allegation into the public record.", - "The charge leaves the auditors answering a court that has made one person out of three, at least for purposes of blame." - ] - }) - .to_string()) - } - - #[async_trait] - impl ModelPort for RegistryNewspaperModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - if request.stage == "newspaper_narrative_selection_agent_action" { - return registry_newspaper_narrative_response(request); - } - if request.stage == "newspaper_copy_desk" { - return Ok(serde_json::json!({ - "assessment":"The page is grounded in its cited public report.", - "queries":[] - }) - .to_string()); - } - if request.stage == "newspaper_night_editor_close_agent_action" { - return Ok(serde_json::json!({ - "tool":"submit_close", - "addressed_query_indices":[], - "rewrites":[] - }) - .to_string()); - } - registry_newspaper_editor_response(request) - } - - fn provider(&self) -> &'static str { - "registry-newspaper-fixture" - } - } - - #[async_trait] - impl ModelPort for RejectingRegistryNewspaperModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - if request.stage == "newspaper_narrative_selection_agent_action" { - return registry_newspaper_narrative_response(request); - } - if request.stage == "newspaper_copy_desk" { - let claim = if request - .lived_stream - .contains("three granary auditors of acting as one accused person") - { - "three granary auditors of acting as one accused person" - } else { - "three granary auditors of being one witch in a long coat" - }; - return Ok(serde_json::json!({ - "assessment":"The article states an outcome that its source does not support.", - "queries":[{ - "article_index":0, - "category":"unsupported_fact", - "claim_or_phrase":claim, - "reason":"The cited report records only an accusation." - }] - }) - .to_string()); - } - if request.stage == "newspaper_night_editor_close_agent_action" { - return Ok(serde_json::json!({ - "tool":"submit_close", - "addressed_query_indices":[0], - "rewrites":[{ - "article_index":0, - "headline":"Court Auditors Face a Singular Accusation", - "deck":"The inner court has turned a granary inquiry into a question of witchcraft and arithmetic.", - "dateline":"Room", - "paragraphs":[ - "The inner court has accused three granary auditors of acting as one accused person, placing the allegation into the public record.", - "The charge leaves the auditors answering a court that has made one person out of three, at least for purposes of blame." - ] - }] - }) - .to_string()); - } - registry_newspaper_editor_response(request) - } - - fn provider(&self) -> &'static str { - "registry-newspaper-fixture" - } - } - - fn seed(name: &str) -> Campaign { - let actor = ActorState { - id: "player".into(), - name: "Player".into(), - location_id: "room".into(), - capabilities: BTreeSet::new(), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }; - Campaign { - schema: "ghostlight.campaign.v1".into(), - id: Uuid::new_v4(), - name: name.into(), - revision: 0, - branch_origin: BranchOrigin { - canon_cutoff: "test".into(), - evidence_receipt_ids: vec![], - }, - world_time: Utc::now(), - tick_hours: 6, - player_actor_id: "player".into(), - locations: BTreeMap::from([( - "room".into(), - Location { - id: "room".into(), - name: "Room".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - )]), - actors: BTreeMap::from([("player".into(), actor)]), - institutions: BTreeMap::new(), - clocks: BTreeMap::new(), - facts: BTreeMap::new(), - civic_systems: BTreeMap::new(), - transcript: vec![], - last_player_activity: Utc::now(), - pending_ticks: 0, - away_ticks_processed: 0, - events: vec![], - news: vec![], - canon_candidates: BTreeMap::new(), - gestalts: BTreeMap::new(), - gestalt_members: BTreeMap::new(), - pending_world_proposals: vec![], - agency_profiles: BTreeMap::new(), - agency_relations: BTreeMap::new(), - gestalt_lineages: BTreeMap::new(), - resolution_policy: Default::default(), - resolution_pins: BTreeMap::new(), - resolution_cover: None, - nemesis_attention_history: Vec::new(), - strategic_tick_count: 0, - } - } - - fn publication(campaign: &Campaign, seed_digest: &str) -> PublishedSessionZeroSeed { - let member_id = "member:host".to_string(); - let mut contract = CampaignContract::default(); - contract.campaign_name = campaign.name.clone(); - contract.vault_provider = "fixture".into(); - let character = CharacterDraft { - schema: "ghostlight.character_draft.v1".into(), - member_id: member_id.clone(), - actor_id: campaign.player_actor_id.clone(), - name: campaign.actors[&campaign.player_actor_id].name.clone(), - ..CharacterDraft::default() - }; - let membership = CampaignMembership { - schema: "ghostlight.campaign_membership.v1".into(), - campaign_id: campaign.id, - governance_epoch: 0, - host_member_id: member_id.clone(), - members: BTreeMap::from([( - member_id.clone(), - CampaignMember { - member_id: member_id.clone(), - account_hash: "account:host".into(), - display_name: "Host".into(), - actor_id: campaign.player_actor_id.clone(), - is_host: true, - active: true, - cell_allowance: 8, - }, - )]), - extraordinary_permissions: BTreeMap::new(), - }; - PublishedSessionZeroSeed { - schema: "ghostlight.published_session_zero_seed.v1".into(), - session_zero_id: Uuid::new_v4(), - approved_seed_digest: seed_digest.into(), - contract: contract.clone(), - membership: membership.clone(), - governance: CampaignGovernance { - schema: "ghostlight.campaign_governance.v1".into(), - campaign_id: campaign.id, - governance_epoch: 0, - time_advance_policy: "unanimous".into(), - pooled_cell_ceiling: 8, - cooperative_shared_scene_only: true, - pvp_enabled: false, - }, - dm_persona: CampaignDmPersona { - schema: "ghostlight.campaign_dm_persona.v1".into(), - id: "dm:test".into(), - name: "Ghostlight".into(), - voice: "Candid".into(), - shared_memories: vec![], - private_member_memories: BTreeMap::new(), - }, - approvals: vec![], - approved_brief: ApprovedCampaignBrief { - schema: "ghostlight.approved_campaign_brief.v1".into(), - session_zero_id: Uuid::new_v4(), - host_member_id: member_id.clone(), - contract, - aggregate_boundaries: vec![], - characters: vec![character], - member_actor_ids: BTreeMap::from([(member_id, campaign.player_actor_id.clone())]), - shared_digest: "sha256:shared".into(), - character_digests: BTreeMap::new(), - }, - approved_world_preview_digest: "sha256:preview".into(), - approved_evidence_gaps: vec![], - approved_branch_assumptions: vec![], - boundaries: vec![], - } - } - - #[tokio::test] - async fn create_fork_reset_and_export_preserve_isolated_stores() { - let dir = tempfile::tempdir().unwrap(); - let registry = CampaignRegistry::new(dir.path().join("campaigns")).unwrap(); - let original = seed("Original"); - let model_receipt = ModelStageReceipt { - schema: "ghostlight.persona_stage_receipt.v1".into(), - receipt_hash: "sha256:receipt".into(), - provider: "fixture".into(), - model: "fixture".into(), - stage: "world_compile".into(), - snapshot_binding: "custom-start".into(), - request_hash: "sha256:request".into(), - output_hash: "sha256:output".into(), - source_receipt_ids: vec![], - latency_ms: 1, - validation_result: "valid".into(), - local_validation_error: None, - input_chars: 7, - output_chars: 7, - provider_attempts: vec![], - }; - registry - .create_unadmitted_fixture(original.clone(), vec![], vec![model_receipt.clone()]) - .await - .unwrap(); - let fork = registry.fork(original.id, "Fork".into()).await.unwrap(); - let fork_id = fork.store.keys("campaign.v1").unwrap()[0] - .parse::() - .unwrap(); - assert_ne!(fork_id, original.id); - assert_eq!( - fork.store - .load_all::("persona_stage_receipt.v1") - .unwrap(), - vec![model_receipt] - ); - assert_eq!( - fork.store.keys("campaign_lifecycle_receipt.v1").unwrap(), - vec![format!("{}:create", fork_id), format!("{}:fork", fork_id)] - ); - let reset = registry.reset(original.id, "Reset".into()).await.unwrap(); - let reset_id = reset.store.keys("campaign.v1").unwrap()[0] - .parse::() - .unwrap(); - assert_ne!(reset_id, original.id); - assert_eq!( - reset.store.keys("campaign_lifecycle_receipt.v1").unwrap(), - vec![ - format!("{}:create", reset_id), - format!("{}:reset", reset_id) - ] - ); - assert_eq!(registry.list().await.len(), 3); - let exported = registry - .export(fork_id, dir.path().join("exports")) - .await - .unwrap(); - let second_export = registry - .export(fork_id, dir.path().join("exports")) - .await - .unwrap(); - assert_ne!(exported, second_export); - let export_store = CampaignStore::open(exported).unwrap(); - let second_export_store = CampaignStore::open(second_export).unwrap(); - assert_eq!( - export_store.keys("campaign.v1").unwrap(), - vec![fork_id.to_string()] - ); - assert_eq!( - second_export_store.keys("campaign.v1").unwrap(), - vec![fork_id.to_string()] - ); - assert_eq!( - registry - .runtime(original.id) - .await - .unwrap() - .store - .keys("campaign.v1") - .unwrap(), - vec![original.id.to_string()] - ); - } - - #[tokio::test] - async fn fork_and_reset_reject_invalid_names_before_creating_state() { - let dir = tempfile::tempdir().unwrap(); - let registry = CampaignRegistry::new(dir.path().join("campaigns")).unwrap(); - let original = seed("Original"); - registry - .create_unadmitted_fixture(original.clone(), vec![], vec![]) - .await - .unwrap(); - - for invalid in ["", " ", "bad\nname"] { - assert!(registry.fork(original.id, invalid.into()).await.is_err()); - assert!(registry.reset(original.id, invalid.into()).await.is_err()); - } - let too_long = "x".repeat(81); - assert!(registry.fork(original.id, too_long.clone()).await.is_err()); - assert!(registry.reset(original.id, too_long).await.is_err()); - assert_eq!(registry.list().await, vec![original.id]); - - let fork = registry - .fork(original.id, " A clean branch ".into()) - .await - .unwrap(); - let fork_id = fork.store.keys("campaign.v1").unwrap()[0].clone(); - let forked = fork - .store - .load::("campaign.v1", &fork_id) - .unwrap() - .unwrap() - .1; - assert_eq!(forked.name, "A clean branch"); - } - - #[tokio::test] - async fn failed_creation_never_enters_the_discoverable_campaign_namespace() { - let dir = tempfile::tempdir().unwrap(); - let root = dir.path().join("campaigns"); - let registry = CampaignRegistry::new(&root).unwrap(); - let mut invalid = seed("Invalid"); - invalid - .actors - .get_mut(&invalid.player_actor_id) - .unwrap() - .location_id = "missing".into(); - - assert!( - registry - .create_unadmitted_fixture(invalid, vec![], vec![]) - .await - .is_err() - ); - assert!(registry.list().await.is_empty()); - assert_eq!(std::fs::read_dir(&root).unwrap().count(), 0); - - let valid = seed("Valid"); - let runtime = registry - .create_unadmitted_fixture(valid.clone(), vec![], vec![]) - .await - .unwrap(); - assert_eq!( - runtime.store.keys("campaign_lifecycle_receipt.v1").unwrap(), - vec![format!("{}:create", valid.id)] - ); - } - - #[tokio::test] - async fn failed_additional_lifecycle_write_never_publishes_the_campaign() { - let dir = tempfile::tempdir().unwrap(); - let root = dir.path().join("campaigns"); - let registry = CampaignRegistry::new(&root).unwrap(); - let campaign = seed("Colliding lifecycle"); - - let result = registry - .create_with_lifecycle( - campaign.clone(), - vec![], - vec![], - Some(CampaignLifecycleReceipt { - schema: "ghostlight.campaign_lifecycle_receipt.v1".into(), - campaign_id: campaign.id, - operation: "create".into(), - parent_campaign_id: None, - parent_revision: None, - created_at: Utc::now(), - }), - ) - .await; - - assert!(result.is_err()); - assert!(registry.list().await.is_empty()); - assert_eq!(std::fs::read_dir(&root).unwrap().count(), 0); - } - - #[tokio::test] - async fn session_zero_publication_is_atomic_complete_and_digest_idempotent() { - let dir = tempfile::tempdir().unwrap(); - let root = dir.path().join("campaigns"); - let registry = CampaignRegistry::new(&root).unwrap(); - let campaign = seed("Approved seed"); - let approved = publication(&campaign, "sha256:approved"); - - let first = registry - .publish_session_zero(campaign.clone(), vec![], vec![], approved.clone()) - .await - .unwrap(); - for document_type in [ - "campaign.v1", - "world_seed_admission.v1", - "world_seed_admission_receipt.v1", - "session_zero_publication.v1", - "campaign_membership.v1", - "campaign_contract.v1", - "campaign_governance.v1", - "campaign_dm_persona.v1", - "approved_campaign_brief.v1", - ] { - assert_eq!(first.store.keys(document_type).unwrap().len(), 1); - } - assert_eq!(registry.list().await, vec![campaign.id]); - assert!(std::fs::read_dir(&root).unwrap().all(|entry| { - !entry - .unwrap() - .file_name() - .to_string_lossy() - .starts_with(".creating-") - })); - - let recovered = registry - .publish_session_zero(campaign.clone(), vec![], vec![], approved) - .await - .unwrap(); - assert_eq!( - recovered.store.keys("campaign.v1").unwrap(), - vec![campaign.id.to_string()] - ); - - let conflicting = publication(&campaign, "sha256:different"); - assert!( - registry - .publish_session_zero(campaign, vec![], vec![], conflicting) - .await - .is_err() - ); - } - - #[tokio::test] - async fn contract_review_replaces_all_governance_rows_in_one_cas() { - let dir = tempfile::tempdir().unwrap(); - let registry = CampaignRegistry::new(dir.path().join("campaigns")).unwrap(); - let campaign = seed("Reviewable seed"); - let original_publication = publication(&campaign, "sha256:original"); - let runtime = registry - .publish_session_zero( - campaign.clone(), - vec![], - vec![], - original_publication.clone(), - ) - .await - .unwrap(); - let (campaign_row, mut next_campaign) = runtime - .store - .load::("campaign.v1", &campaign.id.to_string()) - .unwrap() - .unwrap(); - next_campaign.revision = 1; - let mut reviewed = original_publication; - reviewed.approved_seed_digest = "sha256:reviewed".into(); - reviewed.contract.pacing = "deliberate".into(); - reviewed.approved_brief.contract = reviewed.contract.clone(); - reviewed.membership.governance_epoch = 1; - reviewed.governance.governance_epoch = 1; - reviewed.dm_persona.voice = "Patient and exact".into(); - let receipt = WorldCommitReceipt { - schema: "ghostlight.world_commit_receipt.v1".into(), - campaign_id: campaign.id, - previous_revision: 0, - revision: 1, - command_kind: "unanimous_contract_review".into(), - committed_at: Utc::now(), - roll: None, - }; - - runtime - .store - .commit_contract_review(&campaign_row, &next_campaign, &reviewed, &receipt) - .unwrap(); - assert_eq!( - runtime - .store - .load::("campaign.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1 - .revision, - 1 - ); - assert_eq!( - runtime - .store - .load::("campaign_contract.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1 - .pacing, - "deliberate" - ); - assert_eq!( - runtime - .store - .load::("campaign_dm_persona.v1", "dm:test") - .unwrap() - .unwrap() - .1 - .voice, - "Patient and exact" - ); - - let mut impossible_second = reviewed; - impossible_second.contract.pacing = "frantic".into(); - assert!( - runtime - .store - .commit_contract_review( - &campaign_row, - &next_campaign, - &impossible_second, - &receipt, - ) - .is_err() - ); - assert_eq!( - runtime - .store - .load::("campaign_contract.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1 - .pacing, - "deliberate" - ); - } - - #[tokio::test] - async fn load_existing_migrates_flat_campaign_without_advancing_world_revision() { - let dir = tempfile::tempdir().unwrap(); - let root = dir.path().join("campaigns"); - let flat = seed("Flat legacy"); - let campaign_root = root.join(flat.id.to_string()); - std::fs::create_dir_all(&campaign_root).unwrap(); - let store = CampaignStore::open(campaign_root.join("campaign.cc")).unwrap(); - store - .create_unadmitted_fixture_campaign(&flat, &[], &[]) - .unwrap(); - drop(store); - let registry = CampaignRegistry::new(&root).unwrap(); - registry.load_existing().await.unwrap(); - let runtime = registry.runtime(flat.id).await.unwrap(); - let migrated = runtime - .store - .load::("campaign.v1", &flat.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(migrated.revision, flat.revision); - assert_eq!(migrated.world_time, flat.world_time); - assert!(migrated.agency_profiles.contains_key(&flat.player_actor_id)); - assert_eq!(migrated.resolution_policy.resolution_epoch, 1); - assert_eq!( - runtime - .store - .keys("resolution_control_receipt.v1") - .unwrap() - .len(), - 1 - ); - } - - #[tokio::test] - async fn consumer_seed_admission_and_external_snapshot_share_one_authoritative_path() { - let dir = tempfile::tempdir().unwrap(); - let registry = CampaignRegistry::new(dir.path()).unwrap(); - let mut campaign = seed("Consumer world"); - campaign.institutions.insert( - "external-hold".into(), - crate::domain::InstitutionState { - id: "external-hold".into(), - name: "External Hold".into(), - resources: vec!["ore".into()], - goals: vec!["remain sovereign".into()], - posture: "watchful".into(), - }, - ); - campaign.institutions.insert( - "inner-court".into(), - crate::domain::InstitutionState { - id: "inner-court".into(), - name: "The Inner Court".into(), - resources: vec!["sealed minutes".into()], - goals: vec!["control the grain audit".into()], - posture: "denying that the missing grain has political significance".into(), - }, - ); - campaign.gestalts.insert( - "external-population".into(), - crate::domain::GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "external-population".into(), - name: "External Population".into(), - version: 1, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::from(["farming".into()]), - shared_knowledge: BTreeSet::from(["old road".into()]), - resources: BTreeSet::new(), - goals: vec!["endure".into()], - pressures: Vec::new(), - }, - ); - campaign.player_actor_id = "external-population".into(); - let seed = WorldSeed::from_campaign(&campaign).unwrap(); - let authority_key = "test-authority-key"; - let admission = WorldSeedAdmission { - schema: "ghostlight.world_seed_admission.v1".into(), - campaign_id: campaign.id, - producer_id: "fixture-consumer".into(), - producer_kind: WorldSeedProducerKind::Consumer, - seed_digest: seed.digest().unwrap(), - idempotency_key: "admit-once".into(), - external_subjects: vec![ - ExternalSubjectAuthority { - schema: "ghostlight.external_subject_authority.v1".into(), - id: "authority:external-hold".into(), - campaign_id: campaign.id, - subject_id: "external-hold".into(), - subject_kind: crate::domain::AgencySubjectKind::Institution, - owner_id: "fixture-consumer".into(), - authority_key_sha256: crate::consumer::authority_key_digest(authority_key), - last_source_revision: None, - last_payload_digest: None, - }, - ExternalSubjectAuthority { - schema: "ghostlight.external_subject_authority.v1".into(), - id: "authority:external-population".into(), - campaign_id: campaign.id, - subject_id: "external-population".into(), - subject_kind: crate::domain::AgencySubjectKind::Gestalt, - owner_id: "fixture-consumer".into(), - authority_key_sha256: crate::consumer::authority_key_digest(authority_key), - last_source_revision: None, - last_payload_digest: None, - }, - ], - }; - let request = WorldSeedAdmissionRequest { - schema: "ghostlight.world_seed_admission_request.v1".into(), - seed, - admission, - authority_key: authority_key.into(), - }; - let (runtime, receipt) = registry.admit_world_seed(request.clone()).await.unwrap(); - assert_eq!( - receipt.admitted_subject_ids, - vec!["external-hold", "external-population"] - ); - assert!( - !runtime - .store - .load::("campaign.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1 - .agency_profiles["external-hold"] - .simulation_eligible - ); - let (_, repeated) = registry.admit_world_seed(request).await.unwrap(); - assert_eq!(repeated.seed_digest, receipt.seed_digest); - let newspaper_request = crate::consumer::WorldNewspaperRequest { - schema: "ghostlight.world_newspaper_request.v3".into(), - campaign_id: campaign.id, - authority_id: "authority:external-hold".into(), - owner_id: "fixture-consumer".into(), - authority_key: authority_key.into(), - title: "The Consumer Gazette".into(), - editorial_voice: "A skeptical regional court broadsheet.".into(), - newsroom: crate::newspaper::canopy_ledger_newsroom(), - max_articles: 4, - }; - let mut denied_newspaper = newspaper_request.clone(); - denied_newspaper.authority_key = "wrong-key".into(); - assert!( - registry - .compose_world_newspaper(denied_newspaper, &RegistryNewspaperModel) - .await - .is_err() - ); - let newspaper = registry - .compose_world_newspaper(newspaper_request.clone(), &RegistryNewspaperModel) - .await - .unwrap() - .issue; - assert_eq!(newspaper.source_world_revision, 0); - assert!(newspaper.articles.is_empty()); - - let mut snapshot = crate::consumer::ExternalSubjectSnapshot { - schema: "ghostlight.external_subject_snapshot.v1".into(), - campaign_id: campaign.id, - expected_world_revision: 0, - authority_id: "authority:external-hold".into(), - owner_id: "fixture-consumer".into(), - authority_key: authority_key.into(), - source_revision: 7, - idempotency_key: "snapshot-seven".into(), - payload_digest: String::new(), - projection: crate::consumer::ExternalSubjectProjection::Institution( - crate::domain::InstitutionState { - id: "external-hold".into(), - name: "External Hold".into(), - resources: vec!["ore".into(), "grain".into()], - goals: vec!["remain sovereign".into()], - posture: "mobilized".into(), - }, - ), - }; - snapshot.payload_digest = crate::consumer::snapshot_payload_digest(&snapshot).unwrap(); - let mut denied = snapshot.clone(); - denied.authority_key = "wrong-key".into(); - assert!( - registry - .apply_external_subject_snapshot(denied) - .await - .is_err() - ); - assert_eq!( - runtime - .store - .load::("campaign.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1 - .revision, - 0 - ); - let snapshot_receipt = registry - .apply_external_subject_snapshot(snapshot.clone()) - .await - .unwrap(); - assert_eq!(snapshot_receipt.world_revision, 1); - let updated = runtime - .store - .load::("campaign.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(updated.institutions["external-hold"].posture, "mobilized"); - assert!( - updated.agency_profiles["external-hold"].facets[&crate::domain::AgencyAxis::Authority] - .contains("mobilized") - ); - assert!( - updated.agency_profiles["external-hold"].facets - [&crate::domain::AgencyAxis::EconomyRole] - .contains("grain") - ); - assert_eq!( - registry - .apply_external_subject_snapshot(snapshot) - .await - .unwrap(), - snapshot_receipt - ); - let mut stale_snapshot = crate::consumer::ExternalSubjectSnapshot { - schema: "ghostlight.external_subject_snapshot.v1".into(), - campaign_id: campaign.id, - expected_world_revision: 1, - authority_id: "authority:external-hold".into(), - owner_id: "fixture-consumer".into(), - authority_key: authority_key.into(), - source_revision: 6, - idempotency_key: "snapshot-six".into(), - payload_digest: String::new(), - projection: crate::consumer::ExternalSubjectProjection::Institution( - campaign.institutions["external-hold"].clone(), - ), - }; - stale_snapshot.payload_digest = - crate::consumer::snapshot_payload_digest(&stale_snapshot).unwrap(); - assert!( - registry - .apply_external_subject_snapshot(stale_snapshot) - .await - .is_err() - ); - assert_eq!( - runtime - .store - .load::("campaign.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1 - .revision, - 1 - ); - let mut invalid_gestalt_snapshot = crate::consumer::ExternalSubjectSnapshot { - schema: "ghostlight.external_subject_snapshot.v1".into(), - campaign_id: campaign.id, - expected_world_revision: 1, - authority_id: "authority:external-population".into(), - owner_id: "fixture-consumer".into(), - authority_key: authority_key.into(), - source_revision: 1, - idempotency_key: "population-invalid-home".into(), - payload_digest: String::new(), - projection: crate::consumer::ExternalSubjectProjection::Gestalt( - crate::domain::GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "external-population".into(), - name: "External Population".into(), - version: 2, - home_location_id: "invented-place".into(), - shared_capabilities: BTreeSet::from(["farming".into()]), - shared_knowledge: BTreeSet::from(["old road".into()]), - resources: BTreeSet::new(), - goals: vec!["endure".into()], - pressures: Vec::new(), - }, - ), - }; - invalid_gestalt_snapshot.payload_digest = - crate::consumer::snapshot_payload_digest(&invalid_gestalt_snapshot).unwrap(); - let error = registry - .apply_external_subject_snapshot(invalid_gestalt_snapshot) - .await - .unwrap_err(); - assert!( - error.to_string().contains("unknown home location"), - "{error}" - ); - assert_eq!( - runtime - .store - .load::("campaign.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1 - .revision, - 1 - ); - let mut gestalt_snapshot = crate::consumer::ExternalSubjectSnapshot { - schema: "ghostlight.external_subject_snapshot.v1".into(), - campaign_id: campaign.id, - expected_world_revision: 1, - authority_id: "authority:external-population".into(), - owner_id: "fixture-consumer".into(), - authority_key: authority_key.into(), - source_revision: 1, - idempotency_key: "population-one".into(), - payload_digest: String::new(), - projection: crate::consumer::ExternalSubjectProjection::Gestalt( - crate::domain::GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "external-population".into(), - name: "External Population".into(), - version: 2, - home_location_id: "room".into(), - shared_capabilities: BTreeSet::from(["farming".into(), "milling".into()]), - shared_knowledge: BTreeSet::from(["old road".into(), "new levy".into()]), - resources: BTreeSet::new(), - goals: vec!["endure".into()], - pressures: vec!["taxation".into()], - }, - ), - }; - gestalt_snapshot.payload_digest = - crate::consumer::snapshot_payload_digest(&gestalt_snapshot).unwrap(); - let gestalt_receipt = registry - .apply_external_subject_snapshot(gestalt_snapshot) - .await - .unwrap(); - assert_eq!(gestalt_receipt.world_revision, 2); - let updated = runtime - .store - .load::("campaign.v1", &campaign.id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(updated.gestalts["external-population"].version, 2); - assert!(!updated.agency_profiles["external-population"].simulation_eligible); - assert!( - updated.agency_profiles["external-population"].facets - [&crate::domain::AgencyAxis::EconomyRole] - .contains("milling") - ); - runtime - .kernel - .command(crate::domain::WorldCommand::AdvanceStrategicTick { - expected_revision: 2, - source: crate::domain::TickSource::Scheduler, - plan: Some(crate::domain::StrategicTickPlan { - institution_actions: vec![crate::domain::StrategicInstitutionAction { - institution_id: "inner-court".into(), - posture: - "accusing three granary auditors of being one witch in a long coat" - .into(), - location_ids: vec!["room".into()], - public_channels: vec!["court broadsheet".into()], - }], - ..Default::default() - }), - model_receipt_hash: Some(format!("sha256:{}", "a".repeat(64))), - resolution_wave: None, - }) - .await - .unwrap(); - let newspaper = registry - .compose_world_newspaper(newspaper_request.clone(), &RegistryNewspaperModel) - .await - .unwrap() - .issue; - assert_eq!(newspaper.source_world_revision, 3); - assert_eq!(newspaper.articles.len(), 1); - assert_eq!( - newspaper.articles[0].event_ids(), - ["strategic:3:institution:inner-court"] - ); - assert!( - newspaper.articles[0] - .paragraphs - .join(" ") - .contains("one witch in a long coat") - ); - let successful_receipts = runtime.store.keys("persona_stage_receipt.v1").unwrap(); - assert!( - newspaper - .editorial_receipt_ids - .iter() - .all(|receipt_id| successful_receipts.contains(receipt_id)) - ); - - let repeated_newspaper = registry - .compose_world_newspaper(newspaper_request.clone(), &RegistryNewspaperModel) - .await - .unwrap() - .issue; - assert_eq!(repeated_newspaper.id, newspaper.id); - assert_eq!( - runtime - .store - .keys("persona_stage_receipt.v1") - .unwrap() - .len(), - successful_receipts.len() - ); - - let receipt_count_before_rejection = successful_receipts.len(); - let mut rejected_request = newspaper_request; - rejected_request.title.push_str(" Evening"); - let closed = registry - .compose_world_newspaper(rejected_request, &RejectingRegistryNewspaperModel) - .await - .unwrap(); - assert_eq!(closed.model_receipts.len(), 6); - assert_eq!(closed.copy_desk.queries.len(), 1); - assert!(closed.press_close.night_editor_action_applied); - assert_eq!(closed.press_close.addressed_query_indices, [0]); - assert_eq!( - closed.issue.articles[0].paragraphs[0], - "The inner court has accused three granary auditors of acting as one accused person, placing the allegation into the public record." - ); - let stored_after_rejection = runtime.store.keys("persona_stage_receipt.v1").unwrap(); - let newly_observed_close_receipts = closed - .model_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .filter(|receipt_id| !successful_receipts.contains(receipt_id)) - .collect::>(); - assert_eq!( - stored_after_rejection.len(), - receipt_count_before_rejection + newly_observed_close_receipts.len() - ); - assert!( - closed.model_receipts.iter().all(|receipt| { - stored_after_rejection.contains(&receipt.storage_key().to_owned()) - }) - ); - let proposal = ExternalWorldProposal { - schema: "ghostlight.external_world_proposal.v1".into(), - id: "external-proposal:test".into(), - campaign_id: campaign.id, - world_revision: 1, - authority_id: "authority:external-hold".into(), - external_subject_id: "external-hold".into(), - source_subject_id: "foreign-court".into(), - intent: "Offer a treaty.".into(), - intended_effect: "Open negotiations.".into(), - action_digest: format!("sha256:{}", "a".repeat(64)), - public_channels: vec!["diplomatic".into()], - state_references: Vec::new(), - status: ExternalProposalStatus::Pending, - created_at: Utc::now(), - }; - runtime - .store - .insert( - "external_world_proposal.v1", - "ghostlight.external_world_proposal.v1", - &proposal.id, - &proposal, - ) - .unwrap(); - let proposals = registry - .list_external_proposals(ExternalProposalListRequest { - schema: "ghostlight.external_proposal_list_request.v1".into(), - campaign_id: campaign.id, - authority_id: "authority:external-hold".into(), - owner_id: "fixture-consumer".into(), - authority_key: authority_key.into(), - }) - .await - .unwrap(); - assert_eq!(proposals.proposals, vec![proposal.clone()]); - let acknowledgement = ExternalProposalAcknowledgement { - schema: "ghostlight.external_proposal_acknowledgement.v1".into(), - campaign_id: campaign.id, - authority_id: "authority:external-hold".into(), - owner_id: "fixture-consumer".into(), - authority_key: authority_key.into(), - proposal_id: proposal.id, - idempotency_key: "ack-treaty".into(), - status: ExternalProposalStatus::Rejected, - result_summary: "The hold declined.".into(), - acknowledged_at: Utc::now(), - }; - let acknowledgement_receipt = registry - .acknowledge_external_proposal(acknowledgement.clone()) - .await - .unwrap(); - assert_eq!( - registry - .acknowledge_external_proposal(acknowledgement) - .await - .unwrap(), - acknowledgement_receipt - ); - assert!( - registry - .list_external_proposals(ExternalProposalListRequest { - schema: "ghostlight.external_proposal_list_request.v1".into(), - campaign_id: campaign.id, - authority_id: "authority:external-hold".into(), - owner_id: "fixture-consumer".into(), - authority_key: authority_key.into(), - }) - .await - .unwrap() - .proposals - .is_empty() - ); - } -} diff --git a/crates/ghostlight-dungeon/src/resolution.rs b/crates/ghostlight-dungeon/src/resolution.rs deleted file mode 100644 index cd4b053..0000000 --- a/crates/ghostlight-dungeon/src/resolution.rs +++ /dev/null @@ -1,5505 +0,0 @@ -use crate::domain::*; -use anyhow::{Result, anyhow}; -use sha2::{Digest, Sha256}; -use std::cmp::{Ordering, Reverse}; -use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, VecDeque}; - -pub const MIN_ACTIVE_CELL_BUDGET: u8 = 1; -/// A wave can cover a hundreds-class world while provider concurrency remains -/// independently bounded. Keep this below u8::MAX so malformed sentinel-like -/// values never become an operator setting. -pub const MAX_ACTIVE_CELL_BUDGET: u8 = 240; -pub const MAX_PROVIDER_PARALLELISM: u8 = 32; - -/// True when a publication or reception route is concrete enough to enter an -/// agency profile. Knowledge belongs to the subject state, never this lane. -pub fn information_channel_is_concrete(channel: &str) -> bool { - let channel = channel.trim(); - !channel.is_empty() && channel.len() <= 160 && !channel.eq_ignore_ascii_case("unknown") -} - -/// Canonical world subjects and their agency projections share one ID space. -/// Keep this predicate deterministic and side-effect free: validators, rebases, -/// and kernel application all consult the same occupied-set definition. -pub(crate) fn canonical_subject_id_is_occupied(campaign: &Campaign, subject_id: &str) -> bool { - canonical_subject_id_is_occupied_except_member(campaign, subject_id, None) -} - -pub(crate) fn canonical_subject_id_is_occupied_except_member( - campaign: &Campaign, - subject_id: &str, - permitted_member_id: Option<&str>, -) -> bool { - let permitted_member_id = - permitted_member_id.map(crate::domain::canonical_gestalt_member_local_id); - campaign.actors.contains_key(subject_id) - || campaign.institutions.contains_key(subject_id) - || campaign.gestalts.contains_key(subject_id) - || campaign.gestalt_members.iter().any(|(member_id, member)| { - permitted_member_id.as_deref() - != Some(crate::domain::canonical_gestalt_member_local_id(member_id).as_str()) - && crate::domain::gestalt_member_subject_id(&member.id) == subject_id - }) - || campaign - .agency_profiles - .iter() - .any(|(profile_key, profile)| { - profile_key == subject_id - || profile.id == subject_id - || profile.subject_id == subject_id - }) -} - -#[derive(Clone, Debug)] -struct Candidate { - left: String, - right: String, - loss: MergeLoss, -} - -impl PartialEq for Candidate { - fn eq(&self, other: &Self) -> bool { - self.loss.total.to_bits() == other.loss.total.to_bits() - && self.left == other.left - && self.right == other.right - } -} -impl Eq for Candidate {} -impl PartialOrd for Candidate { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} -impl Ord for Candidate { - fn cmp(&self, other: &Self) -> Ordering { - other - .loss - .total - .total_cmp(&self.loss.total) - .then_with(|| other.left.cmp(&self.left)) - .then_with(|| other.right.cmp(&self.right)) - } -} - -pub fn default_demand(campaign: &Campaign, rationale: impl Into) -> ResolutionDemand { - ResolutionDemand { - schema: "ghostlight.resolution_demand.v1".into(), - campaign_id: campaign.id, - world_revision: campaign.revision, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - axis_weights: BTreeMap::from([ - (AgencyAxis::Geography, 0.25), - (AgencyAxis::Ideology, 0.20), - (AgencyAxis::Authority, 0.25), - (AgencyAxis::EconomyRole, 0.15), - (AgencyAxis::SpeciesBody, 0.05), - (AgencyAxis::Information, 0.10), - ]), - focal_subject_ids: BTreeSet::new(), - horizon_minutes: campaign.tick_hours.saturating_mul(60), - rationale: rationale.into(), - } -} - -pub fn ensure_agency_profiles(campaign: &mut Campaign) { - let evidence = campaign.branch_origin.evidence_receipt_ids.clone(); - for actor in campaign.actors.values() { - campaign - .agency_profiles - .entry(actor.id.clone()) - .or_insert_with(|| profile_for_actor(actor, &evidence)); - } - for institution in campaign.institutions.values() { - campaign - .agency_profiles - .entry(institution.id.clone()) - .or_insert_with(|| profile_for_institution(institution, &evidence)); - } - for gestalt in campaign.gestalts.values() { - campaign - .agency_profiles - .entry(gestalt.id.clone()) - .or_insert_with(|| profile_for_gestalt(gestalt, &evidence)); - } - for actor in campaign.actors.values() { - if let Some(profile) = campaign.agency_profiles.get_mut(&actor.id) { - profile.location_ids = BTreeSet::from([actor.location_id.clone()]); - profile.information_channels.retain(|channel| { - information_channel_is_concrete(channel) && !actor.knowledge.contains(channel) - }); - } - } - for gestalt in campaign.gestalts.values() { - if let Some(profile) = campaign.agency_profiles.get_mut(&gestalt.id) { - profile.information_channels.retain(|channel| { - information_channel_is_concrete(channel) - && !gestalt.shared_knowledge.contains(channel) - }); - } - } - let live: BTreeSet<_> = campaign - .actors - .keys() - .chain(campaign.institutions.keys()) - .chain(campaign.gestalts.keys()) - .cloned() - .collect(); - campaign - .agency_profiles - .retain(|id, profile| live.contains(id) || !profile.active_leaf); - if let Some(player) = campaign.agency_profiles.get_mut(&campaign.player_actor_id) { - player.simulation_eligible = false; - } - ensure_structural_relations(campaign); -} - -/// Normalize the one historical compiler shape that stored the world-subject -/// `member:` namespace inside a Gestalt member's local ID. This migrates only -/// current canonical references. Event history and persisted receipts remain -/// immutable witnesses of the version that produced them. -pub(crate) fn normalize_legacy_gestalt_member_identities(campaign: &mut Campaign) -> Result { - let mut next = campaign.clone(); - let changed = normalize_legacy_gestalt_member_identities_inner(&mut next)?; - if changed { - *campaign = next; - } - Ok(changed) -} - -fn normalize_legacy_gestalt_member_identities_inner(campaign: &mut Campaign) -> Result { - let mut changed = false; - let mut subject_aliases = BTreeMap::new(); - let mut normalized_members = BTreeMap::new(); - - for (stored_key, mut member) in std::mem::take(&mut campaign.gestalt_members) { - if stored_key != member.id { - return Err(anyhow!( - "gestalt member map key {:?} disagrees with record ID {:?}", - stored_key, - member.id - )); - } - let old_local_id = member.id.clone(); - let local_id = crate::domain::canonical_gestalt_member_local_id(&old_local_id); - if local_id.is_empty() { - return Err(anyhow!("gestalt member has an empty canonical local ID")); - } - let canonical_subject_id = crate::domain::gestalt_member_subject_id(&local_id); - let legacy_subject_id = format!("member:{old_local_id}"); - if old_local_id != local_id { - changed = true; - insert_identity_alias( - &mut subject_aliases, - legacy_subject_id.clone(), - canonical_subject_id.clone(), - )?; - } - - match member.materialized_actor_id.clone() { - Some(old_actor_id) => { - let actor = campaign.actors.get(&old_actor_id).ok_or_else(|| { - anyhow!( - "materialized gestalt member {} references missing actor {}", - old_local_id, - old_actor_id - ) - })?; - if actor.id != old_actor_id { - return Err(anyhow!( - "materialized actor map key {:?} disagrees with record ID {:?}", - old_actor_id, - actor.id - )); - } - if old_actor_id != canonical_subject_id { - changed = true; - insert_identity_alias( - &mut subject_aliases, - old_actor_id, - canonical_subject_id.clone(), - )?; - } - member.materialized_actor_id = Some(canonical_subject_id); - } - None => { - if campaign.actors.contains_key(&canonical_subject_id) - || (legacy_subject_id != canonical_subject_id - && campaign.actors.contains_key(&legacy_subject_id)) - { - return Err(anyhow!( - "dormant gestalt member {} collides with a materialized actor", - old_local_id - )); - } - } - } - member.id = local_id.clone(); - if normalized_members - .insert(local_id.clone(), member) - .is_some() - { - return Err(anyhow!( - "gestalt member IDs collide after normalization at {local_id}" - )); - } - } - campaign.gestalt_members = normalized_members; - - if !changed { - return Ok(false); - } - - let mut normalized_actors = BTreeMap::new(); - for (stored_key, mut actor) in std::mem::take(&mut campaign.actors) { - if stored_key != actor.id { - return Err(anyhow!( - "actor map key {:?} disagrees with record ID {:?}", - stored_key, - actor.id - )); - } - let actor_id = rewritten_subject_id(&subject_aliases, &stored_key); - actor.id = actor_id.clone(); - if normalized_actors.insert(actor_id.clone(), actor).is_some() { - return Err(anyhow!( - "actor IDs collide after gestalt member normalization at {actor_id}" - )); - } - } - campaign.actors = normalized_actors; - campaign.player_actor_id = rewritten_subject_id(&subject_aliases, &campaign.player_actor_id); - - for actor in campaign.actors.values_mut() { - rewrite_relationship_targets(&mut actor.relationships, &subject_aliases)?; - } - for member in campaign.gestalt_members.values_mut() { - rewrite_relationship_targets(&mut member.relationships, &subject_aliases)?; - } - for proposal in &mut campaign.pending_world_proposals { - proposal.actor_id = rewritten_subject_id(&subject_aliases, &proposal.actor_id); - for reference in &mut proposal.state_references { - *reference = rewritten_state_reference(&subject_aliases, reference); - } - } - - let mut normalized_profiles = BTreeMap::new(); - for (stored_key, mut profile) in std::mem::take(&mut campaign.agency_profiles) { - let subject_id = rewritten_subject_id(&subject_aliases, &profile.subject_id); - let profile_key = rewritten_subject_id(&subject_aliases, &stored_key); - if profile_key != subject_id { - return Err(anyhow!( - "agency profile key {:?} disagrees with normalized subject {:?}", - profile_key, - subject_id - )); - } - if let Some(old_subject_id) = subject_aliases - .iter() - .find_map(|(old, new)| (new == &subject_id).then_some(old)) - { - let legacy_profile_id = format!("agency-profile:{old_subject_id}"); - if profile.id == legacy_profile_id { - profile.id = format!("agency-profile:{subject_id}"); - } - } - profile.subject_id = subject_id.clone(); - profile.collective_authority_id = profile - .collective_authority_id - .as_deref() - .map(|id| rewritten_subject_id(&subject_aliases, id)); - profile.parent_subject_id = profile - .parent_subject_id - .as_deref() - .map(|id| rewritten_subject_id(&subject_aliases, id)); - if normalized_profiles - .insert(subject_id.clone(), profile) - .is_some() - { - return Err(anyhow!( - "agency profiles collide after gestalt member normalization at {subject_id}" - )); - } - } - campaign.agency_profiles = normalized_profiles; - - for relation in campaign.agency_relations.values_mut() { - relation.from_subject_id = - rewritten_subject_id(&subject_aliases, &relation.from_subject_id); - relation.to_subject_id = rewritten_subject_id(&subject_aliases, &relation.to_subject_id); - } - for pin in campaign.resolution_pins.values_mut() { - pin.subject_ids = pin - .subject_ids - .iter() - .map(|id| rewritten_subject_id(&subject_aliases, id)) - .collect(); - } - campaign.resolution_cover = None; - Ok(true) -} - -fn insert_identity_alias( - aliases: &mut BTreeMap, - old: String, - new: String, -) -> Result<()> { - if old == new { - return Ok(()); - } - if aliases - .insert(old.clone(), new.clone()) - .is_some_and(|prior| prior != new) - { - return Err(anyhow!( - "legacy subject {old} maps to multiple canonical identities" - )); - } - Ok(()) -} - -fn rewritten_subject_id(aliases: &BTreeMap, value: &str) -> String { - aliases - .get(value) - .cloned() - .unwrap_or_else(|| value.to_owned()) -} - -fn rewritten_state_reference(aliases: &BTreeMap, value: &str) -> String { - if let Some(rewritten) = aliases.get(value) { - return rewritten.clone(); - } - for namespace in ["subject:", "actor:"] { - if let Some(subject_id) = value.strip_prefix(namespace) - && let Some(rewritten) = aliases.get(subject_id) - { - return format!("{namespace}{rewritten}"); - } - } - value.to_owned() -} - -fn rewrite_relationship_targets( - relationships: &mut BTreeMap, - aliases: &BTreeMap, -) -> Result<()> { - let mut normalized = BTreeMap::new(); - for (subject_id, description) in std::mem::take(relationships) { - let subject_id = rewritten_subject_id(aliases, &subject_id); - if normalized.insert(subject_id.clone(), description).is_some() { - return Err(anyhow!( - "relationship targets collide after gestalt member normalization at {subject_id}" - )); - } - } - *relationships = normalized; - Ok(()) -} - -fn base_profile( - subject_id: &str, - kind: AgencySubjectKind, - authority: Option, - evidence: &[String], -) -> AgencyProfile { - AgencyProfile { - schema: "ghostlight.agency_profile.v1".into(), - id: format!("agency-profile:{subject_id}"), - subject_id: subject_id.into(), - subject_kind: kind, - profile_version: 0, - collective_authority_id: authority, - parent_subject_id: None, - active_leaf: true, - simulation_eligible: true, - facets: BTreeMap::new(), - location_ids: BTreeSet::new(), - information_channels: BTreeSet::new(), - detail_debt: 0, - last_detail_tick: 0, - evidence_receipt_ids: evidence.to_vec(), - } -} - -fn profile_for_actor(actor: &ActorState, evidence: &[String]) -> AgencyProfile { - let mut profile = base_profile(&actor.id, AgencySubjectKind::Actor, None, evidence); - profile.location_ids.insert(actor.location_id.clone()); - profile.facets.insert( - AgencyAxis::Geography, - BTreeSet::from([actor.location_id.clone()]), - ); - profile.facets.insert( - AgencyAxis::EconomyRole, - actor.capabilities.iter().cloned().collect(), - ); - profile.facets.insert( - AgencyAxis::Information, - actor.knowledge.iter().cloned().collect(), - ); - profile -} - -fn profile_for_institution(value: &InstitutionState, evidence: &[String]) -> AgencyProfile { - let mut profile = base_profile( - &value.id, - AgencySubjectKind::Institution, - Some(value.id.clone()), - evidence, - ); - profile.facets.insert( - AgencyAxis::Authority, - BTreeSet::from([value.id.clone(), value.posture.clone()]), - ); - profile.facets.insert( - AgencyAxis::EconomyRole, - value.resources.iter().cloned().collect(), - ); - profile -} - -fn profile_for_gestalt(value: &GestaltPersonaState, evidence: &[String]) -> AgencyProfile { - let mut profile = base_profile( - &value.id, - AgencySubjectKind::Gestalt, - Some(value.id.clone()), - evidence, - ); - profile.location_ids.insert(value.home_location_id.clone()); - profile.facets.insert( - AgencyAxis::Geography, - BTreeSet::from([value.home_location_id.clone()]), - ); - profile.facets.insert( - AgencyAxis::EconomyRole, - value.shared_capabilities.iter().cloned().collect(), - ); - profile.facets.insert( - AgencyAxis::Information, - value.shared_knowledge.iter().cloned().collect(), - ); - profile -} - -fn ensure_structural_relations(campaign: &mut Campaign) { - let live: BTreeSet<_> = campaign - .agency_profiles - .values() - .filter(|profile| profile.active_leaf) - .map(|profile| profile.subject_id.as_str()) - .collect(); - campaign.agency_relations.retain(|_, relation| { - live.contains(relation.from_subject_id.as_str()) - && live.contains(relation.to_subject_id.as_str()) - }); -} - -#[derive(Clone, Debug)] -struct DerivedAgencyGraph { - neighbors: BTreeMap>, -} - -#[derive(Debug)] -struct ScoringCache { - pressure_tokens: BTreeMap>, - salience: BTreeMap, -} - -impl ScoringCache { - fn new(campaign: &Campaign, profiles: &BTreeMap) -> Self { - Self { - pressure_tokens: profiles - .keys() - .map(|id| (id.clone(), pressure_tokens(campaign, id))) - .collect(), - salience: profiles - .iter() - .map(|(id, profile)| (id.clone(), subject_salience(campaign, profile))) - .collect(), - } - } -} - -impl DerivedAgencyGraph { - fn build(campaign: &Campaign, subjects: BTreeSet) -> Self { - let mut neighbors: BTreeMap<_, _> = subjects - .iter() - .map(|id| (id.clone(), BTreeSet::new())) - .collect(); - { - let mut connect = |left: &str, right: &str| { - if left != right && subjects.contains(left) && subjects.contains(right) { - neighbors - .entry(left.to_owned()) - .or_default() - .insert(right.to_owned()); - neighbors - .entry(right.to_owned()) - .or_default() - .insert(left.to_owned()); - } - }; - for relation in campaign - .agency_relations - .values() - .filter(|relation| relation.active) - { - connect(&relation.from_subject_id, &relation.to_subject_id); - } - let mut by_location: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); - for profile in campaign - .agency_profiles - .values() - .filter(|profile| subjects.contains(&profile.subject_id)) - { - for location in &profile.location_ids { - by_location - .entry(location.as_str()) - .or_default() - .push(profile.subject_id.as_str()); - } - } - for values in by_location.values_mut() { - values.sort_unstable(); - values.dedup(); - for pair in values.windows(2) { - connect(pair[0], pair[1]); - } - } - } - - // A campaign root is a resolution-only Steiner vertex. Linking component - // representatives through it keeps the cover coarsenable without claiming - // that distant or opposed subjects share containment, knowledge, or authority. - let mut seen = BTreeSet::new(); - let mut representatives = Vec::new(); - for start in &subjects { - if !seen.insert(start.clone()) { - continue; - } - representatives.push(start.clone()); - let mut queue = VecDeque::from([start.clone()]); - while let Some(current) = queue.pop_front() { - for next in neighbors.get(¤t).into_iter().flatten() { - if seen.insert(next.clone()) { - queue.push_back(next.clone()); - } - } - } - } - for pair in representatives.windows(2) { - neighbors - .entry(pair[0].clone()) - .or_default() - .insert(pair[1].clone()); - neighbors - .entry(pair[1].clone()) - .or_default() - .insert(pair[0].clone()); - } - Self { neighbors } - } -} - -pub fn validate_policy(policy: &ResolutionPolicy) -> Result<()> { - if !(MIN_ACTIVE_CELL_BUDGET..=MAX_ACTIVE_CELL_BUDGET).contains(&policy.active_cell_budget) - || policy.pending_active_cell_budget.is_some_and(|value| { - !(MIN_ACTIVE_CELL_BUDGET..=MAX_ACTIVE_CELL_BUDGET).contains(&value) - }) - || !(1..=MAX_PROVIDER_PARALLELISM).contains(&policy.provider_parallelism) - { - return Err(anyhow!("resolution policy is outside supported bounds")); - } - Ok(()) -} - -pub fn validate_pins(campaign: &Campaign, pins: &BTreeMap) -> Result<()> { - let subjects: BTreeSet<_> = campaign - .agency_profiles - .values() - .filter(|profile| profile.active_leaf && profile.simulation_eligible) - .map(|profile| profile.subject_id.as_str()) - .collect(); - for pin in pins.values() { - if pin.id.trim().is_empty() - || pin.reason.trim().is_empty() - || pin.subject_ids.is_empty() - || pin - .subject_ids - .iter() - .any(|id| !subjects.contains(id.as_str())) - { - return Err(anyhow!( - "resolution pin is malformed or references an unknown subject" - )); - } - match pin.kind { - ResolutionPinKind::MinimumIndividualDetail if pin.subject_ids.len() != 1 => { - return Err(anyhow!( - "minimum-individual pin must name exactly one subject" - )); - } - ResolutionPinKind::KeepTogether | ResolutionPinKind::KeepSeparate - if pin.subject_ids.len() < 2 => - { - return Err(anyhow!( - "group resolution pin must name at least two subjects" - )); - } - _ => {} - } - } - for together in pins - .values() - .filter(|pin| pin.kind == ResolutionPinKind::KeepTogether) - { - if pins - .values() - .filter(|pin| pin.kind == ResolutionPinKind::KeepSeparate) - .any(|separate| { - together - .subject_ids - .intersection(&separate.subject_ids) - .count() - >= 2 - }) - || pins - .values() - .filter(|pin| pin.kind == ResolutionPinKind::MinimumIndividualDetail) - .any(|individual| !individual.subject_ids.is_disjoint(&together.subject_ids)) - { - return Err(anyhow!( - "resolution pins require the same subjects together and apart" - )); - } - } - Ok(()) -} - -pub fn plan_cover(campaign: &Campaign, demand: ResolutionDemand) -> Result { - let trace = std::env::var_os("GHOSTLIGHT_PARTITION_TRACE").is_some(); - let trace_started = std::time::Instant::now(); - validate_policy(&campaign.resolution_policy)?; - validate_pins(campaign, &campaign.resolution_pins)?; - validate_demand(campaign, &demand)?; - let profiles: BTreeMap<_, _> = campaign - .agency_profiles - .iter() - .filter(|(_, profile)| profile.active_leaf && profile.simulation_eligible) - .map(|(id, profile)| (id.clone(), profile.clone())) - .collect(); - if profiles.is_empty() { - return Err(anyhow!("agency graph has no active subjects")); - } - let scoring = ScoringCache::new(campaign, &profiles); - let mandatory = mandatory_subjects(campaign); - let graph = DerivedAgencyGraph::build(campaign, profiles.keys().cloned().collect()); - if trace { - eprintln!("partition graph: {:?}", trace_started.elapsed()); - } - let mut groups: HashMap> = profiles - .keys() - .map(|id| (id.clone(), BTreeSet::from([id.clone()]))) - .collect(); - contract_together_pins(&mut groups, &campaign.resolution_pins, &mandatory); - let mut group_samples: HashMap> = groups - .iter() - .map(|(id, subjects)| (id.clone(), representative_sample(subjects.iter()))) - .collect(); - let mandatory_cells = groups - .values() - .filter(|subjects| !subjects.is_disjoint(&mandatory)) - .count(); - let configured = campaign.resolution_policy.active_cell_budget as usize; - let target = configured.max(mandatory_cells); - let active_subjects: BTreeSet<_> = profiles.keys().cloned().collect(); - let separate_floor = campaign - .resolution_pins - .values() - .filter(|pin| pin.kind == ResolutionPinKind::KeepSeparate) - .map(|pin| pin.subject_ids.intersection(&active_subjects).count()) - .max() - .unwrap_or(0); - let target = target.max(separate_floor); - let mut neighbors = group_neighbors(&groups, &graph); - let mut heap = candidates( - campaign, - &profiles, - &groups, - &group_samples, - &neighbors, - &scoring, - &demand, - &mandatory, - ); - if trace { - eprintln!("partition heap: {:?}", trace_started.elapsed()); - } - let mut merge_serial = 0u64; - let mut candidate_elapsed = std::time::Duration::ZERO; - let mut heap_pops = 0usize; - while groups.len() > target { - let Some(best) = heap.pop() else { break }; - heap_pops += 1; - if !groups.contains_key(&best.left) - || !groups.contains_key(&best.right) - || !neighbors - .get(&best.left) - .is_some_and(|ids| ids.contains(&best.right)) - { - continue; - } - let left_group = groups - .remove(&best.left) - .ok_or_else(|| anyhow!("partition candidate vanished"))?; - let right_group = groups - .remove(&best.right) - .ok_or_else(|| anyhow!("partition candidate vanished"))?; - let (mut joined, smaller) = if left_group.len() >= right_group.len() { - (left_group, right_group) - } else { - (right_group, left_group) - }; - joined.extend(smaller); - let left_sample = group_samples.remove(&best.left).unwrap_or_default(); - let right_sample = group_samples.remove(&best.right).unwrap_or_default(); - let joined_sample = representative_sample(left_sample.iter().chain(right_sample.iter())); - let new_id = format!("merge-group:{merge_serial:016}"); - merge_serial = merge_serial.saturating_add(1); - let joined_neighbors: BTreeSet<_> = neighbors - .remove(&best.left) - .unwrap_or_default() - .union(&neighbors.remove(&best.right).unwrap_or_default()) - .filter(|id| *id != &best.left && *id != &best.right && groups.contains_key(*id)) - .cloned() - .collect(); - for other in &joined_neighbors { - if let Some(values) = neighbors.get_mut(other) { - values.remove(&best.left); - values.remove(&best.right); - values.insert(new_id.clone()); - } - } - groups.insert(new_id.clone(), joined); - group_samples.insert(new_id.clone(), joined_sample); - neighbors.insert(new_id.clone(), joined_neighbors.clone()); - for other in joined_neighbors { - let candidate = if trace { - let candidate_started = std::time::Instant::now(); - let candidate = candidate_for( - campaign, - &profiles, - &groups, - &group_samples, - &new_id, - &other, - &scoring, - &demand, - &mandatory, - ); - candidate_elapsed += candidate_started.elapsed(); - candidate - } else { - candidate_for( - campaign, - &profiles, - &groups, - &group_samples, - &new_id, - &other, - &scoring, - &demand, - &mandatory, - ) - }; - if let Some(candidate) = candidate { - heap.push(candidate); - } - } - } - if trace { - eprintln!( - "partition merge: {:?}; candidates {:?}; heap pops {}", - trace_started.elapsed(), - candidate_elapsed, - heap_pops - ); - } - refine_boundaries( - campaign, - &profiles, - &graph, - &scoring, - &demand, - &mandatory, - &mut groups, - ); - if trace { - eprintln!("partition refine: {:?}", trace_started.elapsed()); - } - let highest_debt = profiles - .values() - .max_by(|left, right| { - left.detail_debt - .cmp(&right.detail_debt) - .then_with(|| right.subject_id.cmp(&left.subject_id)) - }) - .map(|profile| profile.subject_id.clone()); - let mut cells = Vec::new(); - for subjects in groups.values() { - let (mode, loss) = classify_and_score(campaign, &profiles, &scoring, subjects, &demand); - cells.push(SimulationCell { - schema: "ghostlight.simulation_cell.v1".into(), - id: cell_id(subjects, &mode), - mode, - subject_ids: subjects.clone(), - merge_loss: loss, - rationale: cut_rationale(subjects, &demand), - lease_until_world_revision: campaign.revision.saturating_add(5), - lease_until_strategic_tick: campaign.strategic_tick_count.saturating_add(2), - detail_focus_subject_id: highest_debt - .as_ref() - .filter(|id| subjects.contains(*id)) - .cloned(), - }); - } - cells.sort_by(|left, right| left.id.cmp(&right.id)); - if trace { - eprintln!("partition cells: {:?}", trace_started.elapsed()); - } - cells = preserve_previous_cover( - campaign, &profiles, &graph, &scoring, &demand, &mandatory, target, cells, - ); - validate_cover_with_graph(campaign, &demand, &cells, &graph)?; - if trace { - eprintln!("partition validate: {:?}", trace_started.elapsed()); - } - let effective_budget = cells.len().min(u8::MAX as usize) as u8; - Ok(ResolutionCover { - schema: "ghostlight.resolution_cover.v1".into(), - campaign_id: campaign.id, - world_revision: campaign.revision, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - configured_budget: campaign.resolution_policy.active_cell_budget, - effective_budget, - mandatory_overage: effective_budget - .saturating_sub(campaign.resolution_policy.active_cell_budget), - cells, - demand, - causal_follow_through: Vec::new(), - }) -} - -fn refine_boundaries( - campaign: &Campaign, - profiles: &BTreeMap, - graph: &DerivedAgencyGraph, - scoring: &ScoringCache, - demand: &ResolutionDemand, - mandatory: &BTreeSet, - groups: &mut HashMap>, -) { - let mut subject_group = HashMap::new(); - for (group_id, subjects) in groups.iter() { - for subject in subjects { - subject_group.insert(subject.clone(), group_id.clone()); - } - } - let subjects: Vec<_> = profiles.keys().cloned().collect(); - for subject in subjects { - if mandatory.contains(&subject) { - continue; - } - let Some(source_id) = subject_group.get(&subject).cloned() else { - continue; - }; - if groups - .get(&source_id) - .is_none_or(|values| values.len() <= 1) - { - continue; - } - let adjacent_groups: BTreeSet<_> = graph - .neighbors - .get(&subject) - .into_iter() - .flatten() - .filter_map(|neighbor| subject_group.get(neighbor).cloned()) - .filter(|id| id != &source_id) - .collect(); - if adjacent_groups.is_empty() { - continue; - } - let Some(source) = groups.get(&source_id).cloned() else { - continue; - }; - for destination_id in adjacent_groups { - let Some(destination) = groups.get(&destination_id).cloned() else { - continue; - }; - let mut next_source = source.clone(); - next_source.remove(&subject); - let mut next_destination = destination.clone(); - next_destination.insert(subject.clone()); - if !connected(graph, &next_source) - || !connected(graph, &next_destination) - || violates_separate_pin( - &BTreeSet::from([subject.clone()]), - &destination, - &campaign.resolution_pins, - ) - || breaks_together_pin( - &source_id, - &destination_id, - &subject, - groups, - &campaign.resolution_pins, - ) - { - continue; - } - let old_loss = compression_cost( - &classify_and_score(campaign, profiles, scoring, &source, demand).1, - source.len(), - ) + compression_cost( - &classify_and_score(campaign, profiles, scoring, &destination, demand).1, - destination.len(), - ); - let new_loss = compression_cost( - &classify_and_score(campaign, profiles, scoring, &next_source, demand).1, - next_source.len(), - ) + compression_cost( - &classify_and_score(campaign, profiles, scoring, &next_destination, demand).1, - next_destination.len(), - ); - if old_loss > f32::EPSILON && new_loss <= old_loss * 0.95 { - groups.insert(source_id.clone(), next_source); - groups.insert(destination_id.clone(), next_destination); - subject_group.insert(subject.clone(), destination_id); - break; - } - } - } -} - -fn breaks_together_pin( - source_id: &str, - destination_id: &str, - subject: &str, - groups: &HashMap>, - pins: &BTreeMap, -) -> bool { - pins.values() - .filter(|pin| { - pin.kind == ResolutionPinKind::KeepTogether && pin.subject_ids.contains(subject) - }) - .any(|pin| { - pin.subject_ids.iter().any(|other| { - other != subject - && groups - .get(source_id) - .is_some_and(|values| values.contains(other)) - && !groups - .get(destination_id) - .is_some_and(|values| values.contains(other)) - }) - }) -} - -fn preserve_previous_cover( - campaign: &Campaign, - profiles: &BTreeMap, - graph: &DerivedAgencyGraph, - scoring: &ScoringCache, - demand: &ResolutionDemand, - mandatory: &BTreeSet, - target: usize, - candidate: Vec, -) -> Vec { - let Some(previous) = campaign.resolution_cover.as_ref().filter(|cover| { - cover.resolution_epoch == campaign.resolution_policy.resolution_epoch - && cover.configured_budget == campaign.resolution_policy.active_cell_budget - && cover.cells.len() == target - }) else { - return candidate; - }; - if previous.cells.iter().any(|cell| { - cell.subject_ids.len() > 1 - && (!cell.subject_ids.is_disjoint(mandatory) || !connected(graph, &cell.subject_ids)) - }) { - return candidate; - } - let expected: BTreeSet<_> = profiles.keys().cloned().collect(); - let actual: BTreeSet<_> = previous - .cells - .iter() - .flat_map(|cell| cell.subject_ids.iter().cloned()) - .collect(); - if actual != expected { - return candidate; - } - let old_total: f32 = previous - .cells - .iter() - .map(|cell| { - compression_cost( - &classify_and_score(campaign, profiles, scoring, &cell.subject_ids, demand).1, - cell.subject_ids.len(), - ) - }) - .sum(); - let new_total: f32 = candidate - .iter() - .map(|cell| compression_cost(&cell.merge_loss, cell.subject_ids.len())) - .sum(); - let improvement = if old_total <= f32::EPSILON { - 0.0 - } else { - ((old_total - new_total) / old_total).max(0.0) - }; - let lease_active = previous.cells.iter().any(|cell| { - campaign.revision < cell.lease_until_world_revision - && campaign.strategic_tick_count < cell.lease_until_strategic_tick - }); - if !lease_active && improvement >= 0.10 { - return candidate; - } - let mut preserved: Vec<_> = previous - .cells - .iter() - .map(|cell| { - let (mode, merge_loss) = - classify_and_score(campaign, profiles, scoring, &cell.subject_ids, demand); - SimulationCell { - schema: "ghostlight.simulation_cell.v1".into(), - id: cell_id(&cell.subject_ids, &mode), - mode, - subject_ids: cell.subject_ids.clone(), - merge_loss, - rationale: format!("preserved partition: {}", cell.rationale), - lease_until_world_revision: cell.lease_until_world_revision, - lease_until_strategic_tick: cell.lease_until_strategic_tick, - detail_focus_subject_id: None, - } - }) - .collect(); - if let Some(highest_debt) = profiles - .values() - .max_by(|left, right| { - left.detail_debt - .cmp(&right.detail_debt) - .then_with(|| right.subject_id.cmp(&left.subject_id)) - }) - .map(|profile| profile.subject_id.as_str()) - && let Some(cell) = preserved - .iter_mut() - .find(|cell| cell.subject_ids.contains(highest_debt)) - { - cell.detail_focus_subject_id = Some(highest_debt.to_owned()); - } - preserved.sort_by(|left, right| left.id.cmp(&right.id)); - preserved -} - -fn compression_cost(loss: &MergeLoss, constituent_count: usize) -> f32 { - loss.total * constituent_count.saturating_sub(1) as f32 -} - -pub fn validate_demand(campaign: &Campaign, demand: &ResolutionDemand) -> Result<()> { - let axes = [ - AgencyAxis::Geography, - AgencyAxis::Ideology, - AgencyAxis::Authority, - AgencyAxis::EconomyRole, - AgencyAxis::SpeciesBody, - AgencyAxis::Information, - ]; - if demand.campaign_id != campaign.id - || demand.world_revision != campaign.revision - || demand.resolution_epoch != campaign.resolution_policy.resolution_epoch - || demand.horizon_minutes == 0 - || demand.rationale.trim().is_empty() - || axes.iter().any(|axis| { - demand - .axis_weights - .get(axis) - .is_none_or(|weight| !weight.is_finite() || !(0.0..=1.0).contains(weight)) - }) - || demand - .focal_subject_ids - .iter() - .any(|id| !campaign.agency_profiles.contains_key(id)) - { - return Err(anyhow!("resolution demand is stale or malformed")); - } - let sum: f32 = demand.axis_weights.values().sum(); - if (sum - 1.0).abs() > 0.02 { - return Err(anyhow!("resolution demand axis weights must sum to one")); - } - Ok(()) -} - -pub fn cell_action_limit(cell: &SimulationCell) -> usize { - match cell.mode { - SimulationCellMode::Cohesive => 1, - SimulationCellMode::Arena => { - let count = cell.subject_ids.len().max(1); - let ceil_log = if count <= 1 { - 0 - } else { - usize::BITS - (count - 1).leading_zeros() - }; - 4usize.min(1 + ceil_log as usize) - } - } -} - -fn mandatory_subjects(campaign: &Campaign) -> BTreeSet { - let mut mandatory = BTreeSet::new(); - for pin in campaign.resolution_pins.values() { - if pin.kind == ResolutionPinKind::MinimumIndividualDetail { - mandatory.extend(pin.subject_ids.iter().cloned()); - } - } - for member in campaign.gestalt_members.values() { - if member.relevance_lease_until_revision > campaign.revision - && let Some(actor_id) = &member.materialized_actor_id - { - mandatory.insert(actor_id.clone()); - } - } - mandatory -} - -fn contract_together_pins( - groups: &mut HashMap>, - pins: &BTreeMap, - mandatory: &BTreeSet, -) { - for pin in pins - .values() - .filter(|pin| pin.kind == ResolutionPinKind::KeepTogether) - { - if !pin.subject_ids.is_disjoint(mandatory) { - continue; - } - let keys: Vec<_> = groups - .iter() - .filter(|(_, subjects)| !subjects.is_disjoint(&pin.subject_ids)) - .map(|(key, _)| key.clone()) - .collect(); - let mut joined = BTreeSet::new(); - for key in keys { - if let Some(subjects) = groups.remove(&key) { - joined.extend(subjects); - } - } - if !joined.is_empty() { - groups.insert(cell_id(&joined, &SimulationCellMode::Arena), joined); - } - } -} - -fn candidates( - campaign: &Campaign, - profiles: &BTreeMap, - groups: &HashMap>, - group_samples: &HashMap>, - neighbors: &HashMap>, - scoring: &ScoringCache, - demand: &ResolutionDemand, - mandatory: &BTreeSet, -) -> BinaryHeap { - let mut heap = BinaryHeap::new(); - for (left, adjacent) in neighbors { - for right in adjacent.iter().filter(|right| left < *right) { - if let Some(candidate) = candidate_for( - campaign, - profiles, - groups, - group_samples, - left, - right, - scoring, - demand, - mandatory, - ) { - heap.push(candidate); - } - } - } - heap -} - -fn candidate_for( - campaign: &Campaign, - profiles: &BTreeMap, - groups: &HashMap>, - group_samples: &HashMap>, - left_id: &str, - right_id: &str, - scoring: &ScoringCache, - demand: &ResolutionDemand, - mandatory: &BTreeSet, -) -> Option { - let left = groups.get(left_id)?; - let right = groups.get(right_id)?; - if !left.is_disjoint(mandatory) - || !right.is_disjoint(mandatory) - || violates_separate_pin(left, right, &campaign.resolution_pins) - { - return None; - } - let sample = representative_sample( - group_samples - .get(left_id)? - .iter() - .chain(group_samples.get(right_id)?.iter()), - ); - let loss = score_merge(campaign, profiles, scoring, left, right, &sample, demand); - let (left, right) = if left_id <= right_id { - (left_id.to_owned(), right_id.to_owned()) - } else { - (right_id.to_owned(), left_id.to_owned()) - }; - Some(Candidate { left, right, loss }) -} - -fn group_neighbors( - groups: &HashMap>, - graph: &DerivedAgencyGraph, -) -> HashMap> { - let mut subject_group = HashMap::new(); - for (group_id, subjects) in groups { - for subject in subjects { - subject_group.insert(subject.clone(), group_id.clone()); - } - } - let mut result: HashMap<_, _> = groups - .keys() - .map(|id| (id.clone(), BTreeSet::new())) - .collect(); - for (subject, adjacent) in &graph.neighbors { - let Some(left) = subject_group.get(subject) else { - continue; - }; - for other in adjacent { - let Some(right) = subject_group.get(other) else { - continue; - }; - if left != right { - result - .entry(left.clone()) - .or_default() - .insert(right.clone()); - result - .entry(right.clone()) - .or_default() - .insert(left.clone()); - } - } - } - result -} - -fn violates_separate_pin( - left: &BTreeSet, - right: &BTreeSet, - pins: &BTreeMap, -) -> bool { - pins.values() - .filter(|pin| pin.kind == ResolutionPinKind::KeepSeparate) - .any(|pin| !left.is_disjoint(&pin.subject_ids) && !right.is_disjoint(&pin.subject_ids)) -} - -fn classify_and_score( - campaign: &Campaign, - profiles: &BTreeMap, - scoring: &ScoringCache, - subjects: &BTreeSet, - demand: &ResolutionDemand, -) -> (SimulationCellMode, MergeLoss) { - if subjects.len() <= 1 { - return (SimulationCellMode::Cohesive, MergeLoss::default()); - } - let sampled = bounded_profiles(profiles, subjects); - classify_selection( - campaign, - profiles, - scoring, - sampled, - subjects.iter(), - |id| subjects.contains(id), - subjects.len(), - demand, - ) -} - -fn score_merge( - campaign: &Campaign, - profiles: &BTreeMap, - scoring: &ScoringCache, - left: &BTreeSet, - right: &BTreeSet, - sample_subject_ids: &[String], - demand: &ResolutionDemand, -) -> MergeLoss { - let constituent_count = left.len() + right.len(); - let sampled = sample_subject_ids - .iter() - .filter_map(|id| profiles.get(id)) - .collect(); - classify_selection( - campaign, - profiles, - scoring, - sampled, - std::iter::empty::<&String>(), - |id| left.contains(id) || right.contains(id), - constituent_count, - demand, - ) - .1 -} - -fn classify_selection<'a, I, F>( - campaign: &Campaign, - profiles: &BTreeMap, - scoring: &ScoringCache, - sampled: Vec<&AgencyProfile>, - authority_subjects: I, - contains: F, - constituent_count: usize, - demand: &ResolutionDemand, -) -> (SimulationCellMode, MergeLoss) -where - I: IntoIterator, - F: Fn(&str) -> bool, -{ - let facet = weighted_facet_divergence(&sampled, demand); - let information = set_divergence( - &sampled - .iter() - .map(|profile| &profile.information_channels) - .collect::>(), - ); - let spatial = spatial_divergence(campaign, &sampled, demand.horizon_minutes); - let obligation_sets: Vec<_> = sampled - .iter() - .filter_map(|profile| scoring.pressure_tokens.get(&profile.subject_id)) - .collect(); - let clock_obligation = set_divergence(&obligation_sets); - let mut authorities = BTreeSet::new(); - for subject in authority_subjects { - if let Some(authority) = profiles - .get(subject) - .and_then(|profile| profile.collective_authority_id.as_deref()) - { - authorities.insert(authority); - if authorities.len() > 1 { - break; - } - } - } - let hostile = campaign.agency_relations.values().any(|relation| { - relation.active - && matches!( - relation.kind, - AgencyRelationKind::Rivalry | AgencyRelationKind::Coercion - ) - && contains(&relation.from_subject_id) - && contains(&relation.to_subject_id) - }); - let boundary = hidden_boundary_mass_where(campaign, &contains); - let salience = sampled - .iter() - .filter_map(|profile| scoring.salience.get(&profile.subject_id).copied()) - .fold(0.0_f32, f32::max); - let churn = campaign.resolution_cover.as_ref().is_some_and(|cover| { - !cover.cells.iter().any(|cell| { - cell.subject_ids.len() == constituent_count - && cell.subject_ids.iter().all(|id| contains(id)) - }) - }) as u8 as f32; - let total = 0.25 * facet - + 0.20 * boundary - + 0.15 * information - + 0.15 * spatial - + 0.10 * clock_obligation - + 0.10 * salience - + 0.05 * churn; - let loss = MergeLoss { - facet_divergence: facet, - hidden_boundary_mass: boundary, - information_divergence: information, - spatial_divergence: spatial, - clock_obligation_divergence: clock_obligation, - salience_burial: salience, - partition_churn: churn, - total, - }; - let cohesive = authorities.len() == 1 - && !hostile - && information <= 0.20 - && facet <= 0.25 - && clock_obligation <= 0.25; - ( - if cohesive { - SimulationCellMode::Cohesive - } else { - SimulationCellMode::Arena - }, - loss, - ) -} - -fn bounded_profiles<'a>( - profiles: &'a BTreeMap, - subjects: &BTreeSet, -) -> Vec<&'a AgencyProfile> { - let stride = subjects.len().div_ceil(PROFILE_SAMPLE_LIMIT).max(1); - subjects - .iter() - .step_by(stride) - .take(PROFILE_SAMPLE_LIMIT) - .filter_map(|id| profiles.get(id)) - .collect() -} - -const PROFILE_SAMPLE_LIMIT: usize = 8; - -fn representative_sample<'a>(subjects: impl Iterator) -> Vec { - let mut ranked = subjects - .map(|id| (sample_rank(id), id.clone())) - .collect::>(); - ranked.sort_unstable(); - ranked.dedup_by(|left, right| left.1 == right.1); - ranked.truncate(PROFILE_SAMPLE_LIMIT); - ranked.into_iter().map(|(_, id)| id).collect() -} - -fn sample_rank(id: &str) -> u64 { - id.as_bytes().iter().fold(0xcbf29ce484222325, |hash, byte| { - (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3) - }) -} - -fn pressure_tokens(campaign: &Campaign, subject_id: &str) -> BTreeSet { - if let Some(actor) = campaign.actors.get(subject_id) { - return actor - .obligations - .iter() - .cloned() - .chain(actor.goals.iter().map(|value| format!("goal:{value}"))) - .chain( - actor - .conditions - .iter() - .map(|value| format!("condition:{value}")), - ) - .collect(); - } - if let Some(institution) = campaign.institutions.get(subject_id) { - return institution - .goals - .iter() - .map(|value| format!("goal:{value}")) - .chain(std::iter::once(format!("posture:{}", institution.posture))) - .collect(); - } - campaign - .gestalts - .get(subject_id) - .map(|gestalt| { - gestalt - .goals - .iter() - .map(|value| format!("goal:{value}")) - .chain( - gestalt - .pressures - .iter() - .map(|value| format!("pressure:{value}")), - ) - .collect() - }) - .unwrap_or_default() -} - -fn subject_salience(campaign: &Campaign, profile: &AgencyProfile) -> f32 { - let debt = profile.detail_debt.min(64) as f32 / 64.0; - let event = campaign.events.iter().rev().take(16).any(|event| { - event.actor_ids.contains(&profile.subject_id) - || event.institution_ids.contains(&profile.subject_id) - || event.gestalt_ids.contains(&profile.subject_id) - }) as u8 as f32; - let conflict = campaign.agency_relations.values().any(|relation| { - relation.active - && matches!( - relation.kind, - AgencyRelationKind::Rivalry | AgencyRelationKind::Coercion - ) - && (relation.from_subject_id == profile.subject_id - || relation.to_subject_id == profile.subject_id) - }) as u8 as f32; - (0.45 * debt + 0.30 * event + 0.25 * conflict).clamp(0.0, 1.0) -} - -fn spatial_divergence( - campaign: &Campaign, - profiles: &[&AgencyProfile], - horizon_minutes: u32, -) -> f32 { - if profiles.len() <= 1 { - return 0.0; - } - let mut total = 0.0; - let mut pairs = 0u32; - for (index, left) in profiles.iter().enumerate() { - for right in profiles.iter().skip(index + 1) { - let distance = if !left.location_ids.is_disjoint(&right.location_ids) { - 0.0 - } else { - let minutes = left - .location_ids - .iter() - .flat_map(|location| { - campaign - .locations - .get(location) - .into_iter() - .flat_map(|value| value.routes.values()) - }) - .filter(|route| right.location_ids.contains(&route.destination_id)) - .map(|route| route.travel_minutes) - .min(); - minutes - .map(|minutes| minutes as f32 / horizon_minutes.max(1) as f32) - .unwrap_or(1.0) - .clamp(0.0, 1.0) - }; - total += distance; - pairs += 1; - } - } - total / pairs.max(1) as f32 -} - -fn weighted_facet_divergence(profiles: &[&AgencyProfile], demand: &ResolutionDemand) -> f32 { - demand - .axis_weights - .iter() - .map(|(axis, weight)| { - let empty = BTreeSet::new(); - let sets: Vec<_> = profiles - .iter() - .map(|profile| profile.facets.get(axis).unwrap_or(&empty)) - .collect(); - weight * set_divergence(&sets) - }) - .sum::() - .clamp(0.0, 1.0) -} - -fn set_divergence(sets: &[&BTreeSet]) -> f32 { - if sets.len() <= 1 { - return 0.0; - } - let mut total = 0.0; - let mut pairs = 0; - for (index, left) in sets.iter().enumerate() { - for right in sets.iter().skip(index + 1) { - let union = left.union(right).count(); - let similarity = if union == 0 { - 1.0 - } else { - left.intersection(right).count() as f32 / union as f32 - }; - total += 1.0 - similarity; - pairs += 1; - } - } - if pairs == 0 { - 0.0 - } else { - total / pairs as f32 - } -} - -fn hidden_boundary_mass_where(campaign: &Campaign, contains: &F) -> f32 -where - F: Fn(&str) -> bool, -{ - let mut mass = 0u32; - let mut possible = 0u32; - for relation in campaign - .agency_relations - .values() - .filter(|relation| relation.active) - { - if contains(&relation.from_subject_id) && contains(&relation.to_subject_id) { - possible += 100; - if !matches!( - relation.kind, - AgencyRelationKind::Containment | AgencyRelationKind::SharedLocation - ) { - mass += u32::from(relation.strength); - } - } - } - if possible == 0 { - 0.0 - } else { - mass as f32 / possible as f32 - } -} - -fn cut_rationale(subjects: &BTreeSet, demand: &ResolutionDemand) -> String { - let axis = demand - .axis_weights - .iter() - .max_by(|left, right| left.1.total_cmp(right.1).then_with(|| left.0.cmp(right.0))) - .map(|(axis, _)| format!("{axis:?}").to_lowercase()) - .unwrap_or_else(|| "mixed".into()); - format!( - "{} subjects grouped under {axis}-weighted demand", - subjects.len() - ) -} - -fn cell_id(subjects: &BTreeSet, mode: &SimulationCellMode) -> String { - let material = format!( - "{mode:?}:{}", - subjects.iter().cloned().collect::>().join("|") - ); - format!("cell:{:x}", Sha256::digest(material.as_bytes())) -} - -pub fn validate_cover( - campaign: &Campaign, - demand: &ResolutionDemand, - cells: &[SimulationCell], -) -> Result<()> { - let graph = DerivedAgencyGraph::build( - campaign, - campaign - .agency_profiles - .values() - .filter(|profile| profile.active_leaf && profile.simulation_eligible) - .map(|profile| profile.subject_id.clone()) - .collect(), - ); - validate_cover_with_graph(campaign, demand, cells, &graph) -} - -fn validate_cover_with_graph( - campaign: &Campaign, - demand: &ResolutionDemand, - cells: &[SimulationCell], - graph: &DerivedAgencyGraph, -) -> Result<()> { - let scoring = ScoringCache::new(campaign, &campaign.agency_profiles); - let expected: BTreeSet<_> = campaign - .agency_profiles - .values() - .filter(|profile| profile.active_leaf && profile.simulation_eligible) - .map(|profile| profile.subject_id.clone()) - .collect(); - let mut actual = BTreeSet::new(); - for cell in cells { - if cell.subject_ids.is_empty() { - return Err(anyhow!("resolution cell {} is empty", cell.id)); - } - if let Some(duplicate) = cell - .subject_ids - .iter() - .find(|id| !actual.insert((*id).clone())) - { - return Err(anyhow!( - "resolution subject {duplicate} appears in more than one cell" - )); - } - if cell.subject_ids.len() > 1 && !connected(graph, &cell.subject_ids) { - return Err(anyhow!( - "resolution cell {} is disconnected in the current agency graph", - cell.id - )); - } - if cell.id != cell_id(&cell.subject_ids, &cell.mode) { - return Err(anyhow!( - "resolution cell {} does not match its subjects and mode", - cell.id - )); - } - if cell.mode == SimulationCellMode::Cohesive - && classify_and_score( - campaign, - &campaign.agency_profiles, - &scoring, - &cell.subject_ids, - demand, - ) - .0 != SimulationCellMode::Cohesive - { - return Err(anyhow!( - "resolution cell {} claims collective agency without current cohesive authority", - cell.id - )); - } - } - if actual != expected { - return Err(anyhow!( - "resolution cover does not cover every active subject exactly once" - )); - } - Ok(()) -} - -fn connected(graph: &DerivedAgencyGraph, subjects: &BTreeSet) -> bool { - let Some(start) = subjects.iter().next() else { - return false; - }; - let mut seen = BTreeSet::from([start.clone()]); - let mut queue = VecDeque::from([start.clone()]); - while let Some(current) = queue.pop_front() { - for next in graph.neighbors.get(¤t).into_iter().flatten() { - if subjects.contains(next) && seen.insert(next.clone()) { - queue.push_back(next.clone()); - } - } - } - seen == *subjects -} - -pub fn advance_detail_debt(campaign: &mut Campaign, cover: &ResolutionCover) { - let focused: BTreeSet<_> = cover - .cells - .iter() - .filter_map(|cell| cell.detail_focus_subject_id.clone()) - .chain( - cover - .cells - .iter() - .filter(|cell| cell.subject_ids.len() == 1) - .flat_map(|cell| cell.subject_ids.iter().cloned()), - ) - .collect(); - for profile in campaign - .agency_profiles - .values_mut() - .filter(|profile| profile.active_leaf) - { - if focused.contains(&profile.subject_id) { - profile.detail_debt = 0; - profile.last_detail_tick = campaign.strategic_tick_count.saturating_add(1); - } else { - profile.detail_debt = profile.detail_debt.saturating_add(1); - } - profile.profile_version = profile.profile_version.saturating_add(1); - } -} - -pub fn plan_receipt(campaign: &Campaign, cover: &ResolutionCover) -> ResolutionPlanReceipt { - let previous: BTreeSet<_> = campaign - .resolution_cover - .as_ref() - .map(|value| value.cells.iter().map(|cell| cell.id.clone()).collect()) - .unwrap_or_default(); - let current: BTreeSet<_> = cover.cells.iter().map(|cell| cell.id.clone()).collect(); - let preserved_cell_ids = current.intersection(&previous).cloned().collect::>(); - let collapsed_boundaries = cover - .cells - .iter() - .filter(|cell| cell.subject_ids.len() > 1) - .map(|cell| { - format!( - "{}:{}", - match cell.mode { - SimulationCellMode::Cohesive => "cohesive", - SimulationCellMode::Arena => "arena", - }, - cell.subject_ids - .iter() - .cloned() - .collect::>() - .join("|") - ) - }) - .collect(); - ResolutionPlanReceipt { - schema: "ghostlight.resolution_plan_receipt.v1".into(), - campaign_id: campaign.id, - world_revision: campaign.revision, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - configured_budget: cover.configured_budget, - effective_budget: cover.effective_budget, - cell_ids: cover.cells.iter().map(|cell| cell.id.clone()).collect(), - mandatory_overage: cover.mandatory_overage, - preserved_cell_ids, - collapsed_boundaries, - merge_losses: cover - .cells - .iter() - .map(|cell| (cell.id.clone(), cell.merge_loss.clone())) - .collect(), - rationale: format!( - "{} active cells under {:?}-weighted pressure; {} mandatory overage", - cover.effective_budget, - cover - .demand - .axis_weights - .iter() - .max_by(|left, right| left.1.total_cmp(right.1)) - .map(|(axis, _)| axis), - cover.mandatory_overage - ), - created_at: chrono::Utc::now(), - } -} - -#[derive(Clone, Debug)] -pub struct ResolutionWaveSelection { - pub plan: StrategicTickPlan, - pub activity_proposals: Vec, -} - -pub fn cell_action_digest(proposal: &CellActionProposal) -> Result { - Ok(format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(proposal)?) - )) -} - -pub fn select_resolution_wave( - campaign: &Campaign, - wave: &ResolutionWaveCommit, -) -> Result { - if wave.world_revision != campaign.revision - || wave.resolution_epoch != campaign.resolution_policy.resolution_epoch - || wave.cover.world_revision != campaign.revision - || wave.cover.resolution_epoch != campaign.resolution_policy.resolution_epoch - || wave.plan_receipt.world_revision != campaign.revision - || wave.plan_receipt.resolution_epoch != campaign.resolution_policy.resolution_epoch - || wave - .model_receipt_hashes - .iter() - .any(|hash| !is_sha256(hash)) - { - return Err(anyhow!("resolution wave is stale or malformed")); - } - validate_demand(campaign, &wave.cover.demand)?; - validate_cover(campaign, &wave.cover.demand, &wave.cover.cells)?; - crate::follow_through::validate_causal_follow_through(campaign, &wave.cover)?; - if wave.plan_receipt.cell_ids - != wave - .cover - .cells - .iter() - .map(|cell| cell.id.clone()) - .collect::>() - { - return Err(anyhow!("resolution receipt does not bind the active cover")); - } - let cells: BTreeMap<_, _> = wave - .cover - .cells - .iter() - .map(|cell| (cell.id.as_str(), cell)) - .collect(); - if wave.appraisals.len() != cells.len() { - return Err(anyhow!( - "every active cell must appraise the wave exactly once" - )); - } - let mut seen_cells = BTreeSet::new(); - let mut proposals = Vec::new(); - for appraisal in &wave.appraisals { - let cell = cells - .get(appraisal.cell_id.as_str()) - .ok_or_else(|| anyhow!("cell appraisal references an inactive cell"))?; - if !seen_cells.insert(appraisal.cell_id.as_str()) - || appraisal.schema != "ghostlight.cell_appraisal.v1" - || appraisal.world_revision != campaign.revision - || appraisal.resolution_epoch != campaign.resolution_policy.resolution_epoch - { - return Err(anyhow!("cell appraisal is incomplete or stale")); - } - let quota = cell_action_limit(cell); - if appraisal.considered_subject_ids.is_empty() - || appraisal.considered_subject_ids.len() > quota - { - return Err(anyhow!("cell appraisal exceeds its action quota")); - } - if appraisal - .considered_subject_ids - .iter() - .any(|subject_id| !cell_contains_attributed_subject(campaign, cell, subject_id)) - { - return Err(anyhow!( - "cell appraisal considered a subject outside its exact cell authority" - )); - } - let causal_assignments = - crate::follow_through::assignments_for_cell(campaign, &wave.cover, cell); - if causal_assignments.iter().any(|assignment| { - !appraisal - .considered_subject_ids - .contains(&assignment.responder_subject_id) - }) { - return Err(anyhow!( - "cell appraisal omitted a scheduler-admitted causal responder" - )); - } - if cell - .detail_focus_subject_id - .as_ref() - .is_some_and(|focus| !appraisal.considered_subject_ids.contains(focus)) - { - return Err(anyhow!( - "cell appraisal omitted its mandatory detail-focus subject" - )); - } - let mut action_subject_ids = BTreeSet::new(); - for proposal in &appraisal.actions { - if !action_subject_ids.insert(proposal.subject_id.as_str()) - || !appraisal - .considered_subject_ids - .contains(&proposal.subject_id) - { - return Err(anyhow!( - "cell appraisal contains a duplicate or unconsidered action owner" - )); - } - } - let mut inaction_subject_ids = BTreeSet::new(); - for inaction in &appraisal.inactions { - if inaction.reason.trim().is_empty() - || inaction.reason.chars().count() > 240 - || action_subject_ids.contains(inaction.subject_id.as_str()) - || !inaction_subject_ids.insert(inaction.subject_id.as_str()) - || !appraisal - .considered_subject_ids - .contains(&inaction.subject_id) - || !cell_contains_attributed_subject(campaign, cell, &inaction.subject_id) - { - return Err(anyhow!( - "cell appraisal contains an invalid attributed inaction" - )); - } - } - let decided_subject_ids = action_subject_ids - .iter() - .chain(&inaction_subject_ids) - .copied() - .collect::>(); - if decided_subject_ids - != appraisal - .considered_subject_ids - .iter() - .map(String::as_str) - .collect::>() - { - return Err(anyhow!( - "every considered cell subject must own exactly one action or explicit inaction" - )); - } - for proposal in &appraisal.actions { - let causal_assignment = causal_assignments - .iter() - .find(|assignment| assignment.responder_subject_id == proposal.subject_id) - .copied(); - if causal_assignment.is_some_and(|assignment| { - !proposal - .state_references - .contains(&assignment.anchor_reference) - }) { - return Err(anyhow!( - "causal response action does not cite its admitted committed anchor" - )); - } - let mut scoped_proposal = proposal.clone(); - if let Some(assignment) = causal_assignment { - scoped_proposal - .state_references - .retain(|reference| reference != &assignment.anchor_reference); - } - validate_cell_proposal(campaign, cell, &scoped_proposal)?; - proposals.push(proposal.clone()); - } - } - proposals.sort_by(|left, right| { - right - .priority - .cmp(&left.priority) - .then_with(|| left.subject_id.cmp(&right.subject_id)) - .then_with(|| left.intent.cmp(&right.intent)) - }); - let consequence_limit = 16usize.min(usize::from(wave.cover.effective_budget) * 2); - let mut used = BTreeSet::new(); - let mut selected_actions = Vec::new(); - let mut selected_effect_count = 0usize; - let mut activity_proposals = Vec::new(); - for proposal in proposals { - let key = proposal_target_key(&proposal); - if !used.insert(key) { - continue; - } - if selected_effect_count.saturating_add(proposal.effects.len()) > consequence_limit { - continue; - } - let is_activity = proposal.effects.iter().any(|effect| { - matches!( - effect, - StrategicCellEffect::GestaltActivity { .. } - | StrategicCellEffect::ActorActivity { .. } - | StrategicCellEffect::MemberActivity { .. } - ) - }); - let selected_activity_proposal = is_activity.then(|| proposal.clone()); - selected_effect_count += proposal.effects.len(); - selected_actions.push(proposal); - if let Some(proposal) = selected_activity_proposal { - activity_proposals.push(proposal); - } - } - let plan = project_selected_actions(campaign, selected_actions)?; - Ok(ResolutionWaveSelection { - plan, - activity_proposals, - }) -} - -pub(crate) fn project_selected_actions( - campaign: &Campaign, - selected_actions: Vec, -) -> Result { - let mut plan = StrategicTickPlan { - selected_actions: selected_actions.clone(), - ..StrategicTickPlan::default() - }; - for proposal in selected_actions { - let action_digest = cell_action_digest(&proposal)?; - for effect in proposal.effects { - match effect { - StrategicCellEffect::Institution { - institution_id, - posture, - location_ids, - } => plan.institution_actions.push(StrategicInstitutionAction { - institution_id, - posture, - location_ids, - public_channels: proposal.public_channels.clone(), - }), - StrategicCellEffect::Gestalt { - gestalt_id, - pressure_additions, - pressure_resolutions, - } => plan.gestalt_actions.push(StrategicGestaltAction { - gestalt_id, - pressure_additions, - pressure_resolutions, - public_channels: proposal.public_channels.clone(), - }), - StrategicCellEffect::GestaltActivity { - gestalt_id, - activity, - target_subject_ids, - location_ids, - } => plan.gestalt_activities.push(StrategicGestaltActivity { - action_digest: action_digest.clone(), - gestalt_id, - activity, - target_subject_ids, - location_ids, - public_channels: proposal.public_channels.clone(), - }), - StrategicCellEffect::GestaltMigration { - destination_gestalt_id, - } => { - let gestalt_id = proposal.subject_id.clone(); - if !campaign.gestalts.contains_key(&gestalt_id) { - return Err(anyhow!("strategic migration source vanished")); - } - let destination_location_id = campaign - .gestalts - .get(&destination_gestalt_id) - .ok_or_else(|| anyhow!("strategic migration destination vanished"))? - .home_location_id - .clone(); - plan.gestalt_migrations.push(StrategicGestaltMigration { - gestalt_id, - destination_gestalt_id, - destination_location_id, - public_channels: proposal.public_channels.clone(), - }); - } - StrategicCellEffect::ActorMove { - actor_id, - destination_id, - } => plan.actor_moves.push(StrategicActorMove { - actor_id, - destination_id, - public_channels: proposal.public_channels.clone(), - }), - StrategicCellEffect::ActorActivity { - actor_id, - activity, - target_subject_ids, - location_ids, - } => plan.actor_activities.push(StrategicActorActivity { - action_digest: action_digest.clone(), - actor_id, - activity, - target_subject_ids, - location_ids, - public_channels: proposal.public_channels.clone(), - }), - StrategicCellEffect::MemberActivity { - member_id, - activity, - target_subject_ids, - location_ids, - } => { - let source_gestalt_id = campaign - .gestalt_members - .get(&member_id) - .ok_or_else(|| anyhow!("strategic member vanished"))? - .gestalt_id - .clone(); - plan.member_activities.push(StrategicMemberActivity { - action_digest: action_digest.clone(), - member_id, - source_gestalt_id, - activity, - target_subject_ids, - location_ids, - public_channels: proposal.public_channels.clone(), - }); - } - StrategicCellEffect::MemberMigration { - destination_gestalt_id, - } => { - let member_id = proposal - .subject_id - .strip_prefix("member:") - .ok_or_else(|| anyhow!("member migration lacks exact member authority"))? - .to_owned(); - let source_gestalt_id = campaign - .gestalt_members - .get(&member_id) - .ok_or_else(|| anyhow!("strategic member vanished"))? - .gestalt_id - .clone(); - let destination_location_id = campaign - .gestalts - .get(&destination_gestalt_id) - .ok_or_else(|| anyhow!("member migration destination vanished"))? - .home_location_id - .clone(); - plan.member_migrations.push(StrategicMemberMigration { - member_id, - source_gestalt_id, - destination_gestalt_id, - destination_location_id, - public_channels: proposal.public_channels.clone(), - }); - } - } - } - } - Ok(plan) -} - -pub fn validate_and_resolve_wave( - campaign: &Campaign, - wave: &ResolutionWaveCommit, -) -> Result { - let mut selection = select_resolution_wave(campaign, wave)?; - crate::outcome::validate_activity_outcomes( - campaign, - &selection.activity_proposals, - &wave.activity_outcomes, - )?; - validate_strategic_individuations(campaign, wave, &selection.plan.selected_actions)?; - selection.plan.activity_outcomes = wave.activity_outcomes.clone(); - Ok(selection.plan) -} - -fn validate_strategic_individuations( - campaign: &Campaign, - wave: &ResolutionWaveCommit, - selected_actions: &[CellActionProposal], -) -> Result<()> { - validate_strategic_individuation_proposals( - campaign, - &wave.strategic_individuations, - selected_actions, - ) -} - -pub fn validate_gestalt_individuation( - campaign: &Campaign, - individuation: &GestaltIndividuation, -) -> Result<()> { - let member = &individuation.member; - let profile = campaign - .agency_profiles - .get(&individuation.gestalt_id) - .ok_or_else(|| anyhow!("individuation Gestalt has no agency profile"))?; - let mut findings = Vec::new(); - if let Err(error) = validate_active_gestalt_presence_location( - campaign, - &individuation.gestalt_id, - &individuation.location_id, - ) { - findings.push(error.to_string()); - } - let parent = campaign.gestalts.get(&individuation.gestalt_id); - if parent.is_none() { - findings.push("parent Gestalt does not exist".to_owned()); - } - if !profile.active_leaf { - findings.push("parent Gestalt is not an active leaf".to_owned()); - } - if !profile.simulation_eligible { - findings.push("parent Gestalt is not simulation eligible".to_owned()); - } - if parent.is_some_and(|parent| individuation.expected_gestalt_version != parent.version) { - findings.push("expected Gestalt version does not match the canonical parent".to_owned()); - } - if member.schema != "ghostlight.gestalt_member_delta.v1" { - findings.push("member schema is unsupported".to_owned()); - } - if member.gestalt_id != individuation.gestalt_id { - findings.push("member Gestalt id does not match the canonical parent".to_owned()); - } - if member.version != 0 { - findings.push("new member version must be zero".to_owned()); - } - if member.materialized_actor_id.is_some() { - findings.push("new member cannot claim a materialized Actor id".to_owned()); - } - if member.id.trim().is_empty() { - findings.push("member id is empty".to_owned()); - } - if member.id.chars().count() > 80 { - findings.push("member id exceeds 80 characters".to_owned()); - } - if member.name.trim().is_empty() { - findings.push("member name is empty".to_owned()); - } - if member.name.chars().count() > 160 { - findings.push("member name exceeds 160 characters".to_owned()); - } - let public_name_key = public_identity_key(&member.name); - if public_name_key.is_empty() { - findings.push("member name has no public identity characters".to_owned()); - } - if campaign - .actors - .values() - .any(|actor| public_identity_key(&actor.name) == public_name_key) - && !public_name_key.is_empty() - { - findings.push("member name duplicates an established public Actor identity".to_owned()); - } - if campaign - .gestalt_members - .values() - .any(|existing| public_identity_key(&existing.name) == public_name_key) - && !public_name_key.is_empty() - { - findings - .push("member name duplicates an established public population identity".to_owned()); - } - if member.goals.len() > 8 { - findings.push("member has more than eight goals".to_owned()); - } - if member.memories.len() > 8 { - findings.push("member has more than eight memories".to_owned()); - } - if member.obligations.len() > 8 { - findings.push("member has more than eight obligations".to_owned()); - } - if serde_json::to_vec(member).is_ok_and(|encoded| encoded.len() > 16_384) { - findings.push("member delta exceeds 16384 encoded bytes".to_owned()); - } - if campaign - .gestalt_members - .contains_key(&crate::domain::canonical_gestalt_member_local_id( - &member.id, - )) - { - findings.push("member id duplicates an established population identity".to_owned()); - } - if canonical_subject_id_is_occupied( - campaign, - &crate::domain::gestalt_member_subject_id(&member.id), - ) { - findings.push("member id duplicates an established canonical subject identity".to_owned()); - } - let unsupported_relationships = member - .relationships - .keys() - .filter(|subject_id| { - !campaign.actors.contains_key(*subject_id) - && !campaign.institutions.contains_key(*subject_id) - && !campaign.gestalts.contains_key(*subject_id) - && subject_id - .strip_prefix("member:") - .is_none_or(|member_id| !campaign.gestalt_members.contains_key(member_id)) - }) - .cloned() - .collect::>(); - if !unsupported_relationships.is_empty() { - findings.push(format!( - "member relationships reference unsupported subjects: {}", - unsupported_relationships.join(", ") - )); - } - if findings.is_empty() { - Ok(()) - } else { - Err(anyhow!( - "gestalt individuation exceeds its exact population authority: {}", - findings.join("; ") - )) - } -} - -/// Public names are an interface identity, not merely decorative text. Fold -/// case and punctuation so spelling variants such as `Flint-Measure` and -/// `Flintmeasure` cannot silently create two apparently identical people. -pub fn public_identity_key(value: &str) -> String { - value - .chars() - .filter(|character| character.is_alphanumeric()) - .flat_map(char::to_lowercase) - .collect() -} - -pub(crate) fn validate_strategic_individuation_proposals( - campaign: &Campaign, - proposals: &[StrategicGestaltIndividuation], - selected_actions: &[CellActionProposal], -) -> Result<()> { - if proposals.len() > 1 { - return Err(anyhow!( - "one strategic wave can admit at most one new person" - )); - } - let selected = selected_actions - .iter() - .map(|action| Ok((cell_action_digest(action)?, action))) - .collect::>>()?; - for proposal in proposals { - let action = selected - .get(&proposal.action_digest) - .ok_or_else(|| anyhow!("strategic individuation is not bound to a selected action"))?; - let individuation = &proposal.individuation; - if proposal.schema != "ghostlight.strategic_gestalt_individuation.v1" - || proposal.rationale.trim().is_empty() - || proposal.rationale.chars().count() > 460 - || action.subject_id != individuation.gestalt_id - || validate_gestalt_individuation(campaign, individuation).is_err() - { - return Err(anyhow!( - "strategic individuation exceeds its exact Gestalt action authority" - )); - } - } - Ok(()) -} - -fn validate_cell_proposal( - campaign: &Campaign, - cell: &SimulationCell, - proposal: &CellActionProposal, -) -> Result<()> { - if is_human_controlled_actor(campaign, &proposal.subject_id) - || proposal.intent.trim().is_empty() - || proposal.intent.chars().count() > 460 - || proposal.intended_effect.trim().is_empty() - || proposal.intended_effect.chars().count() > 460 - || !(0..=100).contains(&proposal.priority) - || proposal.effects.is_empty() - || proposal.effects.len() > 4 - { - return Err(anyhow!("cell proposal has no exact constituent authority")); - } - if !cell.subject_ids.contains(&proposal.subject_id) { - if let Some(member_id) = dormant_member_id_for_subject(campaign, &proposal.subject_id) { - return validate_member_cell_proposal(campaign, cell, member_id, proposal); - } - return Err(anyhow!("cell proposal has no exact constituent authority")); - } - let profile = campaign - .agency_profiles - .get(&proposal.subject_id) - .ok_or_else(|| anyhow!("cell proposal constituent lacks an agency profile"))?; - let permitted_references = subject_state_references(campaign, &proposal.subject_id)?; - if proposal - .state_references - .iter() - .any(|reference| !permitted_references.contains(reference)) - || proposal - .public_channels - .iter() - .any(|channel| !profile.information_channels.contains(channel)) - { - return Err(anyhow!( - "cell proposal exceeds constituent knowledge, resources, or information scope" - )); - } - validate_strategic_effect_lanes(&proposal.effects)?; - let prospective_location = proposal.effects.iter().find_map(|effect| match effect { - StrategicCellEffect::ActorMove { destination_id, .. } => Some(destination_id.as_str()), - StrategicCellEffect::GestaltMigration { - destination_gestalt_id, - } => campaign - .gestalts - .get(destination_gestalt_id) - .map(|gestalt| gestalt.home_location_id.as_str()), - _ => None, - }); - for effect in &proposal.effects { - match effect { - StrategicCellEffect::Institution { - institution_id, - posture, - location_ids, - } => { - if institution_id != &proposal.subject_id - || !campaign.institutions.contains_key(institution_id) - || posture.trim().is_empty() - || posture.chars().count() > MAX_POSTURE_CHARS - || !substantive_text_change( - &campaign.institutions[institution_id].posture, - posture, - ) - || location_ids - .iter() - .any(|id| !campaign.locations.contains_key(id)) - || location_ids - .iter() - .any(|id| !profile.location_ids.contains(id)) - { - return Err(anyhow!("institution proposal exceeds constituent state")); - } - } - StrategicCellEffect::Gestalt { - gestalt_id, - pressure_additions, - pressure_resolutions, - } => { - if gestalt_id != &proposal.subject_id - || !campaign.gestalts.contains_key(gestalt_id) - || validate_gestalt_pressure_transition( - &campaign.gestalts[gestalt_id].pressures, - pressure_additions, - pressure_resolutions, - ) - .is_err() - { - return Err(anyhow!("gestalt proposal exceeds constituent state")); - } - } - StrategicCellEffect::GestaltActivity { - gestalt_id, - activity, - target_subject_ids, - location_ids, - } => { - let allowed_targets = strategic_activity_targets(campaign, gestalt_id); - let unique_targets = target_subject_ids.iter().collect::>(); - let unique_locations = location_ids.iter().collect::>(); - let needs_target = activity.requires_explicit_target_for_gestalt(); - if gestalt_id != &proposal.subject_id - || !campaign.gestalts.contains_key(gestalt_id) - || target_subject_ids.len() > 4 - || unique_targets.len() != target_subject_ids.len() - || target_subject_ids - .iter() - .any(|target| !allowed_targets.contains(target)) - || (needs_target && target_subject_ids.is_empty()) - || location_ids.len() > 4 - || unique_locations.len() != location_ids.len() - || location_ids.iter().any(|location| { - !profile.location_ids.contains(location) - && Some(location.as_str()) != prospective_location - }) - { - return Err(anyhow!( - "gestalt activity exceeds exact subject, graph, or location scope" - )); - } - } - StrategicCellEffect::GestaltMigration { - destination_gestalt_id, - } => { - let destination_location_id = campaign - .gestalts - .get(destination_gestalt_id) - .map(|gestalt| gestalt.home_location_id.as_str()) - .ok_or_else(|| { - anyhow!("gestalt migration invented a destination population") - })?; - validate_gestalt_migration( - campaign, - &proposal.subject_id, - destination_gestalt_id, - destination_location_id, - )?; - } - StrategicCellEffect::ActorMove { - actor_id, - destination_id, - } => { - let actor = campaign - .actors - .get(actor_id) - .filter(|_| actor_id == &proposal.subject_id) - .ok_or_else(|| anyhow!("actor proposal exceeds constituent state"))?; - let reachable = - campaign - .locations - .get(&actor.location_id) - .is_some_and(|location| { - location.routes.values().any(|route| { - route.destination_id == *destination_id - && route.travel_minutes - <= campaign.tick_hours.saturating_mul(60) - }) - }); - if !reachable { - return Err(anyhow!("actor proposal exceeds spatial reach")); - } - } - StrategicCellEffect::ActorActivity { - actor_id, - activity, - target_subject_ids, - location_ids, - } => { - let actor = campaign - .actors - .get(actor_id) - .filter(|_| actor_id == &proposal.subject_id) - .ok_or_else(|| anyhow!("actor activity exceeds constituent state"))?; - let allowed_targets = strategic_activity_targets(campaign, actor_id); - let unique_targets = target_subject_ids.iter().collect::>(); - let needs_target = !activity.allows_targetless_local_attempt(); - if target_subject_ids.len() > 4 - || unique_targets.len() != target_subject_ids.len() - || target_subject_ids - .iter() - .any(|target| !allowed_targets.contains(target)) - || (needs_target && target_subject_ids.is_empty()) - || location_ids.len() != 1 - || (location_ids[0] != actor.location_id - && Some(location_ids[0].as_str()) != prospective_location) - { - return Err(anyhow!( - "actor activity exceeds exact subject, graph, or location scope" - )); - } - } - StrategicCellEffect::MemberMigration { .. } => { - return Err(anyhow!( - "a population, institution, actor, or arena cannot migrate a named member" - )); - } - StrategicCellEffect::MemberActivity { .. } => { - return Err(anyhow!( - "a population, institution, actor, or arena cannot act as a named member" - )); - } - } - } - Ok(()) -} - -fn cell_contains_attributed_subject( - campaign: &Campaign, - cell: &SimulationCell, - subject_id: &str, -) -> bool { - if is_human_controlled_actor(campaign, subject_id) { - return false; - } - if cell.subject_ids.contains(subject_id) { - return true; - } - if let Some(member_id) = dormant_member_id_for_subject(campaign, subject_id) { - return cell - .subject_ids - .contains(&campaign.gestalt_members[member_id].gestalt_id); - } - false -} - -fn is_human_controlled_actor(campaign: &Campaign, subject_id: &str) -> bool { - subject_id == campaign.player_actor_id - || campaign - .agency_profiles - .get(subject_id) - .is_some_and(|profile| !profile.simulation_eligible) -} - -pub fn substantive_text_change(current: &str, candidate: &str) -> bool { - let current = current.trim(); - let candidate = candidate.trim(); - !candidate.is_empty() && !current.eq_ignore_ascii_case(candidate) -} - -pub fn validate_gestalt_pressure_transition( - current: &[String], - additions: &[String], - resolutions: &[String], -) -> Result<()> { - if additions.len() + resolutions.len() == 0 || additions.len() + resolutions.len() > 4 { - return Err(anyhow!( - "gestalt pressure transition must change one to four markers" - )); - } - let clean = |value: &String| { - !value.is_empty() && value.chars().count() <= 240 && value.trim().len() == value.len() - }; - if additions.iter().any(|value| !clean(value)) || resolutions.iter().any(|value| !clean(value)) - { - return Err(anyhow!( - "gestalt pressure markers must be clean bounded text" - )); - } - let normalized_additions = additions - .iter() - .map(|value| value.to_lowercase()) - .collect::>(); - let normalized_resolutions = resolutions - .iter() - .map(|value| value.to_lowercase()) - .collect::>(); - let normalized_current = current - .iter() - .map(|value| value.to_lowercase()) - .collect::>(); - if normalized_additions.len() != additions.len() { - return Err(anyhow!("gestalt pressure additions contain duplicates")); - } - if normalized_resolutions.len() != resolutions.len() { - return Err(anyhow!("gestalt pressure resolutions contain duplicates")); - } - if !normalized_additions.is_disjoint(&normalized_resolutions) { - return Err(anyhow!( - "gestalt pressure additions and resolutions overlap" - )); - } - let repeated = additions - .iter() - .filter(|value| normalized_current.contains(&value.to_lowercase())) - .cloned() - .collect::>(); - if !repeated.is_empty() { - return Err(anyhow!( - "gestalt pressure additions already exist: {}", - repeated.join(" | ") - )); - } - let invented = resolutions - .iter() - .filter(|value| !current.contains(value)) - .cloned() - .collect::>(); - if !invented.is_empty() { - return Err(anyhow!( - "gestalt pressure resolutions are not exact current markers: {}; exact current pressures are: {}", - invented.join(" | "), - current.join(" | ") - )); - } - Ok(()) -} - -fn validate_member_cell_proposal( - campaign: &Campaign, - cell: &SimulationCell, - member_id: &str, - proposal: &CellActionProposal, -) -> Result<()> { - let member = campaign - .gestalt_members - .get(member_id) - .filter(|member| { - member.materialized_actor_id.is_none() && cell.subject_ids.contains(&member.gestalt_id) - }) - .ok_or_else(|| anyhow!("named member is not a dematerialized exception of this cell"))?; - let permitted_references = member_state_references(campaign, member_id)?; - let information_channels = effective_member_information_channels(campaign, member_id)?; - if proposal - .state_references - .iter() - .any(|reference| !permitted_references.contains(reference)) - || proposal - .public_channels - .iter() - .any(|channel| !information_channels.contains(channel)) - { - return Err(anyhow!( - "named member proposal borrowed another subject's state or information channel" - )); - } - validate_strategic_effect_lanes(&proposal.effects)?; - let prospective_location = proposal.effects.iter().find_map(|effect| match effect { - StrategicCellEffect::MemberMigration { - destination_gestalt_id, - } => campaign - .gestalts - .get(destination_gestalt_id) - .map(|gestalt| gestalt.home_location_id.as_str()), - _ => None, - }); - for effect in &proposal.effects { - match effect { - StrategicCellEffect::MemberActivity { - member_id: effect_member_id, - activity, - target_subject_ids, - location_ids, - } => { - let allowed_targets = member_activity_targets(campaign, member_id)?; - let unique_targets = target_subject_ids.iter().collect::>(); - let exact_location = dormant_member_location(campaign, member_id)?; - let needs_target = !activity.allows_targetless_local_attempt(); - if effect_member_id != member_id - || target_subject_ids.len() > 4 - || unique_targets.len() != target_subject_ids.len() - || target_subject_ids - .iter() - .any(|target| !allowed_targets.contains(target)) - || (needs_target && target_subject_ids.is_empty()) - || location_ids.len() != 1 - || (location_ids[0] != exact_location - && Some(location_ids[0].as_str()) != prospective_location) - { - return Err(anyhow!( - "named member activity exceeds exact personal, graph, or location scope" - )); - } - } - StrategicCellEffect::MemberMigration { - destination_gestalt_id, - } => { - let destination_location_id = campaign - .gestalts - .get(destination_gestalt_id) - .map(|gestalt| gestalt.home_location_id.as_str()) - .ok_or_else(|| { - anyhow!("named member migration invented a destination gestalt") - })?; - validate_member_migration( - campaign, - member_id, - &member.gestalt_id, - destination_gestalt_id, - destination_location_id, - )?; - } - _ => { - return Err(anyhow!( - "named member exception may propose only its own validated activity or migration" - )); - } - } - } - Ok(()) -} - -pub fn validate_gestalt_migration( - campaign: &Campaign, - source_gestalt_id: &str, - destination_gestalt_id: &str, - destination_location_id: &str, -) -> Result<()> { - if source_gestalt_id == destination_gestalt_id { - return Err(anyhow!( - "gestalt migration must name a different destination population" - )); - } - let source = campaign - .gestalts - .get(source_gestalt_id) - .ok_or_else(|| anyhow!("gestalt migration source is unknown"))?; - let destination = campaign - .gestalts - .get(destination_gestalt_id) - .filter(|destination| destination.home_location_id == destination_location_id) - .ok_or_else(|| anyhow!("gestalt migration destination or location is unknown"))?; - if source.home_location_id == destination_location_id { - return Err(anyhow!( - "gestalt migration must change the source population location" - )); - } - for (gestalt_id, gestalt) in [ - (source_gestalt_id, source), - (destination_gestalt_id, destination), - ] { - let profile = campaign - .agency_profiles - .get(gestalt_id) - .filter(|profile| { - profile.subject_kind == AgencySubjectKind::Gestalt - && profile.active_leaf - && profile.simulation_eligible - }) - .ok_or_else(|| anyhow!("gestalt migration endpoint is not an active leaf"))?; - if !profile.location_ids.contains(&gestalt.home_location_id) { - return Err(anyhow!( - "gestalt migration endpoint has incoherent location state" - )); - } - } - let relation_exists = campaign.agency_relations.values().any(|relation| { - relation.active - && relation.kind == AgencyRelationKind::Migration - && relation.from_subject_id == source_gestalt_id - && relation.to_subject_id == destination_gestalt_id - }); - if !relation_exists { - return Err(anyhow!( - "gestalt migration lacks an explicit source-to-destination relation" - )); - } - let reachable = route_travel_minutes_within( - campaign, - &source.home_location_id, - destination_location_id, - campaign.tick_hours.saturating_mul(60), - ) - .is_some(); - if !reachable { - return Err(anyhow!( - "gestalt migration destination is not reachable within the strategic horizon" - )); - } - Ok(()) -} - -pub fn validate_member_migration( - campaign: &Campaign, - member_id: &str, - source_gestalt_id: &str, - destination_gestalt_id: &str, - destination_location_id: &str, -) -> Result<()> { - let member = campaign - .gestalt_members - .get(member_id) - .filter(|member| { - member.materialized_actor_id.is_none() && member.gestalt_id == source_gestalt_id - }) - .ok_or_else(|| anyhow!("member migration source is stale or individually active"))?; - if source_gestalt_id == destination_gestalt_id { - return Err(anyhow!( - "member migration must change active population leaf" - )); - } - let source = campaign - .gestalts - .get(source_gestalt_id) - .ok_or_else(|| anyhow!("member migration source gestalt is unknown"))?; - let destination = campaign - .gestalts - .get(destination_gestalt_id) - .filter(|destination| destination.home_location_id == destination_location_id) - .ok_or_else(|| anyhow!("member migration destination gestalt or location is unknown"))?; - for gestalt_id in [source_gestalt_id, destination_gestalt_id] { - let profile = campaign - .agency_profiles - .get(gestalt_id) - .filter(|profile| { - profile.subject_kind == AgencySubjectKind::Gestalt - && profile.active_leaf - && profile.simulation_eligible - }) - .ok_or_else(|| anyhow!("member migration endpoint is not an active gestalt leaf"))?; - if !profile - .location_ids - .contains(if gestalt_id == source_gestalt_id { - &source.home_location_id - } else { - &destination.home_location_id - }) - { - return Err(anyhow!( - "member migration endpoint has incoherent location state" - )); - } - } - let relation_exists = campaign.agency_relations.values().any(|relation| { - relation.active - && relation.kind == AgencyRelationKind::Migration - && relation.from_subject_id == source_gestalt_id - && relation.to_subject_id == destination_gestalt_id - }); - if !relation_exists { - return Err(anyhow!( - "member migration lacks an explicit source-to-destination migration relation" - )); - } - let origin = member - .last_location_id - .as_deref() - .unwrap_or(&source.home_location_id); - let reachable = route_travel_minutes_within( - campaign, - origin, - destination_location_id, - campaign.tick_hours.saturating_mul(60), - ) - .is_some(); - if !reachable { - return Err(anyhow!("member migration exceeds the strategic horizon")); - } - Ok(()) -} - -pub fn gestalt_migration_destinations( - campaign: &Campaign, - source_gestalt_id: &str, - origin_location_id: &str, -) -> BTreeMap { - campaign - .agency_relations - .values() - .filter(|relation| { - relation.active - && relation.kind == AgencyRelationKind::Migration - && relation.from_subject_id == source_gestalt_id - }) - .filter_map(|relation| { - let destination = campaign.gestalts.get(&relation.to_subject_id)?; - let profile = campaign.agency_profiles.get(&destination.id)?; - if !profile.active_leaf || !profile.simulation_eligible { - return None; - } - let reachable = route_travel_minutes_within( - campaign, - origin_location_id, - &destination.home_location_id, - campaign.tick_hours.saturating_mul(60), - ) - .is_some(); - reachable.then(|| (destination.id.clone(), destination.home_location_id.clone())) - }) - .collect() -} - -/// Directed shortest-path travel time bounded by the simulation horizon. -/// Containment is intentionally absent: only explicit topology edges carry -/// movement authority. -pub(crate) fn route_travel_minutes_within( - campaign: &Campaign, - origin_location_id: &str, - destination_location_id: &str, - maximum_minutes: u32, -) -> Option { - if origin_location_id == destination_location_id { - return campaign - .locations - .contains_key(origin_location_id) - .then_some(0); - } - if !campaign.locations.contains_key(origin_location_id) - || !campaign.locations.contains_key(destination_location_id) - { - return None; - } - let mut best = BTreeMap::from([(origin_location_id.to_owned(), 0_u32)]); - let mut frontier = BinaryHeap::from([(Reverse(0_u32), origin_location_id.to_owned())]); - while let Some((Reverse(elapsed), location_id)) = frontier.pop() { - if elapsed > maximum_minutes || best.get(&location_id).is_some_and(|known| elapsed > *known) - { - continue; - } - if location_id == destination_location_id { - return Some(elapsed); - } - let location = campaign.locations.get(&location_id)?; - for route in location.routes.values() { - let Some(next) = elapsed.checked_add(route.travel_minutes) else { - continue; - }; - if next > maximum_minutes || !campaign.locations.contains_key(&route.destination_id) { - continue; - } - if best - .get(&route.destination_id) - .is_none_or(|known| next < *known) - { - best.insert(route.destination_id.clone(), next); - frontier.push((Reverse(next), route.destination_id.clone())); - } - } - } - None -} - -pub fn member_state_references(campaign: &Campaign, member_id: &str) -> Result> { - let member = campaign - .gestalt_members - .get(member_id) - .ok_or_else(|| anyhow!("gestalt member is unknown"))?; - let gestalt = campaign - .gestalts - .get(&member.gestalt_id) - .ok_or_else(|| anyhow!("gestalt member baseline is unknown"))?; - let mut references = BTreeSet::from([ - crate::domain::gestalt_member_subject_id(member_id), - crate::domain::gestalt_state_reference(&member.gestalt_id), - format!( - "location:{}", - member - .last_location_id - .as_deref() - .unwrap_or(&gestalt.home_location_id) - ), - ]); - references.extend( - effective_member_capabilities(campaign, member_id)? - .into_iter() - .map(|value| format!("capability:{value}")), - ); - references.extend( - effective_member_knowledge(campaign, member_id)? - .into_iter() - .map(|value| format!("knowledge:{value}")), - ); - references.extend( - member - .equipment - .iter() - .map(|value| format!("resource:{value}")), - ); - for relation in campaign.agency_relations.values().filter(|relation| { - relation.active - && relation.kind == AgencyRelationKind::Migration - && relation.from_subject_id == member.gestalt_id - }) { - if let Some(destination) = campaign.gestalts.get(&relation.to_subject_id) { - references.insert(crate::domain::gestalt_state_reference(&destination.id)); - references.insert(format!("location:{}", destination.home_location_id)); - } - } - Ok(references) -} - -pub fn effective_member_information_channels( - campaign: &Campaign, - member_id: &str, -) -> Result> { - let member = campaign - .gestalt_members - .get(member_id) - .ok_or_else(|| anyhow!("gestalt member is unknown"))?; - campaign - .agency_profiles - .get(&member.gestalt_id) - .map(|profile| profile.information_channels.clone()) - .ok_or_else(|| anyhow!("gestalt member agency profile is unknown")) -} - -pub fn effective_member_capabilities( - campaign: &Campaign, - member_id: &str, -) -> Result> { - let member = campaign - .gestalt_members - .get(member_id) - .ok_or_else(|| anyhow!("gestalt member is unknown"))?; - let gestalt = campaign - .gestalts - .get(&member.gestalt_id) - .ok_or_else(|| anyhow!("gestalt member baseline is unknown"))?; - Ok(gestalt - .shared_capabilities - .union(&member.capability_additions) - .filter(|value| !member.capability_removals.contains(*value)) - .cloned() - .collect()) -} - -pub fn effective_member_knowledge( - campaign: &Campaign, - member_id: &str, -) -> Result> { - let member = campaign - .gestalt_members - .get(member_id) - .ok_or_else(|| anyhow!("gestalt member is unknown"))?; - let gestalt = campaign - .gestalts - .get(&member.gestalt_id) - .ok_or_else(|| anyhow!("gestalt member baseline is unknown"))?; - Ok(gestalt - .shared_knowledge - .union(&member.knowledge_additions) - .filter(|value| !member.knowledge_removals.contains(*value)) - .cloned() - .collect()) -} - -pub fn subject_state_references(campaign: &Campaign, subject_id: &str) -> Result> { - let profile = campaign - .agency_profiles - .get(subject_id) - .ok_or_else(|| anyhow!("agency subject is unknown"))?; - let mut references = BTreeSet::from([format!("subject:{subject_id}")]); - references.extend( - profile - .location_ids - .iter() - .map(|value| format!("location:{value}")), - ); - references.extend(profile.facets.iter().flat_map(|(axis, values)| { - values - .iter() - .map(move |value| format!("facet:{axis:?}:{value}")) - })); - if let Some(actor) = campaign.actors.get(subject_id) { - references.extend( - actor - .capabilities - .iter() - .map(|value| format!("capability:{value}")) - .chain( - actor - .knowledge - .iter() - .map(|value| format!("knowledge:{value}")), - ) - .chain( - actor - .equipment - .iter() - .map(|value| format!("resource:{value}")), - ) - .chain( - actor - .obligations - .iter() - .map(|value| format!("obligation:{value}")), - ), - ); - } - if let Some(institution) = campaign.institutions.get(subject_id) { - references.extend( - institution - .resources - .iter() - .map(|value| format!("resource:{value}")) - .chain( - institution - .goals - .iter() - .map(|value| format!("goal:{value}")), - ), - ); - } - if let Some(gestalt) = campaign.gestalts.get(subject_id) { - references.extend( - gestalt - .shared_capabilities - .iter() - .map(|value| format!("capability:{value}")) - .chain( - gestalt - .shared_knowledge - .iter() - .map(|value| format!("knowledge:{value}")), - ) - .chain( - gestalt - .resources - .iter() - .map(|value| format!("resource:{value}")), - ), - ); - for (destination_id, location_id) in - gestalt_migration_destinations(campaign, subject_id, &gestalt.home_location_id) - { - references.insert(crate::domain::gestalt_state_reference(&destination_id)); - references.insert(format!("location:{location_id}")); - } - } - Ok(references) -} - -pub fn strategic_activity_targets(campaign: &Campaign, subject_id: &str) -> BTreeSet { - let mut targets = campaign - .agency_relations - .values() - .filter(|relation| relation.active) - .filter_map(|relation| { - if relation.from_subject_id == subject_id { - Some(relation.to_subject_id.clone()) - } else if relation.to_subject_id == subject_id { - Some(relation.from_subject_id.clone()) - } else { - None - } - }) - .filter(|target| target != subject_id && campaign.agency_profiles.contains_key(target)) - .collect::>(); - if let Some(source) = campaign.agency_profiles.get(subject_id) { - targets.extend( - campaign - .agency_profiles - .values() - .filter(|target| { - target.subject_id != subject_id - && target.active_leaf - && !source.location_ids.is_disjoint(&target.location_ids) - }) - .map(|target| target.subject_id.clone()), - ); - targets.extend(campaign.gestalt_members.values().filter_map(|member| { - if member.materialized_actor_id.is_some() { - return None; - } - let location = dormant_member_location(campaign, &member.id).ok()?; - source - .location_ids - .contains(&location) - .then(|| crate::domain::gestalt_member_subject_id(&member.id)) - })); - } - targets -} - -pub fn member_activity_targets(campaign: &Campaign, member_id: &str) -> Result> { - let member = campaign - .gestalt_members - .get(member_id) - .filter(|member| member.materialized_actor_id.is_none()) - .ok_or_else(|| anyhow!("gestalt member is not dormant"))?; - dormant_member_location(campaign, member_id)?; - let mut targets = strategic_activity_targets(campaign, &member.gestalt_id); - targets.insert(member.gestalt_id.clone()); - targets.remove(&crate::domain::gestalt_member_subject_id(member_id)); - Ok(targets) -} - -/// Resolve a subject-shaped member ID only while its canonical person remains -/// folded into a Gestalt. Materialized people deliberately retain the same -/// stable ID, so the `member:` prefix cannot own their current subject kind. -pub fn dormant_member_id_for_subject<'a>( - campaign: &'a Campaign, - subject_id: &str, -) -> Option<&'a str> { - campaign - .gestalt_members - .values() - .filter(|member| { - member.materialized_actor_id.is_none() - && crate::domain::gestalt_member_subject_id(&member.id) == subject_id - && !campaign.actors.contains_key(subject_id) - }) - .map(|member| member.id.as_str()) - .next() -} - -pub fn validate_active_gestalt_presence_location( - campaign: &Campaign, - gestalt_id: &str, - location_id: &str, -) -> Result<()> { - let profile = campaign - .agency_profiles - .get(gestalt_id) - .filter(|profile| { - profile.subject_kind == AgencySubjectKind::Gestalt - && profile.active_leaf - && profile.simulation_eligible - }) - .ok_or_else(|| anyhow!("gestalt presence requires an active population leaf"))?; - if !profile.location_ids.contains(location_id) { - return Err(anyhow!( - "gestalt presence location is outside the population's exact scope" - )); - } - Ok(()) -} - -pub fn dormant_member_location(campaign: &Campaign, member_id: &str) -> Result { - let member = campaign - .gestalt_members - .get(member_id) - .filter(|member| member.materialized_actor_id.is_none()) - .ok_or_else(|| anyhow!("gestalt member is not dormant"))?; - let location_id = member - .last_location_id - .clone() - .or_else(|| { - campaign - .gestalts - .get(&member.gestalt_id) - .map(|gestalt| gestalt.home_location_id.clone()) - }) - .ok_or_else(|| anyhow!("gestalt member has no population location"))?; - validate_active_gestalt_presence_location(campaign, &member.gestalt_id, &location_id)?; - Ok(location_id) -} - -fn proposal_target_key(proposal: &CellActionProposal) -> String { - proposal.subject_id.clone() -} - -fn validate_strategic_effect_lanes(effects: &[StrategicCellEffect]) -> Result<()> { - let mut lanes = BTreeSet::new(); - for (index, effect) in effects.iter().enumerate() { - if effects[..index].contains(effect) { - return Err(anyhow!( - "a strategic action cannot repeat an exact typed effect" - )); - } - let lane = match effect { - StrategicCellEffect::GestaltActivity { .. } - | StrategicCellEffect::ActorActivity { .. } - | StrategicCellEffect::MemberActivity { .. } => None, - _ => Some(effect.lane()), - }; - if lane.is_some_and(|lane| !lanes.insert(lane)) { - return Err(anyhow!( - "one strategic action may use each scalar effect lane at most once" - )); - } - } - Ok(()) -} - -fn is_sha256(value: &str) -> bool { - value - .strip_prefix("sha256:") - .is_some_and(|hex| hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit())) -} - -/// Project the resolution-only consequences of an already accepted population -/// split. Canonical populations, memberships, lineage, and resource custody -/// must already have been committed by the world mutation reducer. -pub(crate) fn project_fission_resolution( - campaign: &mut Campaign, - preview: &GestaltFissionPreview, -) -> Result<()> { - let parent_profile = campaign - .agency_profiles - .get_mut(&preview.parent_gestalt_id) - .ok_or_else(|| anyhow!("fission parent lacks an agency profile"))?; - parent_profile.active_leaf = false; - parent_profile.simulation_eligible = false; - parent_profile.profile_version = parent_profile.profile_version.saturating_add(1); - let inherited = parent_profile.clone(); - for child in &preview.children { - campaign.gestalts.insert(child.id.clone(), child.clone()); - let mut profile = profile_for_gestalt(child, &preview.evidence_receipt_ids); - profile.parent_subject_id = Some(preview.parent_gestalt_id.clone()); - if child.id == preview.residual_child_id { - profile.simulation_eligible = false; - } - profile.facets = inherited.facets.clone(); - profile - .facets - .entry(preview.partition_axis.clone()) - .or_default() - .insert( - preview - .child_partition_values - .get(&child.id) - .expect("validated child partition value") - .clone(), - ); - for receipt_id in &inherited.evidence_receipt_ids { - if !profile.evidence_receipt_ids.contains(receipt_id) { - profile.evidence_receipt_ids.push(receipt_id.clone()); - } - } - campaign.agency_profiles.insert(child.id.clone(), profile); - } - campaign.resolution_cover = None; - campaign.resolution_policy.resolution_epoch = campaign - .resolution_policy - .resolution_epoch - .saturating_add(1); - Ok(()) -} - -pub fn validate_fission(campaign: &Campaign, preview: &GestaltFissionPreview) -> Result<()> { - validate_fission_shape(campaign, preview, false) -} - -pub fn validate_elaborated_fission( - campaign: &Campaign, - preview: &GestaltFissionPreview, -) -> Result<()> { - validate_fission_shape(campaign, preview, true) -} - -fn preserves_inherited_prefix_with_unique_additions( - values: &[String], - inherited: &[String], -) -> bool { - if !values.starts_with(inherited) { - return false; - } - let inherited_len = inherited.len(); - let inherited = inherited.iter().collect::>(); - let mut additions = BTreeSet::new(); - values[inherited_len..] - .iter() - .all(|value| !inherited.contains(value) && additions.insert(value)) -} - -fn validate_fission_shape( - campaign: &Campaign, - preview: &GestaltFissionPreview, - allow_semantic_additions: bool, -) -> Result<()> { - let parent = campaign - .gestalts - .get(&preview.parent_gestalt_id) - .ok_or_else(|| anyhow!("fission parent is unknown"))?; - let parent_profile = campaign - .agency_profiles - .get(&preview.parent_gestalt_id) - .filter(|profile| profile.active_leaf) - .ok_or_else(|| anyhow!("fission parent is not an active leaf gestalt"))?; - let child_ids: BTreeSet<_> = preview - .children - .iter() - .map(|child| child.id.as_str()) - .collect(); - let residual_value = preview - .child_partition_values - .get(&preview.residual_child_id) - .map(|value| value.trim().to_ascii_lowercase()); - let assigned_resources = preview - .resource_child_assignments - .keys() - .cloned() - .collect::>(); - let child_resources = preview - .children - .iter() - .flat_map(|child| { - child - .resources - .iter() - .cloned() - .map(move |resource| (resource, child.id.clone())) - }) - .collect::>(); - let unique_child_resources = child_resources - .iter() - .map(|(resource, _)| resource.clone()) - .collect::>(); - let mut mismatches = Vec::new(); - let mut require = |condition: bool, diagnostic: String| { - if !condition { - mismatches.push(diagnostic); - } - }; - require( - preview.campaign_id == campaign.id, - "campaign id does not match the frozen world".into(), - ); - require( - preview.expected_world_revision == campaign.revision, - "expected world revision is stale".into(), - ); - require( - preview.requires_approval, - "fission must require approval".into(), - ); - require( - preview.children.len() >= 2, - "fission needs at least two children".into(), - ); - require( - child_ids.len() == preview.children.len(), - "child ids are not unique".into(), - ); - require( - child_ids.contains(preview.residual_child_id.as_str()), - "residual child id is not one of the children".into(), - ); - require( - residual_value.as_deref() == Some("other/unknown"), - "residual child partition must be other/unknown".into(), - ); - require( - preview.child_partition_values.len() == preview.children.len(), - "partition values do not cover the children exactly".into(), - ); - for child in &preview.children { - let label = if child.id.trim().is_empty() { - "" - } else { - &child.id - }; - require(!child.id.trim().is_empty(), "child id is empty".into()); - require( - !child.name.trim().is_empty(), - format!("child {label} has an empty name"), - ); - require( - child.version == 0, - format!("child {label} version is not zero"), - ); - require( - !canonical_subject_id_is_occupied(campaign, &child.id), - format!("child {label} collides with an established canonical subject identity"), - ); - require( - campaign.locations.contains_key(&child.home_location_id), - format!("child {label} has an unknown home location"), - ); - require( - preview.partition_axis == AgencyAxis::Geography - || child.home_location_id == parent.home_location_id, - format!("child {label} changed home outside a geography fission"), - ); - require( - if allow_semantic_additions { - child - .shared_capabilities - .is_superset(&parent.shared_capabilities) - } else { - child.shared_capabilities == parent.shared_capabilities - }, - format!("child {label} changed inherited capabilities outside its authority"), - ); - require( - if allow_semantic_additions { - child.shared_knowledge.is_superset(&parent.shared_knowledge) - } else { - child.shared_knowledge == parent.shared_knowledge - }, - format!("child {label} changed inherited knowledge outside its authority"), - ); - require( - if allow_semantic_additions { - preserves_inherited_prefix_with_unique_additions(&child.goals, &parent.goals) - } else { - child.goals == parent.goals - }, - format!( - "child {label} must preserve inherited goals as an exact prefix and add no duplicates" - ), - ); - require( - if allow_semantic_additions { - preserves_inherited_prefix_with_unique_additions( - &child.pressures, - &parent.pressures, - ) - } else { - child.pressures == parent.pressures - }, - format!( - "child {label} must preserve inherited pressures as an exact prefix and add no duplicates" - ), - ); - require( - preview.child_partition_values.contains_key(&child.id), - format!("child {label} has no partition value"), - ); - } - for (member, child) in &preview.member_child_assignments { - require( - campaign - .gestalt_members - .get(member) - .is_some_and(|value| value.gestalt_id == parent.id), - format!("member {member} does not belong to the parent"), - ); - require( - child_ids.contains(child.as_str()), - format!("member {member} is assigned to unknown child {child}"), - ); - } - require( - assigned_resources == parent.resources, - format!( - "resource assignments must cover exactly the parent resources; expected {:?}, received {:?}", - parent.resources, assigned_resources - ), - ); - require( - unique_child_resources == parent.resources, - format!( - "child resource custody must equal the parent resources; expected {:?}, received {:?}", - parent.resources, unique_child_resources - ), - ); - require( - child_resources.len() == unique_child_resources.len(), - "a resource appears in more than one child".into(), - ); - for (resource, child) in &preview.resource_child_assignments { - require( - child_ids.contains(child.as_str()), - format!("resource {resource} is assigned to unknown child {child}"), - ); - require( - preview - .children - .iter() - .any(|candidate| candidate.id == *child && candidate.resources.contains(resource)), - format!("resource {resource} is absent from assigned child {child}"), - ); - } - require( - parent_profile.subject_kind == AgencySubjectKind::Gestalt, - "parent agency profile is not a Gestalt".into(), - ); - if !mismatches.is_empty() { - return Err(anyhow!( - "gestalt fission preview mismatches: {}", - mismatches.join("; ") - )); - } - Ok(()) -} - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - use chrono::Utc; - use std::time::Instant; - use uuid::Uuid; - - pub(crate) fn campaign(subjects: usize, budget: u8) -> Campaign { - let player_id = "player".to_owned(); - let actors = BTreeMap::from([( - player_id.clone(), - ActorState { - id: player_id.clone(), - name: "Player".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![], - }, - )]); - let institutions = (0..subjects) - .map(|index| { - let id = format!("faction-{index:04}"); - ( - id.clone(), - InstitutionState { - id, - name: format!("Faction {index}"), - resources: vec![format!("resource-{}", index % 7)], - goals: vec![format!("goal-{}", index % 5)], - posture: format!("posture-{}", index % 3), - }, - ) - }) - .collect(); - let mut value = Campaign { - schema: "ghostlight.campaign.v1".into(), - id: Uuid::new_v4(), - name: "Resolution fixture".into(), - revision: 0, - branch_origin: BranchOrigin { - canon_cutoff: "fixture".into(), - evidence_receipt_ids: vec![], - }, - world_time: Utc::now(), - tick_hours: 6, - player_actor_id: player_id, - locations: BTreeMap::from([( - "center".into(), - Location { - id: "center".into(), - name: "Center".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - )]), - actors, - institutions, - clocks: BTreeMap::new(), - facts: BTreeMap::new(), - civic_systems: BTreeMap::new(), - transcript: vec![], - last_player_activity: Utc::now(), - pending_ticks: 0, - away_ticks_processed: 0, - events: vec![], - news: vec![], - canon_candidates: BTreeMap::new(), - gestalts: BTreeMap::new(), - gestalt_members: BTreeMap::new(), - pending_world_proposals: vec![], - agency_profiles: BTreeMap::new(), - agency_relations: BTreeMap::new(), - gestalt_lineages: BTreeMap::new(), - resolution_policy: ResolutionPolicy { - active_cell_budget: budget, - ..ResolutionPolicy::default() - }, - resolution_pins: BTreeMap::new(), - resolution_cover: None, - nemesis_attention_history: Vec::new(), - strategic_tick_count: 0, - }; - ensure_agency_profiles(&mut value); - for (index, profile) in value - .agency_profiles - .values_mut() - .filter(|profile| profile.simulation_eligible) - .enumerate() - { - profile.facets.insert( - AgencyAxis::Geography, - BTreeSet::from([format!("region-{}", index % 4)]), - ); - profile.facets.insert( - AgencyAxis::Ideology, - BTreeSet::from([format!("ideology-{}", index % 6)]), - ); - profile.facets.insert( - AgencyAxis::SpeciesBody, - BTreeSet::from([format!("body-{}", index % 2)]), - ); - } - value - } - - #[test] - fn fission_validation_uses_the_unified_canonical_subject_id_namespace() { - let mut value = campaign(1, 1); - value.gestalts.insert( - "villagers".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "villagers".into(), - name: "Villagers".into(), - version: 0, - home_location_id: "center".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - ensure_agency_profiles(&mut value); - let mut detached_profile = value.agency_profiles["villagers"].clone(); - detached_profile.id = "reserved-profile-id".into(); - detached_profile.subject_id = "reserved-profile-subject".into(); - detached_profile.active_leaf = false; - detached_profile.simulation_eligible = false; - value - .agency_profiles - .insert("reserved-profile-key".into(), detached_profile); - value.gestalt_members.insert( - "reserved-member".into(), - GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "reserved-member".into(), - gestalt_id: "villagers".into(), - version: 0, - name: "Reserved Member".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, - }, - ); - - let child = |id: &str, name: &str| GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: id.into(), - name: name.into(), - version: 0, - home_location_id: "center".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }; - let preview = GestaltFissionPreview { - schema: "ghostlight.gestalt_fission_preview.v1".into(), - campaign_id: value.id, - expected_world_revision: value.revision, - parent_gestalt_id: "villagers".into(), - partition_axis: AgencyAxis::Ideology, - children: vec![ - child("new-villagers", "New villagers"), - child("other", "Other"), - ], - child_partition_values: BTreeMap::from([ - ("new-villagers".into(), "new".into()), - ("other".into(), "other/unknown".into()), - ]), - residual_child_id: "other".into(), - member_child_assignments: BTreeMap::new(), - resource_child_assignments: BTreeMap::new(), - evidence_receipt_ids: vec![], - gaps: vec![], - canon_candidates: vec![], - requires_approval: true, - }; - - for occupied_id in [ - "player", - "faction-0000", - "villagers", - "reserved-profile-key", - "reserved-profile-id", - "reserved-profile-subject", - "member:reserved-member", - ] { - let mut colliding = preview.clone(); - colliding.children[0].id = occupied_id.into(); - colliding.child_partition_values.remove("new-villagers"); - colliding - .child_partition_values - .insert(occupied_id.into(), "new".into()); - let diagnostic = validate_fission(&value, &colliding) - .unwrap_err() - .to_string(); - assert!( - diagnostic.contains("collides with an established canonical subject identity"), - "{occupied_id} escaped the canonical subject namespace: {diagnostic}" - ); - } - } - - #[test] - fn profile_maintenance_never_promotes_knowledge_into_public_channels() { - let mut value = campaign(1, 1); - value - .actors - .get_mut("player") - .unwrap() - .knowledge - .insert("private convoy vulnerability".into()); - - value.agency_profiles.remove("player"); - ensure_agency_profiles(&mut value); - assert!( - value.agency_profiles["player"] - .information_channels - .is_empty() - ); - - value - .agency_profiles - .get_mut("player") - .unwrap() - .information_channels = BTreeSet::from([ - "private convoy vulnerability".into(), - "licensed courier wire".into(), - "unknown".into(), - ]); - ensure_agency_profiles(&mut value); - assert_eq!( - value.agency_profiles["player"].information_channels, - BTreeSet::from(["licensed courier wire".into()]) - ); - } - - #[test] - fn human_controlled_actor_remains_a_target_without_becoming_a_simulation_subject() { - let mut value = campaign(1, 1); - value - .agency_profiles - .get_mut("faction-0000") - .unwrap() - .location_ids - .insert("center".into()); - - assert!(!value.agency_profiles["player"].simulation_eligible); - assert!( - strategic_activity_targets(&value, "faction-0000").contains("player"), - "simulation eligibility controls who may act through a Persona cell, not who may be addressed" - ); - } - - #[test] - fn materialized_member_actor_has_one_exact_cell_authority() { - let mut value = campaign(0, 2); - value.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![], - }, - ); - value.gestalt_members.insert( - "sable".into(), - GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "sable".into(), - gestalt_id: "refugees".into(), - version: 1, - name: "Sable".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:sable".into()), - last_relevant_revision: 0, - relevance_lease_until_revision: 5, - }, - ); - value.actors.insert( - "member:sable".into(), - ActorState { - id: "member:sable".into(), - name: "Sable".into(), - location_id: "center".into(), - capabilities: BTreeSet::from(["route scouting".into()]), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - ensure_agency_profiles(&mut value); - let actor_cell = SimulationCell { - schema: "ghostlight.simulation_cell.v1".into(), - id: "actor-cell".into(), - mode: SimulationCellMode::Arena, - subject_ids: BTreeSet::from(["member:sable".into()]), - merge_loss: MergeLoss::default(), - rationale: "exact materialized actor".into(), - lease_until_world_revision: 0, - lease_until_strategic_tick: 0, - detail_focus_subject_id: None, - }; - let population_cell = SimulationCell { - schema: "ghostlight.simulation_cell.v1".into(), - id: "population-cell".into(), - mode: SimulationCellMode::Cohesive, - subject_ids: BTreeSet::from(["refugees".into()]), - merge_loss: MergeLoss::default(), - rationale: "population baseline".into(), - lease_until_world_revision: 0, - lease_until_strategic_tick: 0, - detail_focus_subject_id: None, - }; - let proposal = CellActionProposal { - subject_id: "member:sable".into(), - intent: "inspect the eastern trail".into(), - intended_effect: "identify an immediate route hazard".into(), - priority: 50, - state_references: vec![ - "subject:member:sable".into(), - "location:center".into(), - "capability:route scouting".into(), - ], - public_channels: vec![], - effects: vec![StrategicCellEffect::ActorActivity { - actor_id: "member:sable".into(), - activity: StrategicActivityKind::Investigate, - target_subject_ids: vec![], - location_ids: vec!["center".into()], - }], - }; - - validate_cell_proposal(&value, &actor_cell, &proposal).unwrap(); - assert!(cell_contains_attributed_subject( - &value, - &actor_cell, - "member:sable" - )); - assert!(!cell_contains_attributed_subject( - &value, - &population_cell, - "member:sable" - )); - assert_eq!(dormant_member_id_for_subject(&value, "member:sable"), None); - } - - #[test] - fn legacy_prefixed_member_identity_migrates_once_without_losing_person_state() { - let mut value = campaign(1, 1); - value.gestalts.insert( - "raincross-households".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "raincross-households".into(), - name: "Raincross households".into(), - version: 0, - home_location_id: "center".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }, - ); - value.gestalt_members.insert( - "member:cal_rusk".into(), - GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "member:cal_rusk".into(), - gestalt_id: "raincross-households".into(), - version: 3, - name: "Cal Rusk".into(), - capability_additions: BTreeSet::from(["read flood trails".into()]), - capability_removals: BTreeSet::new(), - knowledge_additions: BTreeSet::from(["the bypass is passable".into()]), - knowledge_removals: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::from([( - "member:member:cal_rusk".into(), - "trusts his own survey".into(), - )]), - goals: vec!["keep the households alive".into()], - memories: vec!["surveyed the bypass".into()], - last_location_id: Some("center".into()), - materialized_actor_id: Some("member:member:cal_rusk".into()), - last_relevant_revision: 5, - relevance_lease_until_revision: 9, - }, - ); - value.actors.insert( - "member:member:cal_rusk".into(), - ActorState { - id: "member:member:cal_rusk".into(), - name: "Cal Rusk".into(), - location_id: "center".into(), - capabilities: BTreeSet::from(["read flood trails".into()]), - knowledge: BTreeSet::from(["the bypass is passable".into()]), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec!["keep the households alive".into()], - memories: vec!["surveyed the bypass".into()], - }, - ); - value - .actors - .get_mut("player") - .unwrap() - .relationships - .insert( - "member:member:cal_rusk".into(), - "heard his careful report".into(), - ); - value.pending_world_proposals.push(WorldActionProposal { - actor_id: "member:member:cal_rusk".into(), - intent: "check the route".into(), - intended_effect: "keep the route legible".into(), - priority: 1, - state_references: vec!["subject:member:member:cal_rusk".into()], - }); - ensure_agency_profiles(&mut value); - value - .agency_profiles - .get_mut("member:member:cal_rusk") - .unwrap() - .detail_debt = 17; - value.agency_relations.insert( - "cal-households".into(), - AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "cal-households".into(), - from_subject_id: "member:member:cal_rusk".into(), - to_subject_id: "raincross-households".into(), - kind: AgencyRelationKind::Membership, - strength: 100, - active: true, - evidence_receipt_ids: vec![], - }, - ); - value.resolution_pins.insert( - "pin-cal".into(), - ResolutionPin { - schema: "ghostlight.resolution_pin.v1".into(), - id: "pin-cal".into(), - kind: ResolutionPinKind::MinimumIndividualDetail, - subject_ids: BTreeSet::from(["member:member:cal_rusk".into()]), - reason: "foreground".into(), - created_world_revision: 5, - }, - ); - value.resolution_cover = - Some(plan_cover(&value, default_demand(&value, "legacy cover")).unwrap()); - - assert!(normalize_legacy_gestalt_member_identities(&mut value).unwrap()); - assert!(!normalize_legacy_gestalt_member_identities(&mut value).unwrap()); - assert!(!value.gestalt_members.contains_key("member:cal_rusk")); - let member = &value.gestalt_members["cal_rusk"]; - assert_eq!(member.id, "cal_rusk"); - assert_eq!( - member.materialized_actor_id.as_deref(), - Some("member:cal_rusk") - ); - assert!( - member - .knowledge_additions - .contains("the bypass is passable") - ); - assert!(member.memories.contains(&"surveyed the bypass".into())); - assert!(member.relationships.contains_key("member:cal_rusk")); - assert!(!value.actors.contains_key("member:member:cal_rusk")); - assert_eq!(value.actors["member:cal_rusk"].name, "Cal Rusk"); - assert!( - value.actors["player"] - .relationships - .contains_key("member:cal_rusk") - ); - assert_eq!(value.pending_world_proposals[0].actor_id, "member:cal_rusk"); - assert_eq!( - value.pending_world_proposals[0].state_references, - ["subject:member:cal_rusk"] - ); - assert_eq!(value.agency_profiles["member:cal_rusk"].detail_debt, 17); - assert_eq!( - value.agency_relations["cal-households"].from_subject_id, - "member:cal_rusk" - ); - assert_eq!( - value.resolution_pins["pin-cal"].subject_ids, - BTreeSet::from(["member:cal_rusk".into()]) - ); - assert!(value.resolution_cover.is_none()); - } - - #[test] - fn aetheria_scale_cover_is_complete_unique_and_budgeted() { - for budget in [1, 4, 8, 32] { - let value = campaign(24, budget); - let cover = plan_cover(&value, default_demand(&value, "test pressure")).unwrap(); - assert_eq!(cover.cells.len(), usize::from(budget).min(24)); - let covered: Vec<_> = cover - .cells - .iter() - .flat_map(|cell| cell.subject_ids.iter()) - .collect(); - assert_eq!(covered.len(), 24); - assert_eq!(covered.iter().copied().collect::>().len(), 24); - validate_cover(&value, &cover.demand, &cover.cells).unwrap(); - } - } - - #[test] - fn results_and_tie_breaking_are_deterministic() { - let value = campaign(24, 8); - let demand = default_demand(&value, "same pressure"); - assert_eq!( - plan_cover(&value, demand.clone()).unwrap(), - plan_cover(&value, demand).unwrap() - ); - } - - #[test] - fn lease_cannot_preserve_a_cell_disconnected_by_current_topology() { - let mut value = campaign(4, 2); - let demand = default_demand(&value, "topology changed beneath the lease"); - let profiles = value.agency_profiles.clone(); - let scoring = ScoringCache::new(&value, &profiles); - let stale_groups = [ - BTreeSet::from(["faction-0000".into(), "faction-0002".into()]), - BTreeSet::from(["faction-0001".into(), "faction-0003".into()]), - ]; - let stale_cells = stale_groups - .into_iter() - .map(|subject_ids| { - let (mode, merge_loss) = - classify_and_score(&value, &profiles, &scoring, &subject_ids, &demand); - SimulationCell { - schema: "ghostlight.simulation_cell.v1".into(), - id: cell_id(&subject_ids, &mode), - mode, - subject_ids, - merge_loss, - rationale: "previously connected partition".into(), - lease_until_world_revision: value.revision + 5, - lease_until_strategic_tick: value.strategic_tick_count + 2, - detail_focus_subject_id: None, - } - }) - .collect::>(); - value.resolution_cover = Some(ResolutionCover { - schema: "ghostlight.resolution_cover.v1".into(), - campaign_id: value.id, - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - configured_budget: 2, - effective_budget: 2, - mandatory_overage: 0, - cells: stale_cells.clone(), - demand: demand.clone(), - causal_follow_through: Vec::new(), - }); - - let cover = plan_cover(&value, demand).unwrap(); - validate_cover(&value, &cover.demand, &cover.cells).unwrap(); - assert_ne!(cover.cells, stale_cells); - } - - #[test] - fn rivals_at_budget_one_form_an_arena_not_a_false_collective() { - let mut value = campaign(2, 1); - value.agency_relations.insert( - "rivalry".into(), - AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "rivalry".into(), - from_subject_id: "faction-0000".into(), - to_subject_id: "faction-0001".into(), - kind: AgencyRelationKind::Rivalry, - strength: 100, - active: true, - evidence_receipt_ids: vec![], - }, - ); - let cover = plan_cover(&value, default_demand(&value, "war")).unwrap(); - assert_eq!(cover.cells.len(), 1); - assert_eq!(cover.cells[0].mode, SimulationCellMode::Arena); - } - - #[test] - fn foreground_subjects_create_reported_temporary_overage() { - let mut value = campaign(5, 1); - for id in ["faction-0000", "faction-0001", "faction-0002"] { - value.resolution_pins.insert( - format!("foreground:{id}"), - ResolutionPin { - schema: "ghostlight.resolution_pin.v1".into(), - id: format!("foreground:{id}"), - kind: ResolutionPinKind::MinimumIndividualDetail, - subject_ids: BTreeSet::from([id.into()]), - reason: "directly engaged foreground subject".into(), - created_world_revision: value.revision, - }, - ); - } - let demand = default_demand(&value, "foreground"); - let cover = plan_cover(&value, demand).unwrap(); - assert_eq!(cover.effective_budget, 4); - assert_eq!(cover.mandatory_overage, 3); - for id in ["faction-0000", "faction-0001", "faction-0002"] { - assert!( - cover - .cells - .iter() - .any(|cell| { cell.subject_ids == BTreeSet::from([id.to_owned()]) }) - ); - } - } - - #[test] - fn model_focal_subjects_raise_salience_without_overriding_the_budget() { - let value = campaign(5, 1); - let mut demand = default_demand(&value, "broad pressure"); - demand.focal_subject_ids = value - .agency_profiles - .values() - .filter(|profile| profile.simulation_eligible) - .map(|profile| profile.subject_id.clone()) - .collect(); - let cover = plan_cover(&value, demand).unwrap(); - assert_eq!(cover.effective_budget, 1); - assert_eq!(cover.mandatory_overage, 0); - assert_eq!(cover.cells[0].subject_ids.len(), 5); - } - - #[test] - fn contradictory_pins_are_rejected() { - let mut value = campaign(3, 2); - value.resolution_pins.insert( - "together".into(), - ResolutionPin { - schema: "ghostlight.resolution_pin.v1".into(), - id: "together".into(), - kind: ResolutionPinKind::KeepTogether, - subject_ids: BTreeSet::from(["faction-0000".into(), "faction-0001".into()]), - reason: "test".into(), - created_world_revision: 0, - }, - ); - value.resolution_pins.insert( - "apart".into(), - ResolutionPin { - schema: "ghostlight.resolution_pin.v1".into(), - id: "apart".into(), - kind: ResolutionPinKind::KeepSeparate, - subject_ids: BTreeSet::from(["faction-0000".into(), "faction-0001".into()]), - reason: "test".into(), - created_world_revision: 0, - }, - ); - assert!(plan_cover(&value, default_demand(&value, "pins")).is_err()); - } - - #[test] - fn detail_debt_rotates_low_budget_attention() { - let mut value = campaign(6, 1); - let mut focused = BTreeSet::new(); - for _ in 0..6 { - let cover = plan_cover(&value, default_demand(&value, "quiet world")).unwrap(); - focused.insert( - cover.cells[0] - .detail_focus_subject_id - .clone() - .expect("aggregate must have a detail focus"), - ); - advance_detail_debt(&mut value, &cover); - value.resolution_cover = Some(cover); - value.strategic_tick_count += 1; - value.revision += 1; - } - assert_eq!(focused.len(), 6); - } - - #[test] - fn planning_never_mutates_canonical_state() { - let value = campaign(24, 4); - let before = value.clone(); - let _ = plan_cover(&value, default_demand(&value, "read only")).unwrap(); - assert_eq!(value, before); - } - - #[test] - fn pressure_transition_rejects_noops_and_invented_resolutions() { - let current = vec!["the ferry deadline is near".into()]; - assert!( - validate_gestalt_pressure_transition( - ¤t, - &["shelter assignments are disputed".into()], - &["the ferry deadline is near".into()], - ) - .is_ok() - ); - assert!(validate_gestalt_pressure_transition(¤t, &[], &[]).is_err()); - let repeated = validate_gestalt_pressure_transition( - ¤t, - &["THE FERRY DEADLINE IS NEAR".into()], - &[], - ) - .unwrap_err(); - assert!(repeated.to_string().contains("already exist")); - let invented = validate_gestalt_pressure_transition( - ¤t, - &[], - &["an invented solved problem".into()], - ) - .unwrap_err(); - assert!(invented.to_string().contains("not exact current markers")); - assert!(invented.to_string().contains("the ferry deadline is near")); - assert!(!substantive_text_change( - "holding position", - "Holding Position" - )); - assert!(substantive_text_change( - "holding position", - "releasing the reserve" - )); - assert!(substantive_text_change( - "holding position", - &"a".repeat(MAX_POSTURE_CHARS + 1) - )); - } - - #[test] - fn canonical_actor_activity_uses_exact_actor_scope() { - let mut value = campaign(0, 1); - let mut liaison = value.actors["player"].clone(); - liaison.id = "liaison".into(); - liaison.name = "Liaison".into(); - liaison.capabilities.insert("read ration ledgers".into()); - value.actors.insert(liaison.id.clone(), liaison); - ensure_agency_profiles(&mut value); - let cell = SimulationCell { - schema: "ghostlight.simulation_cell.v1".into(), - id: "cell:liaison".into(), - mode: SimulationCellMode::Cohesive, - subject_ids: BTreeSet::from(["liaison".into()]), - merge_loss: MergeLoss::default(), - rationale: "exact actor fixture".into(), - lease_until_world_revision: 0, - lease_until_strategic_tick: 0, - detail_focus_subject_id: Some("liaison".into()), - }; - let proposal = CellActionProposal { - subject_id: "liaison".into(), - intent: "inspect the room's ration ledger".into(), - intended_effect: "attempt a local investigation".into(), - priority: 50, - state_references: vec!["subject:liaison".into()], - public_channels: vec![], - effects: vec![StrategicCellEffect::ActorActivity { - actor_id: "liaison".into(), - activity: StrategicActivityKind::Investigate, - target_subject_ids: vec![], - location_ids: vec!["center".into()], - }], - }; - validate_cell_proposal(&value, &cell, &proposal).unwrap(); - - let mut wrong_location = proposal.clone(); - let StrategicCellEffect::ActorActivity { location_ids, .. } = - &mut wrong_location.effects[0] - else { - unreachable!() - }; - *location_ids = vec!["somewhere-else".into()]; - assert!(validate_cell_proposal(&value, &cell, &wrong_location).is_err()); - - let mut player_puppet = proposal; - player_puppet.subject_id = "player".into(); - let StrategicCellEffect::ActorActivity { actor_id, .. } = &mut player_puppet.effects[0] - else { - unreachable!() - }; - *actor_id = "player".into(); - assert!(validate_cell_proposal(&value, &cell, &player_puppet).is_err()); - } - - #[test] - fn selected_action_projects_travel_and_destination_activity_as_one_choice() { - let mut value = campaign(0, 1); - value.locations.insert( - "encampment".into(), - Location { - id: "encampment".into(), - name: "Refugee Encampment".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - ); - value.locations.get_mut("center").unwrap().routes.insert( - "to-encampment".into(), - Route { - destination_id: "encampment".into(), - distance: "nearby".into(), - travel_minutes: 30, - }, - ); - let mut liaison = value.actors["player"].clone(); - liaison.id = "liaison".into(); - liaison.name = "Liaison".into(); - value.actors.insert(liaison.id.clone(), liaison); - ensure_agency_profiles(&mut value); - let cell = SimulationCell { - schema: "ghostlight.simulation_cell.v1".into(), - id: "cell:liaison".into(), - mode: SimulationCellMode::Cohesive, - subject_ids: BTreeSet::from(["liaison".into()]), - merge_loss: MergeLoss::default(), - rationale: "exact actor fixture".into(), - lease_until_world_revision: 0, - lease_until_strategic_tick: 0, - detail_focus_subject_id: Some("liaison".into()), - }; - let proposal = CellActionProposal { - subject_id: "liaison".into(), - intent: "travel to the encampment and ask about its shortage".into(), - intended_effect: "arrive and make one local request".into(), - priority: 70, - state_references: vec!["subject:liaison".into()], - public_channels: vec![], - effects: vec![ - StrategicCellEffect::ActorMove { - actor_id: "liaison".into(), - destination_id: "encampment".into(), - }, - StrategicCellEffect::ActorActivity { - actor_id: "liaison".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec![], - location_ids: vec!["encampment".into()], - }, - ], - }; - - validate_cell_proposal(&value, &cell, &proposal).unwrap(); - let digest = cell_action_digest(&proposal).unwrap(); - let plan = project_selected_actions(&value, vec![proposal.clone()]).unwrap(); - assert_eq!(plan.selected_actions, vec![proposal]); - assert_eq!(plan.actor_moves.len(), 1); - assert_eq!(plan.actor_activities.len(), 1); - assert_eq!(plan.actor_activities[0].action_digest, digest); - assert_eq!(plan.actor_activities[0].location_ids, vec!["encampment"]); - } - - #[test] - fn partitions_one_thousand_subjects_with_bounded_local_work() { - let value = campaign(1_000, 8); - let started = Instant::now(); - let cover = plan_cover(&value, default_demand(&value, "large skeleton")).unwrap(); - assert_eq!(cover.cells.len(), 8); - if cfg!(debug_assertions) { - assert!(started.elapsed().as_secs_f32() < 6.0); - } else { - assert!(started.elapsed().as_millis() < 100); - } - } - - #[test] - fn partitions_one_thousand_subjects_into_a_two_hundred_cell_wave() { - let value = campaign(1_000, 200); - let cover = plan_cover(&value, default_demand(&value, "hundreds-class world")).unwrap(); - assert_eq!(cover.configured_budget, 200); - assert_eq!(cover.effective_budget, 200); - assert_eq!(cover.cells.len(), 200); - let represented = cover - .cells - .iter() - .flat_map(|cell| cell.subject_ids.iter()) - .collect::>(); - assert_eq!(represented.len(), 1_000); - } - - #[test] - fn partitions_twenty_four_hundred_subjects_into_a_two_hundred_forty_cell_cover() { - let value = campaign(2_400, 240); - let started = Instant::now(); - let cover = plan_cover( - &value, - default_demand(&value, "ten-percent expanded-world cover"), - ) - .unwrap(); - assert_eq!(cover.configured_budget, 240); - assert_eq!(cover.effective_budget, 240); - assert_eq!(cover.cells.len(), 240); - let represented = cover - .cells - .iter() - .flat_map(|cell| cell.subject_ids.iter()) - .collect::>(); - assert_eq!(represented.len(), 2_400); - if cfg!(debug_assertions) { - assert!(started.elapsed().as_secs_f32() < 20.0); - } - } - - #[test] - fn arena_cannot_act_as_a_collective_or_borrow_a_constituents_secret() { - let mut value = campaign(2, 1); - value.agency_relations.insert( - "rivalry".into(), - AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "rivalry".into(), - from_subject_id: "faction-0000".into(), - to_subject_id: "faction-0001".into(), - kind: AgencyRelationKind::Rivalry, - strength: 100, - active: true, - evidence_receipt_ids: vec![], - }, - ); - value - .agency_profiles - .get_mut("faction-0001") - .unwrap() - .information_channels - .insert("secret-courier".into()); - let cover = plan_cover(&value, default_demand(&value, "espionage")).unwrap(); - let cell = cover.cells[0].clone(); - assert_eq!(cell.mode, SimulationCellMode::Arena); - let make_wave = |proposal: CellActionProposal| { - let decision_owner = proposal.subject_id.clone(); - let detail_focus = cover.cells[0].detail_focus_subject_id.clone(); - let mut considered_subject_ids = BTreeSet::from([decision_owner.clone()]); - let mut inactions = Vec::new(); - if let Some(detail_focus) = detail_focus.filter(|focus| focus != &decision_owner) { - considered_subject_ids.insert(detail_focus.clone()); - inactions.push(CellInaction { - subject_id: detail_focus, - reason: "The detail-focus subject explicitly holds its current course.".into(), - }); - } - ResolutionWaveCommit { - schema: "ghostlight.resolution_wave_commit.v1".into(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - plan_receipt: plan_receipt(&value, &cover), - appraisals: vec![CellAppraisal { - schema: "ghostlight.cell_appraisal.v1".into(), - cell_id: cell.id.clone(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - considered_subject_ids, - actions: vec![proposal], - inactions, - }], - cover: cover.clone(), - activity_outcomes: vec![], - strategic_individuations: vec![], - model_receipt_hashes: vec![], - } - }; - let collective = CellActionProposal { - subject_id: cell.id.clone(), - intent: "speak for everyone".into(), - intended_effect: "declare consensus".into(), - priority: 1, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::Institution { - institution_id: "faction-0000".into(), - posture: "unified".into(), - location_ids: vec![], - }], - }; - assert!(validate_and_resolve_wave(&value, &make_wave(collective)).is_err()); - let borrowed_secret = CellActionProposal { - subject_id: "faction-0000".into(), - intent: "publish through a rival's courier".into(), - intended_effect: "send a message".into(), - priority: 1, - state_references: vec![], - public_channels: vec!["secret-courier".into()], - effects: vec![StrategicCellEffect::Institution { - institution_id: "faction-0000".into(), - posture: "messaging".into(), - location_ids: vec![], - }], - }; - assert!(validate_and_resolve_wave(&value, &make_wave(borrowed_secret)).is_err()); - - let valid_action = CellActionProposal { - subject_id: "faction-0000".into(), - intent: "publish a bounded position".into(), - intended_effect: "adopt a materially different posture".into(), - priority: 50, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::Institution { - institution_id: "faction-0000".into(), - posture: "publishing a bounded position under the current pressure".into(), - location_ids: vec![], - }], - }; - let mut mixed = make_wave(valid_action.clone()); - mixed.appraisals[0] - .considered_subject_ids - .insert("faction-0001".into()); - mixed.appraisals[0].inactions = vec![CellInaction { - subject_id: "faction-0001".into(), - reason: "The rival deliberately holds its separate position.".into(), - }]; - validate_and_resolve_wave(&value, &mixed).unwrap(); - - let mut maximum_posture = valid_action.clone(); - let StrategicCellEffect::Institution { posture, .. } = &mut maximum_posture.effects[0] - else { - unreachable!() - }; - *posture = "x".repeat(MAX_POSTURE_CHARS); - validate_and_resolve_wave(&value, &make_wave(maximum_posture.clone())).unwrap(); - - let StrategicCellEffect::Institution { posture, .. } = &mut maximum_posture.effects[0] - else { - unreachable!() - }; - posture.push('x'); - assert!(validate_and_resolve_wave(&value, &make_wave(maximum_posture)).is_err()); - - let mut omitted = mixed.clone(); - omitted.appraisals[0].inactions.clear(); - assert!( - validate_and_resolve_wave(&value, &omitted) - .unwrap_err() - .to_string() - .contains("every considered cell subject") - ); - - let mut contradictory = make_wave(valid_action); - contradictory.appraisals[0].inactions = vec![CellInaction { - subject_id: "faction-0000".into(), - reason: "The same institution cannot also hold.".into(), - }]; - assert!(validate_and_resolve_wave(&value, &contradictory).is_err()); - } - - #[test] - fn causal_response_owner_must_consider_and_cite_the_scheduler_admitted_anchor() { - let mut value = campaign(1, 1); - value.events.push(Event { - id: "winter-tally-accusation".into(), - at: value.world_time, - kind: "institution_action".into(), - summary: "Faction 0000 is publicly accused of hiding the winter tally.".into(), - actor_ids: Vec::new(), - institution_ids: vec!["faction-0000".into()], - gestalt_ids: Vec::new(), - location_ids: vec!["center".into()], - public_channels: vec!["public notice".into()], - }); - let mut cover = plan_cover( - &value, - default_demand(&value, "a committed accusation requires a decision window"), - ) - .unwrap(); - cover.causal_follow_through = vec![CausalFollowThroughAssignment { - anchor_reference: "event:winter-tally-accusation".into(), - responder_subject_id: "faction-0000".into(), - }]; - crate::follow_through::validate_causal_follow_through(&value, &cover).unwrap(); - let action = CellActionProposal { - subject_id: "faction-0000".into(), - intent: "answer the accusation".into(), - intended_effect: "publish a bounded denial without deciding public belief".into(), - priority: 50, - state_references: Vec::new(), - public_channels: Vec::new(), - effects: vec![StrategicCellEffect::Institution { - institution_id: "faction-0000".into(), - posture: "publicly contests the winter-tally accusation".into(), - location_ids: Vec::new(), - }], - }; - let make_wave = |action: CellActionProposal| ResolutionWaveCommit { - schema: "ghostlight.resolution_wave_commit.v1".into(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - plan_receipt: plan_receipt(&value, &cover), - appraisals: vec![CellAppraisal { - schema: "ghostlight.cell_appraisal.v1".into(), - cell_id: cover.cells[0].id.clone(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - considered_subject_ids: BTreeSet::from(["faction-0000".into()]), - actions: vec![action], - inactions: Vec::new(), - }], - cover: cover.clone(), - activity_outcomes: Vec::new(), - strategic_individuations: Vec::new(), - model_receipt_hashes: Vec::new(), - }; - - assert!(select_resolution_wave(&value, &make_wave(action.clone())).is_err()); - let mut grounded = action; - grounded - .state_references - .push("event:winter-tally-accusation".into()); - let grounded_result = select_resolution_wave(&value, &make_wave(grounded)); - assert!(grounded_result.is_ok(), "{:#?}", grounded_result.err()); - - let mut omitted = make_wave(CellActionProposal { - subject_id: "faction-0000".into(), - intent: "hold".into(), - intended_effect: "hold".into(), - priority: 1, - state_references: vec!["event:winter-tally-accusation".into()], - public_channels: Vec::new(), - effects: vec![StrategicCellEffect::Institution { - institution_id: "faction-0000".into(), - posture: "holds its prior course".into(), - location_ids: vec!["center".into()], - }], - }); - omitted.appraisals[0].considered_subject_ids.clear(); - assert!(select_resolution_wave(&value, &omitted).is_err()); - } - - #[test] - fn rival_arena_preserves_named_member_agency_and_exact_private_state() { - let mut value = campaign(0, 1); - let gestalt = |id: &str, name: &str, knowledge: &[&str]| GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: id.into(), - name: name.into(), - version: 0, - home_location_id: "center".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: knowledge.iter().map(|value| (*value).into()).collect(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }; - value.gestalts.insert( - "refugees".into(), - gestalt("refugees", "Transit refugees", &["camp schedule"]), - ); - value.gestalts.insert( - "dockers".into(), - gestalt("dockers", "Dock residents", &["private dock code"]), - ); - value.gestalt_members.insert( - "mira".into(), - GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "mira".into(), - gestalt_id: "refugees".into(), - version: 1, - name: "Mira".into(), - capability_additions: BTreeSet::new(), - capability_removals: BTreeSet::new(), - knowledge_additions: BTreeSet::from(["the player helped me".into()]), - knowledge_removals: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::from([("player".into(), "trusted rescuer".into())]), - goals: vec!["settle somewhere safe".into()], - memories: vec!["escaped the fire with the player's help".into()], - last_location_id: Some("center".into()), - materialized_actor_id: None, - last_relevant_revision: 1, - relevance_lease_until_revision: 0, - }, - ); - ensure_agency_profiles(&mut value); - assert!( - member_activity_targets(&value, "mira") - .unwrap() - .contains("player"), - "a folded named member may address the co-located human without making the human Persona-controlled" - ); - value - .agency_profiles - .get_mut("refugees") - .unwrap() - .information_channels - .insert("camp-bulletin".into()); - value.agency_relations.insert( - "rivalry".into(), - AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "rivalry".into(), - from_subject_id: "refugees".into(), - to_subject_id: "dockers".into(), - kind: AgencyRelationKind::Rivalry, - strength: 70, - active: true, - evidence_receipt_ids: vec![], - }, - ); - value.agency_relations.insert( - "migration".into(), - AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "migration".into(), - from_subject_id: "refugees".into(), - to_subject_id: "dockers".into(), - kind: AgencyRelationKind::Migration, - strength: 90, - active: true, - evidence_receipt_ids: vec![], - }, - ); - let demand = default_demand(&value, "resettlement under hostile pressure"); - let cover = plan_cover(&value, demand).unwrap(); - assert_eq!(cover.cells.len(), 1); - assert_eq!(cover.cells[0].mode, SimulationCellMode::Arena); - let proposal = CellActionProposal { - subject_id: "member:mira".into(), - intent: "take the offered berth".into(), - intended_effect: - "Mira joins the dock residents without speaking for either population.".into(), - priority: 5, - state_references: vec![ - "member:mira".into(), - "knowledge:the player helped me".into(), - ], - public_channels: vec![], - effects: vec![StrategicCellEffect::MemberMigration { - destination_gestalt_id: "dockers".into(), - }], - }; - let make_wave = |proposal: CellActionProposal| { - let decision_owner = proposal.subject_id.clone(); - let detail_focus = cover.cells[0].detail_focus_subject_id.clone(); - let mut considered_subject_ids = BTreeSet::from([decision_owner.clone()]); - let mut inactions = Vec::new(); - if let Some(detail_focus) = detail_focus.filter(|focus| focus != &decision_owner) { - considered_subject_ids.insert(detail_focus.clone()); - inactions.push(CellInaction { - subject_id: detail_focus, - reason: "The detail-focus subject explicitly holds its current course.".into(), - }); - } - ResolutionWaveCommit { - schema: "ghostlight.resolution_wave_commit.v1".into(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - plan_receipt: plan_receipt(&value, &cover), - appraisals: vec![CellAppraisal { - schema: "ghostlight.cell_appraisal.v1".into(), - cell_id: cover.cells[0].id.clone(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - considered_subject_ids, - actions: vec![proposal], - inactions, - }], - cover: cover.clone(), - activity_outcomes: vec![], - strategic_individuations: vec![], - model_receipt_hashes: vec![], - } - }; - let plan = validate_and_resolve_wave(&value, &make_wave(proposal.clone())).unwrap(); - assert_eq!(plan.member_migrations.len(), 1); - - let member_activity = CellActionProposal { - subject_id: "member:mira".into(), - intent: "offer help to the refugee organizers".into(), - intended_effect: "make the offer without deciding their response".into(), - priority: 90, - state_references: vec!["member:mira".into()], - public_channels: vec!["camp-bulletin".into()], - effects: vec![StrategicCellEffect::MemberActivity { - member_id: "mira".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["refugees".into()], - location_ids: vec!["center".into()], - }], - }; - let activity_plan = select_resolution_wave(&value, &make_wave(member_activity.clone())) - .unwrap() - .plan; - assert_eq!(activity_plan.member_activities.len(), 1); - assert!(activity_plan.member_migrations.is_empty()); - - let mut local_member_communication = member_activity.clone(); - let StrategicCellEffect::MemberActivity { - target_subject_ids, .. - } = &mut local_member_communication.effects[0] - else { - unreachable!() - }; - target_subject_ids.clear(); - assert!(select_resolution_wave(&value, &make_wave(local_member_communication)).is_ok()); - - let mut targetless_member_coordination = member_activity.clone(); - let StrategicCellEffect::MemberActivity { - activity, - target_subject_ids, - .. - } = &mut targetless_member_coordination.effects[0] - else { - unreachable!() - }; - *activity = StrategicActivityKind::Coordinate; - target_subject_ids.clear(); - assert!( - select_resolution_wave(&value, &make_wave(targetless_member_coordination)).is_err() - ); - - let same_member_wave = ResolutionWaveCommit { - schema: "ghostlight.resolution_wave_commit.v1".into(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - plan_receipt: plan_receipt(&value, &cover), - appraisals: vec![CellAppraisal { - schema: "ghostlight.cell_appraisal.v1".into(), - cell_id: cover.cells[0].id.clone(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - considered_subject_ids: BTreeSet::from(["member:mira".into()]), - actions: vec![member_activity.clone(), proposal.clone()], - inactions: vec![], - }], - cover: cover.clone(), - activity_outcomes: vec![], - strategic_individuations: vec![], - model_receipt_hashes: vec![], - }; - assert!(select_resolution_wave(&value, &same_member_wave).is_err()); - - let mut announced = proposal.clone(); - announced.public_channels = vec!["camp-bulletin".into()]; - assert!(validate_and_resolve_wave(&value, &make_wave(announced)).is_ok()); - - let mut knowledge_as_channel = proposal.clone(); - knowledge_as_channel.public_channels = vec!["the player helped me".into()]; - assert!(validate_and_resolve_wave(&value, &make_wave(knowledge_as_channel)).is_err()); - - let mut collective_theft = proposal.clone(); - collective_theft.subject_id = "refugees".into(); - assert!(validate_and_resolve_wave(&value, &make_wave(collective_theft)).is_err()); - - let mut borrowed_secret = proposal; - borrowed_secret - .state_references - .push("knowledge:private dock code".into()); - assert!(validate_and_resolve_wave(&value, &make_wave(borrowed_secret)).is_err()); - - let exact_rival_activity = CellActionProposal { - subject_id: "refugees".into(), - intent: "challenge the dockers' exclusion plan".into(), - intended_effect: "attempt to obstruct the dockers without speaking for them".into(), - priority: 80, - state_references: vec!["subject:refugees".into()], - public_channels: vec!["camp-bulletin".into()], - effects: vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees".into(), - activity: StrategicActivityKind::Obstruct, - target_subject_ids: vec!["dockers".into()], - location_ids: vec!["center".into()], - }], - }; - let activity_plan = - select_resolution_wave(&value, &make_wave(exact_rival_activity.clone())) - .unwrap() - .plan; - assert_eq!(activity_plan.gestalt_activities.len(), 1); - assert!(activity_plan.gestalt_actions.is_empty()); - - let internal_coordination = CellActionProposal { - subject_id: "refugees".into(), - intent: "coordinate the refugee households' own water watch".into(), - intended_effect: "attempt internal coordination without inventing an external target" - .into(), - priority: 80, - state_references: vec!["subject:refugees".into()], - public_channels: vec![], - effects: vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "refugees".into(), - activity: StrategicActivityKind::Coordinate, - target_subject_ids: vec![], - location_ids: vec!["center".into()], - }], - }; - let internal_plan = select_resolution_wave(&value, &make_wave(internal_coordination)) - .unwrap() - .plan; - assert_eq!(internal_plan.gestalt_activities.len(), 1); - assert!( - internal_plan.gestalt_activities[0] - .target_subject_ids - .is_empty() - ); - - let lower_priority_pressure = CellActionProposal { - subject_id: "refugees".into(), - intent: "register the unresolved exclusion".into(), - intended_effect: "add a pressure marker".into(), - priority: 20, - state_references: vec!["subject:refugees".into()], - public_channels: vec![], - effects: vec![StrategicCellEffect::Gestalt { - gestalt_id: "refugees".into(), - pressure_additions: vec!["the dockers' exclusion remains unresolved".into()], - pressure_resolutions: vec![], - }], - }; - let same_subject_wave = ResolutionWaveCommit { - schema: "ghostlight.resolution_wave_commit.v1".into(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - plan_receipt: plan_receipt(&value, &cover), - appraisals: vec![CellAppraisal { - schema: "ghostlight.cell_appraisal.v1".into(), - cell_id: cover.cells[0].id.clone(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - considered_subject_ids: BTreeSet::from(["refugees".into()]), - actions: vec![exact_rival_activity.clone(), lower_priority_pressure], - inactions: vec![], - }], - cover: cover.clone(), - activity_outcomes: vec![], - strategic_individuations: vec![], - model_receipt_hashes: vec![], - }; - assert!(select_resolution_wave(&value, &same_subject_wave).is_err()); - - let mut borrowed_rival_channel = exact_rival_activity.clone(); - borrowed_rival_channel.public_channels = vec!["private dock code".into()]; - assert!(select_resolution_wave(&value, &make_wave(borrowed_rival_channel)).is_err()); - - let mut invented_target = exact_rival_activity; - let StrategicCellEffect::GestaltActivity { - target_subject_ids, .. - } = &mut invented_target.effects[0] - else { - unreachable!() - }; - *target_subject_ids = vec!["unseen-stranger".into()]; - assert!(select_resolution_wave(&value, &make_wave(invented_target)).is_err()); - - assert!(strategic_activity_targets(&value, "dockers").contains("member:mira")); - let address_mira = CellActionProposal { - subject_id: "dockers".into(), - intent: "offer Mira paid work unloading the next boat".into(), - intended_effect: "make the offer without deciding Mira's response".into(), - priority: 75, - state_references: vec!["subject:dockers".into()], - public_channels: vec![], - effects: vec![StrategicCellEffect::GestaltActivity { - gestalt_id: "dockers".into(), - activity: StrategicActivityKind::Communicate, - target_subject_ids: vec!["member:mira".into()], - location_ids: vec!["center".into()], - }], - }; - let address_plan = select_resolution_wave(&value, &make_wave(address_mira)) - .unwrap() - .plan; - assert_eq!(address_plan.gestalt_activities.len(), 1); - assert_eq!(address_plan.gestalt_activities[0].gestalt_id, "dockers"); - assert_eq!( - address_plan.gestalt_activities[0].target_subject_ids, - vec!["member:mira"] - ); - } - - #[test] - fn consequence_cap_keeps_the_highest_numeric_priorities() { - let value = campaign(3, 1); - let cover = plan_cover(&value, default_demand(&value, "urgent choices")).unwrap(); - assert_eq!(cover.cells.len(), 1); - let cell = &cover.cells[0]; - let action = |subject_id: &str, priority: i16| CellActionProposal { - subject_id: subject_id.into(), - intent: format!("{subject_id} commits"), - intended_effect: format!("{subject_id} adopts an urgent posture"), - priority, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::Institution { - institution_id: subject_id.into(), - posture: format!("urgent posture {priority}"), - location_ids: vec![], - }], - }; - let wave = ResolutionWaveCommit { - schema: "ghostlight.resolution_wave_commit.v1".into(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - plan_receipt: plan_receipt(&value, &cover), - appraisals: vec![CellAppraisal { - schema: "ghostlight.cell_appraisal.v1".into(), - cell_id: cell.id.clone(), - world_revision: value.revision, - resolution_epoch: value.resolution_policy.resolution_epoch, - considered_subject_ids: cell.subject_ids.clone(), - actions: vec![ - action("faction-0000", 1), - action("faction-0001", 100), - action("faction-0002", 50), - ], - inactions: vec![], - }], - cover, - activity_outcomes: vec![], - strategic_individuations: vec![], - model_receipt_hashes: vec![], - }; - let plan = validate_and_resolve_wave(&value, &wave).unwrap(); - assert_eq!(plan.institution_actions.len(), 2); - assert_eq!(plan.institution_actions[0].institution_id, "faction-0001"); - assert_eq!(plan.institution_actions[1].institution_id, "faction-0002"); - } - - #[test] - fn fission_preserves_parent_and_member_delta_while_activating_child_leaves() { - let mut value = campaign(1, 1); - value.gestalts.insert( - "villagers".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "villagers".into(), - name: "Villagers".into(), - version: 0, - home_location_id: "center".into(), - shared_capabilities: BTreeSet::from(["farm".into()]), - shared_knowledge: BTreeSet::from(["local roads".into()]), - resources: BTreeSet::from(["granary".into()]), - goals: vec!["survive winter".into()], - pressures: vec![], - }, - ); - value.gestalt_members.insert( - "john".into(), - GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "john".into(), - gestalt_id: "villagers".into(), - version: 3, - name: "John".into(), - capability_additions: BTreeSet::from(["smith".into()]), - capability_removals: BTreeSet::new(), - knowledge_additions: BTreeSet::new(), - knowledge_removals: BTreeSet::new(), - equipment: BTreeSet::from(["hammer".into()]), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec!["met the traveler".into()], - last_location_id: Some("center".into()), - materialized_actor_id: None, - last_relevant_revision: 0, - relevance_lease_until_revision: 0, - }, - ); - ensure_agency_profiles(&mut value); - let child = |id: &str, name: &str| GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: id.into(), - name: name.into(), - version: 0, - home_location_id: "center".into(), - shared_capabilities: BTreeSet::from(["farm".into()]), - shared_knowledge: BTreeSet::from(["local roads".into()]), - resources: BTreeSet::new(), - goals: vec!["survive winter".into()], - pressures: vec![], - }; - let mut other = child("other", "Other villagers"); - other.resources.insert("granary".into()); - let preview = GestaltFissionPreview { - schema: "ghostlight.gestalt_fission_preview.v1".into(), - campaign_id: value.id, - expected_world_revision: value.revision, - parent_gestalt_id: "villagers".into(), - partition_axis: AgencyAxis::Ideology, - children: vec![child("traditionalists", "Traditionalists"), other], - child_partition_values: BTreeMap::from([ - ("traditionalists".into(), "traditionalist".into()), - ("other".into(), "other/unknown".into()), - ]), - residual_child_id: "other".into(), - member_child_assignments: BTreeMap::new(), - resource_child_assignments: BTreeMap::from([("granary".into(), "other".into())]), - evidence_receipt_ids: vec![], - gaps: vec![], - canon_candidates: vec![], - requires_approval: true, - }; - let mut duplicated = preview.clone(); - duplicated.requires_approval = false; - duplicated.children[0].name.clear(); - duplicated.children[0].resources.insert("granary".into()); - let diagnostic = validate_fission(&value, &duplicated) - .unwrap_err() - .to_string(); - assert!(diagnostic.contains("must require approval")); - assert!(diagnostic.contains("has an empty name")); - assert!(diagnostic.contains("appears in more than one child")); - let transition = crate::legacy_transition::lower_fission( - &value, - &preview, - Utc::now() + chrono::Duration::minutes(5), - ) - .unwrap(); - crate::legacy_transition::apply_lowered_fission( - &mut value, - &preview, - &transition, - Utc::now(), - ) - .unwrap(); - value.revision += 1; - assert!(value.gestalts.contains_key("villagers")); - assert!(!value.agency_profiles["villagers"].active_leaf); - assert!(value.agency_profiles["traditionalists"].active_leaf); - assert!(value.agency_profiles["other"].active_leaf); - assert!(value.agency_profiles["traditionalists"].simulation_eligible); - assert!(!value.agency_profiles["other"].simulation_eligible); - assert!(value.gestalts["villagers"].resources.is_empty()); - assert!(value.gestalts["traditionalists"].resources.is_empty()); - assert_eq!( - value.gestalts["other"].resources, - BTreeSet::from(["granary".into()]) - ); - assert_eq!(value.gestalt_members["john"].gestalt_id, "other"); - assert_eq!(value.gestalt_members["john"].version, 4); - assert!( - value.gestalt_members["john"] - .memories - .contains(&"met the traveler".into()) - ); - assert_eq!( - value.gestalt_lineages["villagers"].residual_child_id, - "other" - ); - - let john_actor_id = crate::domain::gestalt_member_subject_id("john"); - value.actors.insert( - john_actor_id.clone(), - ActorState { - id: john_actor_id.clone(), - name: "John".into(), - location_id: "center".into(), - capabilities: BTreeSet::from(["farm".into(), "smith".into()]), - knowledge: BTreeSet::from(["local roads".into()]), - equipment: BTreeSet::from(["hammer".into()]), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec!["survive winter".into()], - memories: vec!["met the traveler".into()], - }, - ); - value - .gestalt_members - .get_mut("john") - .unwrap() - .materialized_actor_id = Some(john_actor_id.clone()); - ensure_agency_profiles(&mut value); - let john_before_nested_fission = value.actors[&john_actor_id].clone(); - - let mut nested_residual = child("other-unknown", "Other unclassified villagers"); - nested_residual.resources.insert("granary".into()); - let nested = GestaltFissionPreview { - schema: "ghostlight.gestalt_fission_preview.v1".into(), - campaign_id: value.id, - expected_world_revision: value.revision, - parent_gestalt_id: "other".into(), - partition_axis: AgencyAxis::EconomyRole, - children: vec![ - child("other-smiths", "Smiths among the other villagers"), - nested_residual, - ], - child_partition_values: BTreeMap::from([ - ("other-smiths".into(), "smith".into()), - ("other-unknown".into(), "other/unknown".into()), - ]), - residual_child_id: "other-unknown".into(), - member_child_assignments: BTreeMap::from([("john".into(), "other-smiths".into())]), - resource_child_assignments: BTreeMap::from([( - "granary".into(), - "other-unknown".into(), - )]), - evidence_receipt_ids: vec![], - gaps: vec![], - canon_candidates: vec![], - requires_approval: true, - }; - let transition = crate::legacy_transition::lower_fission( - &value, - &nested, - Utc::now() + chrono::Duration::minutes(5), - ) - .unwrap(); - crate::legacy_transition::apply_lowered_fission( - &mut value, - &nested, - &transition, - Utc::now(), - ) - .unwrap(); - assert!(!value.agency_profiles["other"].active_leaf); - assert!(value.agency_profiles["other-smiths"].active_leaf); - assert!(value.agency_profiles["other-smiths"].simulation_eligible); - assert!(!value.agency_profiles["other-unknown"].simulation_eligible); - assert!(value.gestalts["other"].resources.is_empty()); - assert!(value.gestalts["other-smiths"].resources.is_empty()); - assert_eq!( - value.gestalts["other-unknown"].resources, - BTreeSet::from(["granary".into()]) - ); - assert_eq!(value.gestalt_members["john"].gestalt_id, "other-smiths"); - assert_eq!(value.actors[&john_actor_id], john_before_nested_fission); - assert_eq!( - value.gestalt_members["john"] - .materialized_actor_id - .as_deref(), - Some(john_actor_id.as_str()) - ); - assert_eq!(value.gestalt_members["john"].version, 5); - assert_eq!( - value.gestalt_members["john"].memories, - vec!["met the traveler"] - ); - assert!( - effective_member_capabilities(&value, "john") - .unwrap() - .contains("smith") - ); - validate_active_gestalt_presence_location(&value, "other-smiths", "center").unwrap(); - assert!(validate_active_gestalt_presence_location(&value, "other", "center").is_err()); - assert!(validate_active_gestalt_presence_location(&value, "villagers", "center").is_err()); - } - - #[test] - fn golden_pressures_preserve_the_behavioral_boundary_they_weight() { - for axis in [ - AgencyAxis::Geography, - AgencyAxis::Ideology, - AgencyAxis::EconomyRole, - AgencyAxis::SpeciesBody, - AgencyAxis::Information, - ] { - let mut value = campaign(4, 2); - for (index, id) in (0..4).map(|index| (index, format!("faction-{index:04}"))) { - let profile = value.agency_profiles.get_mut(&id).unwrap(); - for current in [ - AgencyAxis::Geography, - AgencyAxis::Ideology, - AgencyAxis::Authority, - AgencyAxis::EconomyRole, - AgencyAxis::SpeciesBody, - AgencyAxis::Information, - ] { - profile - .facets - .insert(current, BTreeSet::from(["shared".into()])); - } - profile.facets.insert( - axis.clone(), - BTreeSet::from([format!("side-{}", index / 2)]), - ); - } - let mut demand = default_demand(&value, format!("golden {axis:?}")); - for weight in demand.axis_weights.values_mut() { - *weight = 0.02; - } - demand.axis_weights.insert(axis.clone(), 0.90); - let cover = plan_cover(&value, demand).unwrap(); - assert_eq!(cover.cells.len(), 2); - for cell in cover.cells { - let preserved_values: BTreeSet<_> = cell - .subject_ids - .iter() - .flat_map(|id| value.agency_profiles[id].facets[&axis].iter().cloned()) - .collect(); - assert_eq!(preserved_values.len(), 1, "failed golden pressure {axis:?}"); - } - } - } -} diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs new file mode 100644 index 0000000..4daba0c --- /dev/null +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -0,0 +1,1976 @@ +//! One-process runtime for the sealed world owner. + +use crate::{ + app_session::{AppSessionOwner, VerifiedPrincipalEvidence}, + eve::{self, EveCommandInvocation}, + heimdall::{self, HeimdallClient}, + idunn_health::{ + GHOSTLIGHT_IDUNN_HEALTH_CONTRACT, GhostlightTrafficAdmissionGate, IdunnHealthPublisher, + IdunnReleaseBinding, active_activation_binding, + }, + mesh::{self, MeshPublisher, MeshRuntimeIdentity}, + world::{ + AffordanceId, CommandBody, CommandId, ControllerError, ControllerModels, + ControllerPendingReason, ControllerRunner, ControllerWorkCustody, CreateWorldIntent, + DecisionAction, DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, + NarrativeRun, OperationalRun, PrincipalCommandIntent, PrincipalId, SubmissionDisposition, + SubmitReceipt, WorldMailbox, WorldSnapshot, + }, +}; +use anyhow::{Context, bail}; +use axum::{ + Json, Router, + extract::{Path, Request, State}, + http::{HeaderMap, HeaderValue, StatusCode, header}, + middleware::{self, Next}, + response::{ + IntoResponse, Response, + sse::{Event as SseEvent, KeepAlive, Sse}, + }, + routing::{get, post}, +}; +use chrono::{DateTime, Utc}; +use serde::Deserialize; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::{convert::Infallible, net::SocketAddr, path::PathBuf, sync::Arc, time::Duration}; +use tokio::sync::{Mutex, broadcast, mpsc}; +use tower_http::services::ServeDir; +use tracing_subscriber::EnvFilter; + +const COOKIE_NAME: &str = "ghostlight_session"; + +#[derive(Clone)] +struct AppState { + world: WorldMailbox, + controllers: Arc>>, + sessions: Arc>, + heimdall: Arc, + mesh: Option, + mesh_identity: MeshRuntimeIdentity, + revisions: broadcast::Sender, + fatal: mpsc::UnboundedSender, + traffic: Option>, +} + +struct ProductionAdmission { + traffic: Arc, + health: IdunnHealthPublisher, +} + +#[derive(Clone)] +struct RequestTrafficAdmission { + traffic: Arc, + fatal: mpsc::UnboundedSender, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct CreatePayload { + title: String, + subject_label: String, + #[serde(default)] + narrative_persona_label: Option, + #[serde(default)] + operational_agent_label: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SpeakPayload { + text: String, + opportunity: DecisionOpportunity, + affordance_id: AffordanceId, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct EmptyPayload {} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct CompleteAuthPayload { + handle: String, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ControllerActPayload { + opportunity: DecisionOpportunity, +} + +pub(crate) async fn run() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter(EnvFilter::from_default_env()) + .init(); + let runtime_root = std::env::var_os("GHOSTLIGHT_DUNGEON_ROOT") + .map(PathBuf::from) + .unwrap_or_else(default_runtime_root); + let service_root = runtime_root.join("service"); + let runtime_id = + std::env::var("GHOSTLIGHT_RUNTIME_ID").unwrap_or_else(|_| "ghostlight-dungeon".into()); + let mesh_identity = MeshRuntimeIdentity { + runtime_id: runtime_id.clone(), + service_id: std::env::var("GHOSTLIGHT_SERVICE_ID") + .unwrap_or_else(|_| "ghostlight-dungeon".into()), + located_service: std::env::var("GHOSTLIGHT_LOCATED_SERVICE") + .unwrap_or_else(|_| "local".into()), + }; + + // Production may inspect immutable root activation inputs and the provider + // health identity, then publish one warming statement. World, session, + // controller, replay, CultMesh, and socket authority remain unopened until + // Idunn grants that exact statement. + let (fatal, mut fatal_events) = mpsc::unbounded_channel(); + let production_admission = initialize_production_admission(&mesh_identity).await?; + let mut request_admission = None; + let mut idunn_health = match production_admission { + Some(admission) => { + let ProductionAdmission { traffic, health } = admission; + traffic + .require_current() + .context("root traffic admission changed after initial grant")?; + request_admission = Some(RequestTrafficAdmission { + traffic: traffic.clone(), + fatal: fatal.clone(), + }); + let traffic_failure = fatal.clone(); + tokio::spawn(async move { + if let Err(error) = maintain_traffic_admission(traffic).await { + let _ = traffic_failure + .send(format!("root traffic admission was revoked: {error:#}")); + } + }); + Some(health) + } + None => None, + }; + + tokio::task::yield_now().await; + require_no_runtime_custody_failure(&mut fatal_events)?; + std::fs::create_dir_all(&service_root)?; + let (world, world_owner) = WorldMailbox::open(runtime_root.join("world.cc"))?; + require_no_runtime_custody_failure(&mut fatal_events)?; + let controllers = match open_controller(&world, &service_root, &runtime_id) { + Ok(runner) => Some(runner), + Err(error) => { + tracing::warn!(%error, "controller cognition is unavailable; world authority remains online"); + None + } + }; + require_no_runtime_custody_failure(&mut fatal_events)?; + let wrapping_key = std::env::var_os("GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE") + .map(PathBuf::from) + .unwrap_or_else(|| runtime_root.join("secrets/session-wrapping.key")); + let sessions = AppSessionOwner::open(service_root.join("app-sessions-v2.cc"), wrapping_key)?; + let heimdall = Arc::new(HeimdallClient::from_env()?); + require_no_runtime_custody_failure(&mut fatal_events)?; + let mesh = match open_mesh(&service_root, &mesh_identity) { + Ok(mesh) => Some(mesh), + Err(error) => { + tracing::warn!(%error, "derived CultMesh projection is unavailable; world authority remains online"); + None + } + }; + require_no_runtime_custody_failure(&mut fatal_events)?; + let (revisions, _) = broadcast::channel(32); + let state = AppState { + world, + controllers: Arc::new(Mutex::new(controllers)), + sessions: Arc::new(Mutex::new(sessions)), + heimdall, + mesh, + mesh_identity: mesh_identity.clone(), + revisions, + fatal, + traffic: request_admission + .as_ref() + .map(|admission| admission.traffic.clone()), + }; + require_no_runtime_custody_failure(&mut fatal_events)?; + publish_projection(&state).await?; + tokio::spawn(maintain_mesh_projection(state.clone())); + + let release_web_root = std::env::current_exe()? + .parent() + .map(|parent| parent.join("web")); + let web_root = release_web_root + .filter(|path| path.join("index.html").is_file()) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../web/dist")); + let app = app_router(state.clone(), web_root); + let app = match request_admission.clone() { + Some(admission) => app.layer(middleware::from_fn_with_state( + admission, + enforce_request_traffic_admission, + )), + None => app, + }; + let address: SocketAddr = std::env::var("GHOSTLIGHT_DUNGEON_BIND") + .unwrap_or_else(|_| "127.0.0.1:8831".into()) + .parse()?; + require_no_runtime_custody_failure(&mut fatal_events)?; + require_current_traffic_admission(request_admission.as_ref(), "before HTTP bind")?; + let listener = tokio::net::TcpListener::bind(address).await?; + require_no_runtime_custody_failure(&mut fatal_events)?; + require_current_traffic_admission(request_admission.as_ref(), "after HTTP bind")?; + canonical_readiness(&state) + .await + .context("runtime is not ready for active signed health")?; + if let Some(publisher) = idunn_health.as_mut() { + publisher + .publish("active", "world-owner-serving") + .context("publishing initial active Idunn health")?; + } + require_current_traffic_admission(request_admission.as_ref(), "before HTTP serve")?; + tracing::info!(%address, "Ghostlight Dungeon world owner serving"); + let server = axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ); + tokio::select! { + result = server => result.context("Ghostlight HTTP server stopped"), + result = world_owner => { + result.context("world-owner task panicked")?; + bail!("world-owner task stopped while the daemon was serving") + } + result = maintain_runtime_health(idunn_health, state.clone()) => { + result?; + bail!("runtime readiness owner stopped while the daemon was serving") + } + result = maintain_session_refresh(state.clone()) => { + result?; + bail!("app-session refresh owner stopped while the daemon was serving") + } + detail = fatal_events.recv() => { + bail!( + "runtime custody failed: {}", + detail.unwrap_or_else(|| "fatal signal channel closed".into()) + ) + } + } +} + +fn open_controller( + world: &WorldMailbox, + service_root: &std::path::Path, + runtime_id: &str, +) -> anyhow::Result { + let endpoint: SocketAddr = std::env::var("GHOSTLIGHT_CONTROLLER_CONNECTOR") + .unwrap_or_else(|_| "127.0.0.1:4103".into()) + .parse() + .context("GHOSTLIGHT_CONTROLLER_CONNECTOR is not a socket address")?; + let credential = std::env::var_os("GHOSTLIGHT_CONTROLLER_CREDENTIAL") + .map(PathBuf::from) + .context("GHOSTLIGHT_CONTROLLER_CREDENTIAL is required")?; + ControllerRunner::open( + world.clone(), + endpoint, + credential, + runtime_id.to_owned(), + service_root.join("controller-work.cc"), + ControllerModels { + projector: std::env::var("GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL") + .unwrap_or_else(|_| "gpt-5.6-luna".into()), + persona: std::env::var("GHOSTLIGHT_CONTROLLER_PERSONA_MODEL") + .unwrap_or_else(|_| "gpt-5.6-sol".into()), + interpreter: std::env::var("GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL") + .unwrap_or_else(|_| "gpt-5.6-terra".into()), + operational_agent: std::env::var("GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL") + .unwrap_or_else(|_| "gpt-5.6-terra".into()), + }, + ) + .map_err(Into::into) +} + +fn open_mesh( + service_root: &std::path::Path, + identity: &MeshRuntimeIdentity, +) -> anyhow::Result { + let target = std::env::var("GHOSTLIGHT_ODIN_RUDP") + .ok() + .map(|value| value.parse()) + .transpose() + .context("GHOSTLIGHT_ODIN_RUDP is not a socket address")?; + MeshPublisher::open(service_root.join("mesh-v2.cc"), target, identity.clone()) +} + +fn app_router(state: AppState, web_root: PathBuf) -> Router { + api_router(state) + .fallback_service(ServeDir::new(web_root).append_index_html_on_directories(true)) +} + +async fn enforce_request_traffic_admission( + State(admission): State, + request: Request, + next: Next, +) -> Response { + if let Err(error) = admission.traffic.require_current() { + let _ = admission + .fatal + .send(format!("request traffic admission failed: {error:#}")); + return ( + StatusCode::SERVICE_UNAVAILABLE, + "Ghostlight traffic admission is not current", + ) + .into_response(); + } + next.run(request).await +} + +fn api_router(state: AppState) -> Router { + Router::new() + .route("/health", get(health)) + .route("/api/eve/provider", get(eve_provider)) + .route("/api/eve/surfaces/{surface_id}", get(eve_surface)) + .route("/api/eve/commands", post(eve_command)) + .route("/api/eve/events", get(revision_events)) + .with_state(state) +} + +async fn health(State(state): State) -> Response { + match runtime_readiness(&state).await { + Ok(health) => Json(health).into_response(), + Err(error) => ( + StatusCode::SERVICE_UNAVAILABLE, + Json(json!({"status":"failed","message":error.to_string()})), + ) + .into_response(), + } +} + +async fn eve_provider(State(state): State) -> Response { + Json(mesh::provider_advertisement( + &state.mesh_identity, + &Utc::now().to_rfc3339(), + )) + .into_response() +} + +async fn eve_surface( + Path(surface_id): Path, + headers: HeaderMap, + State(state): State, +) -> Response { + if surface_id != mesh::SURFACE_ID { + return StatusCode::NOT_FOUND.into_response(); + } + let Some(principal) = authenticated_principal(&headers, &state).await else { + return Json(eve::anonymous_surface()).into_response(); + }; + match current_world(&state).await.and_then(|snapshot| { + eve::authenticated_surface(principal.account_subject_hash(), snapshot.as_ref()) + }) { + Ok(surface) => Json(surface).into_response(), + Err(error) => ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"message":error.to_string()})), + ) + .into_response(), + } +} + +async fn eve_command( + headers: HeaderMap, + State(state): State, + Json(invocation): Json, +) -> Response { + // Axum has now consumed and decoded the complete command. This is the + // traffic-to-application transfer point: revocation blocks later commands, + // while WorldMailbox owns any consequence accepted below. + if let Err(error) = require_command_traffic_admission(&state) { + let _ = state + .fatal + .send(format!("command traffic admission failed: {error:#}")); + return ( + StatusCode::SERVICE_UNAVAILABLE, + "Ghostlight traffic admission is not current", + ) + .into_response(); + } + if let Err(error) = eve::validate_invocation(&invocation, "https-json") { + return Json(eve::command_result( + &invocation, + "denied", + error.to_string(), + None, + None, + None, + )) + .into_response(); + } + match invocation.operation.operation_id.as_str() { + "heimdall.auth.begin" => begin_authentication(&state, invocation).await, + "heimdall.auth.complete" => complete_authentication(&state, invocation).await, + "app.auth.logout" => logout(&headers, &state, invocation).await, + _ => { + let Some(principal) = authenticated_principal(&headers, &state).await else { + return Json(eve::command_result( + &invocation, + "denied", + "Authentication is required.", + None, + None, + None, + )) + .into_response(); + }; + dispatch_world(&state, &principal, invocation).await + } + } +} + +fn require_command_traffic_admission(state: &AppState) -> anyhow::Result<()> { + match state.traffic.as_ref() { + Some(traffic) => traffic.require_current(), + None => Ok(()), + } +} + +async fn begin_authentication(state: &AppState, invocation: EveCommandInvocation) -> Response { + if let Err(error) = serde_json::from_value::(invocation.payload.clone()) { + return Json(eve::command_result( + &invocation, + "denied", + format!("invalid command payload: {error}"), + None, + None, + None, + )) + .into_response(); + } + let idempotency = invocation + .operation + .idempotency_key + .as_deref() + .unwrap_or(""); + match state.heimdall.begin(idempotency).await { + Ok(receipt) + if receipt.status == "pending" + && !receipt.handle.is_empty() + && receipt + .expires_at + .parse::>() + .is_ok_and(|expiry| expiry > Utc::now()) => + { + Json(eve::command_result( + &invocation, + "accepted", + "Continue authentication with Heimdall.", + None, + Some(json!({ + "pluginId":"gamecult.heimdall.access", + "schemaId":"heimdall.auth_navigation_receipt.v1", + "payload":{ + "schema":"heimdall.auth_navigation_receipt.v1", + "handle":receipt.handle, + "navigation":{ + "url":receipt.navigation.url, + "allowedOrigins":receipt.navigation.allowed_origins + } + } + })), + None, + )) + .into_response() + } + Ok(_) => Json(eve::command_result( + &invocation, + "denied", + "Heimdall returned an invalid authentication attempt.", + None, + None, + None, + )) + .into_response(), + Err(error) => Json(eve::command_result( + &invocation, + "denied", + error.to_string(), + None, + None, + None, + )) + .into_response(), + } +} + +async fn complete_authentication(state: &AppState, invocation: EveCommandInvocation) -> Response { + let payload = match serde_json::from_value::(invocation.payload.clone()) { + Ok(payload) => payload, + Err(error) => { + return Json(eve::command_result( + &invocation, + "denied", + format!("invalid command payload: {error}"), + None, + None, + None, + )) + .into_response(); + } + }; + let handle = payload.handle.as_str(); + if handle.is_empty() { + return Json(eve::command_result( + &invocation, + "denied", + "Authentication completion omitted its opaque handle.", + None, + None, + None, + )) + .into_response(); + } + let idempotency = invocation + .operation + .idempotency_key + .as_deref() + .unwrap_or(""); + let completion = match state.heimdall.complete(handle, idempotency).await { + Ok(value) => value, + Err(error) => { + return Json(eve::command_result( + &invocation, + "denied", + error.to_string(), + None, + None, + None, + )) + .into_response(); + } + }; + if completion.status == "pending" { + return Json(auth_completion_result( + &invocation, + "pending", + "pending", + "Heimdall is waiting for Discord.", + )) + .into_response(); + } + if completion.status != "authenticated" || completion.handle.as_deref() != Some(handle) { + let message = completion + .error + .clone() + .unwrap_or_else(|| "Heimdall denied access.".into()); + return Json(auth_completion_result( + &invocation, + "denied", + "denied", + &message, + )) + .into_response(); + } + let adopted = match adopt_heimdall_completion(state, completion).await { + Ok(value) => value, + Err(error) => { + return Json(auth_completion_result( + &invocation, + "denied", + "denied", + &error.to_string(), + )) + .into_response(); + } + }; + let mut response = Json(auth_completion_result( + &invocation, + "accepted", + "authenticated", + "Authenticated.", + )) + .into_response(); + response.headers_mut().insert( + header::SET_COOKIE, + session_cookie(&adopted.token, adopted.expires_at, Utc::now()), + ); + response +} + +struct AdoptedSession { + token: String, + expires_at: DateTime, +} + +async fn adopt_heimdall_completion( + state: &AppState, + completion: heimdall::AuthCompletionReceipt, +) -> anyhow::Result { + let admission = state.heimdall.verify_completion(completion).await?; + let expires_at = admission.refresh_expires_at(); + let token = { + let mut sessions = state.sessions.lock().await; + let result = sessions.create_session(admission); + if result.is_err() && !sessions.is_healthy() { + signal_fatal( + state, + "app-session authentication adoption", + result.as_ref().unwrap_err(), + ); + } + result? + }; + Ok(AdoptedSession { token, expires_at }) +} + +fn auth_completion_result( + invocation: &EveCommandInvocation, + command_state: &str, + auth_state: &str, + message: &str, +) -> Value { + eve::command_result( + invocation, + command_state, + message, + None, + Some(json!({ + "pluginId":"gamecult.heimdall.access", + "schemaId":"heimdall.auth_completion_status.v1", + "payload":{"schema":"heimdall.auth_completion_status.v1","status":auth_state} + })), + None, + ) +} + +async fn logout( + headers: &HeaderMap, + state: &AppState, + invocation: EveCommandInvocation, +) -> Response { + if let Err(error) = serde_json::from_value::(invocation.payload.clone()) { + return Json(eve::command_result( + &invocation, + "denied", + format!("invalid command payload: {error}"), + None, + None, + None, + )) + .into_response(); + } + let raw_cookie = cookie_value(headers).unwrap_or_default(); + let local_logout = { + let mut sessions = state.sessions.lock().await; + match sessions.session_for_logout(raw_cookie) { + Ok(remote) => match sessions.revoke_cookie(raw_cookie) { + Ok(true) => Ok(remote), + Ok(false) => Ok(remote), + Err(error) => Err(error), + }, + Err(error) => Err(error), + } + }; + let remote = match local_logout { + Ok(remote) => remote, + Err(error) => { + signal_fatal(state, "app-session logout", &error); + return Json(auth_completion_result( + &invocation, + "unknown", + "unknown", + "Local session revocation was not confirmed.", + )) + .into_response(); + } + }; + if let Some(session) = remote { + let heimdall = state.heimdall.clone(); + tokio::spawn(async move { + let idempotency = format!( + "logout:{}:{}", + session.heimdall_session_id, session.access_revision + ); + if let Err(error) = heimdall.logout(&session.refresh_claim, &idempotency).await { + tracing::warn!(%error, "local logout succeeded but Heimdall logout was unavailable"); + } + }); + } + let mut response = Json(auth_completion_result( + &invocation, + "accepted", + "anonymous", + "Signed out.", + )) + .into_response(); + response.headers_mut().insert( + header::SET_COOKIE, + HeaderValue::from_static( + "ghostlight_session=; Max-Age=0; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/", + ), + ); + response +} + +async fn dispatch_world( + state: &AppState, + principal: &VerifiedPrincipalEvidence, + invocation: EveCommandInvocation, +) -> Response { + if invocation.operation.operation_id == "world.controller.act" { + return dispatch_controller(state, principal, invocation).await; + } + let result = execute_world(state, principal, &invocation).await; + match result { + Ok(receipt) => { + let version = match publish_projection(state).await { + Ok(version) => Some(version), + Err(error) => { + tracing::error!(%error, "world revision could not be read after commit"); + current_world(state) + .await + .ok() + .map(|snapshot| eve::surface_version(snapshot.as_ref())) + } + }; + Json(eve::command_result( + &invocation, + "accepted", + "World owner accepted the command.", + version, + None, + Some(receipt), + )) + .into_response() + } + Err(error) => { + let state_name = if matches!(error, RuntimeCommandError::OutcomeUnknown(_)) { + "unknown" + } else { + "denied" + }; + Json(eve::command_result( + &invocation, + state_name, + error.to_string(), + current_world(state) + .await + .ok() + .map(|snapshot| eve::surface_version(snapshot.as_ref())), + None, + None, + )) + .into_response() + } + } +} + +async fn dispatch_controller( + state: &AppState, + principal: &VerifiedPrincipalEvidence, + invocation: EveCommandInvocation, +) -> Response { + let admitted = admit_controller_command(state, principal, &invocation).await; + let (command_id, opportunity) = match admitted { + Ok(admitted) => admitted, + Err(error) => { + return Json(eve::command_result( + &invocation, + "denied", + error.to_string(), + current_world(state) + .await + .ok() + .map(|snapshot| eve::surface_version(snapshot.as_ref())), + None, + None, + )) + .into_response(); + } + }; + + // Keep the sole runner borrowed from its availability slot for the full + // turn. Quarantine therefore has a clean edge: no second runner can cross + // another provider boundary after this one loses its local invariant. + let mut controller_slot = state.controllers.lock().await; + let Some(controller) = controller_slot.as_ref() else { + return Json(eve::command_result( + &invocation, + "unknown", + "Controller cognition is unavailable; no world outcome is claimed.", + current_world(state) + .await + .ok() + .map(|snapshot| eve::surface_version(snapshot.as_ref())), + None, + None, + )) + .into_response(); + }; + let result = match opportunity.controller_mode { + crate::world::ControllerMode::NarrativePersona => controller + .run_narrative(command_id, &opportunity) + .await + .map(controller_narrative_result), + crate::world::ControllerMode::OperationalAgent => controller + .run_operational(command_id, &opportunity) + .await + .map(controller_operational_result), + crate::world::ControllerMode::Human => unreachable!("human opportunity was not admitted"), + }; + let quarantine = match &result { + Ok(ControllerHttpResult::Pending { quarantine, .. }) => *quarantine, + Ok(ControllerHttpResult::Completed { .. }) => false, + Err(error) => error.requires_quarantine(), + }; + if quarantine { + tracing::error!("controller cognition quarantined after losing its local invariant"); + controller_slot.take(); + } + drop(controller_slot); + + match result { + Ok(ControllerHttpResult::Completed { + message, + receipt, + world_changed, + }) => { + let version = if world_changed { + match publish_projection(state).await { + Ok(version) => Some(version), + Err(error) => { + tracing::error!(%error, "world revision could not be read after controller commit"); + current_world(state) + .await + .ok() + .map(|snapshot| eve::surface_version(snapshot.as_ref())) + } + } + } else { + current_world(state) + .await + .ok() + .map(|snapshot| eve::surface_version(snapshot.as_ref())) + }; + Json(eve::command_result( + &invocation, + "accepted", + message, + version, + None, + Some(receipt), + )) + .into_response() + } + Ok(ControllerHttpResult::Pending { + state_name, + message, + receipt, + .. + }) => Json(eve::command_result( + &invocation, + state_name, + message, + current_world(state) + .await + .ok() + .map(|snapshot| eve::surface_version(snapshot.as_ref())), + None, + Some(receipt), + )) + .into_response(), + Err(error) => { + let state_name = controller_error_disposition(&error); + Json(eve::command_result( + &invocation, + state_name, + error.to_string(), + current_world(state) + .await + .ok() + .map(|snapshot| eve::surface_version(snapshot.as_ref())), + None, + None, + )) + .into_response() + } + } +} + +async fn admit_controller_command( + state: &AppState, + principal: &VerifiedPrincipalEvidence, + invocation: &EveCommandInvocation, +) -> Result<(CommandId, DecisionOpportunity), RuntimeCommandError> { + let command_id = CommandId::parse_uuid( + invocation + .operation + .idempotency_key + .as_deref() + .unwrap_or(""), + )?; + let payload: ControllerActPayload = serde_json::from_value(invocation.payload.clone()) + .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; + if payload.opportunity.controller_mode == crate::world::ControllerMode::Human { + return Err(RuntimeCommandError::Payload( + "human decisions cannot enter through the controller runner".into(), + )); + } + let source_version = invocation + .operation + .route_hint + .source_version + .ok_or_else(|| RuntimeCommandError::Payload("source version is required".into()))?; + let opportunity_version = + payload.opportunity.revision.checked_add(1).ok_or_else(|| { + RuntimeCommandError::Payload("opportunity revision overflowed".into()) + })?; + if source_version != opportunity_version { + return Err(RuntimeCommandError::Payload( + "opportunity and surface version disagree".into(), + )); + } + let snapshot = current_world(state) + .await + .map_err(|error| RuntimeCommandError::Payload(error.to_string()))? + .ok_or_else(|| RuntimeCommandError::Payload("world has not been created".into()))?; + if snapshot.owner != PrincipalId::new(principal.account_subject_hash()) { + return Err(RuntimeCommandError::Payload( + "only the world owner may ask a controller to act".into(), + )); + } + if payload.opportunity.world_id != snapshot.world_id { + return Err(RuntimeCommandError::Payload( + "controller opportunity belongs to another world".into(), + )); + } + Ok((command_id, payload.opportunity)) +} + +enum ControllerHttpResult { + Completed { + message: &'static str, + receipt: Value, + world_changed: bool, + }, + Pending { + state_name: &'static str, + message: &'static str, + receipt: Value, + quarantine: bool, + }, +} + +fn controller_narrative_result(run: NarrativeRun) -> ControllerHttpResult { + match run { + NarrativeRun::Completed(decision) => { + let (turn, capture, disposition) = decision.into_parts(); + let (submission, world_changed) = controller_submission(disposition); + ControllerHttpResult::Completed { + message: "Narrative Persona completed its decision.", + receipt: json!({ + "kind":"narrative_persona", + "personaProse":turn.source_prose(), + "personaSourceDigest":turn.source_digest(), + "personaReceiptDigest":turn.receipt_digest(), + "interpretation":{ + "proposal":capture.proposal.as_ref().map(|source| json!({ + "startByte":source.start_byte, + "endByte":source.end_byte, + })), + "gaps":capture.gaps.iter().map(|gap| json!({ + "kind":gap.kind, + "startByte":gap.source.start_byte, + "endByte":gap.source.end_byte, + "detail":gap.detail, + })).collect::>(), + "finalization":capture.finalization, + "inferenceReceipts":capture.inference_receipts, + }, + "submission":submission, + }), + world_changed, + } + } + NarrativeRun::Pending(pending) => { + controller_pending_result(pending.mode(), pending.reason(), pending.persona_prose()) + } + } +} + +fn controller_operational_result(run: OperationalRun) -> ControllerHttpResult { + match run { + OperationalRun::Completed(decision) => { + let (capture, disposition) = decision.into_parts(); + let (submission, world_changed) = controller_submission(disposition); + ControllerHttpResult::Completed { + message: "Operational agent completed its decision.", + receipt: json!({ + "kind":"operational_agent", + "proposal":capture.proposal, + "needs":capture.needs, + "inferenceReceipts":capture.inference_receipts, + "submission":submission, + }), + world_changed, + } + } + OperationalRun::Pending(pending) => { + controller_pending_result(pending.mode(), pending.reason(), None) + } + } +} + +fn controller_pending_result( + mode: crate::world::ControllerMode, + reason: ControllerPendingReason, + persona_prose: Option<&str>, +) -> ControllerHttpResult { + let (state_name, message, quarantine) = match reason { + ControllerPendingReason::InferenceRetryable => ( + "pending", + "The exact controller inference remains available for connector replay.", + false, + ), + ControllerPendingReason::InferenceRecoveryRequired => ( + "unknown", + "The connector cannot establish an exact outcome for this inference.", + false, + ), + ControllerPendingReason::WorldUnavailable => ( + "unknown", + "The world owner is unavailable; no controller outcome is claimed.", + false, + ), + ControllerPendingReason::WorldOutcomeUnknown => ( + "unknown", + "World commit custody is uncertain; no controller outcome is claimed.", + false, + ), + ControllerPendingReason::StoreReopenRequired => ( + "unknown", + "Controller work-store custody is uncertain; controller cognition has been quarantined.", + true, + ), + }; + ControllerHttpResult::Pending { + state_name, + message, + receipt: json!({ + "kind":"controller_pending", + "mode":mode, + "reason":format!("{reason:?}"), + "personaProse":persona_prose, + }), + quarantine, + } +} + +fn controller_submission(disposition: SubmissionDisposition) -> (Value, bool) { + match disposition { + SubmissionDisposition::NoProposal(receipt) => { + let changed = matches!(&receipt, SubmitReceipt::Applied(_)); + ( + json!({ + "kind":"no_proposal", + "commit":submit_receipt(receipt), + }), + changed, + ) + } + SubmissionDisposition::Completed(receipt) => { + let changed = matches!(&receipt, SubmitReceipt::Applied(_)); + (submit_receipt(receipt), changed) + } + SubmissionDisposition::PreviouslyConfirmed(confirmation) => ( + json!({ + "kind":"previously_confirmed", + "commandId":confirmation.command_id, + "revision":confirmation.resulting_revision, + "stateDigest":confirmation.resulting_state_digest, + "commitDigest":confirmation.commit_digest, + }), + false, + ), + } +} + +fn controller_error_disposition(error: &ControllerError) -> &'static str { + match error { + ControllerError::WorkPersistence(_) | ControllerError::Serialization(_) => "unknown", + ControllerError::Inference { .. } | ControllerError::ProviderContract { .. } => "unknown", + ControllerError::Snapshot( + MailboxError::Unavailable | MailboxError::OutcomeUnknown { .. }, + ) => "unknown", + ControllerError::Snapshot(_) + | ControllerError::NoOpportunity { .. } + | ControllerError::AmbiguousOpportunity + | ControllerError::OpportunityMismatch + | ControllerError::SpeakUnavailable + | ControllerError::CommandMismatch + | ControllerError::MissingControllerWork + | ControllerError::World(_) => "denied", + } +} + +#[derive(Debug, thiserror::Error)] +enum RuntimeCommandError { + #[error("invalid command payload: {0}")] + Payload(String), + #[error("world command outcome is unknown after durable submission: {0}")] + OutcomeUnknown(String), + #[error(transparent)] + Mailbox(#[from] MailboxError), + #[error(transparent)] + Kernel(#[from] KernelError), +} + +async fn execute_world( + state: &AppState, + verified_principal: &VerifiedPrincipalEvidence, + invocation: &EveCommandInvocation, +) -> Result { + let command_id = CommandId::parse_uuid( + invocation + .operation + .idempotency_key + .as_deref() + .unwrap_or(""), + )?; + if invocation.operation.operation_id == "world.create" { + let payload: CreatePayload = serde_json::from_value(invocation.payload.clone()) + .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; + let receipt = state + .world + .create( + CreateWorldIntent { + id: command_id, + title: payload.title, + human_subject_label: payload.subject_label, + narrative_persona_label: payload.narrative_persona_label, + operational_agent_label: payload.operational_agent_label, + }, + verified_principal, + ) + .await + .map_err(map_mailbox)?; + return Ok(json!({ + "kind":"created", + "commandId":serde_json::to_value(receipt.command_id).unwrap_or(Value::Null), + "worldId":serde_json::to_value(receipt.world_id).unwrap_or(Value::Null), + "stateDigest":receipt.resulting_state_digest, + "commitDigest":receipt.commit_digest + })); + } + + let snapshot = current_world(state) + .await + .map_err(|error| RuntimeCommandError::Payload(error.to_string()))? + .ok_or_else(|| RuntimeCommandError::Payload("world has not been created".into()))?; + let source_version = invocation + .operation + .route_hint + .source_version + .ok_or_else(|| RuntimeCommandError::Payload("source version is required".into()))?; + let expected_revision = source_version.checked_sub(1).ok_or_else(|| { + RuntimeCommandError::Payload("source version does not name a world revision".into()) + })?; + let body = match invocation.operation.operation_id.as_str() { + "world.approve" => { + serde_json::from_value::(invocation.payload.clone()) + .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; + CommandBody::ApproveDraft + } + "world.activate" => { + serde_json::from_value::(invocation.payload.clone()) + .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; + CommandBody::ActivateWorld + } + "world.speak" => { + let payload: SpeakPayload = serde_json::from_value(invocation.payload.clone()) + .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; + if payload.opportunity.revision != expected_revision { + return Err(RuntimeCommandError::Payload( + "opportunity and surface version disagree".into(), + )); + } + CommandBody::ExerciseDecision { + opportunity: payload.opportunity, + invocation: DecisionInvocation { + affordance_id: payload.affordance_id, + action: DecisionAction::Speak { text: payload.text }, + }, + } + } + operation => { + return Err(RuntimeCommandError::Payload(format!( + "unknown world operation {operation}" + ))); + } + }; + let receipt = state + .world + .submit_principal( + PrincipalCommandIntent { + id: command_id, + world_id: snapshot.world_id, + expected_revision, + body, + }, + verified_principal, + ) + .await + .map_err(map_mailbox)?; + Ok(submit_receipt(receipt)) +} + +fn submit_receipt(receipt: SubmitReceipt) -> Value { + match receipt { + SubmitReceipt::Applied(receipt) => json!({ + "kind":"applied", + "commandId":serde_json::to_value(receipt.command_id).unwrap_or(Value::Null), + "revision":receipt.resulting_revision, + "stateDigest":receipt.resulting_state_digest, + "commitDigest":receipt.commit_digest + }), + SubmitReceipt::AlreadyApplied(receipt) => json!({ + "kind":"already_applied", + "commandId":serde_json::to_value(receipt.command_id).unwrap_or(Value::Null), + "revision":receipt.resulting_revision, + "stateDigest":receipt.resulting_state_digest, + "commitDigest":receipt.commit_digest + }), + } +} + +fn map_mailbox(error: MailboxError) -> RuntimeCommandError { + match error { + MailboxError::OutcomeUnknown { command_id } => { + RuntimeCommandError::OutcomeUnknown(format!("{command_id:?}")) + } + other => RuntimeCommandError::Mailbox(other), + } +} + +async fn current_world(state: &AppState) -> anyhow::Result> { + match state.world.snapshot().await { + Ok(snapshot) => Ok(Some(snapshot)), + Err(MailboxError::Kernel(KernelError::WorldNotCreated)) => Ok(None), + Err(error) => Err(error.into()), + } +} + +async fn publish_projection(state: &AppState) -> anyhow::Result { + let snapshot = current_world(state).await?; + let version = eve::surface_version(snapshot.as_ref()); + let _ = state.revisions.send(version); + if let Some(mesh) = state.mesh.clone() { + let _projection = tokio::task::spawn_blocking(move || { + if let Err(error) = mesh.publish(snapshot.as_ref()) { + tracing::warn!(%error, "derived CultMesh projection update failed"); + } + }); + } + Ok(version) +} + +async fn refresh_mesh_projection(state: &AppState) -> anyhow::Result { + let snapshot = current_world(state).await?; + let version = eve::surface_version(snapshot.as_ref()); + let Some(mesh) = state.mesh.clone() else { + bail!("CultMesh projection is unavailable"); + }; + tokio::task::spawn_blocking(move || mesh.publish(snapshot.as_ref())) + .await + .context("CultMesh projection worker panicked")??; + Ok(version) +} + +async fn canonical_readiness(state: &AppState) -> anyhow::Result { + let snapshot = current_world(state) + .await + .context("world owner is not ready")?; + state + .sessions + .lock() + .await + .validate_custody() + .context("app-session owner is not ready")?; + let expected_version = eve::surface_version(snapshot.as_ref()); + let expected_world_state = eve::world_state(snapshot.as_ref()); + Ok(json!({ + "schema":"ghostlight.service_health.v2", + "status":"ok", + "worldState":expected_world_state, + "surfaceVersion":expected_version, + "updatedAtUtc":Utc::now().to_rfc3339(), + "runtime":state.mesh_identity.runtime_id, + "commit":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development"), + })) +} + +async fn runtime_readiness(state: &AppState) -> anyhow::Result { + let mut health = canonical_readiness(state).await?; + let expected_version = health["surfaceVersion"].as_u64().unwrap_or_default(); + let expected_world_state = health["worldState"].as_str().unwrap_or("unknown"); + let projection_status = match &state.mesh { + Some(mesh) => match mesh.health() { + Ok(health) + if health.get("status").and_then(Value::as_str) == Some("ok") + && health.get("surfaceVersion").and_then(Value::as_u64) + == Some(expected_version) + && health.get("worldState").and_then(Value::as_str) + == Some(expected_world_state) => + { + "ok" + } + Ok(_) | Err(_) => "degraded", + }, + None => "unavailable", + }; + let controller_status = match state.controllers.try_lock() { + Ok(slot) => match slot.as_ref() { + Some(controller) => { + match tokio::time::timeout(Duration::from_millis(100), controller.custody_probe()) + .await + { + Ok(Ok(ControllerWorkCustody::Owned { .. })) => "ok", + Ok(Ok(ControllerWorkCustody::Uncertain { .. })) | Ok(Err(_)) => "degraded", + Err(_) => "busy", + } + } + None => "unavailable", + }, + Err(_) => "active", + }; + health["projectionStatus"] = Value::String(projection_status.into()); + health["controllerStatus"] = Value::String(controller_status.into()); + Ok(health) +} + +async fn maintain_mesh_projection(state: AppState) { + let mut interval = tokio::time::interval(Duration::from_secs(120)); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + // Startup publishes once before serving. Do not wake clients with a duplicate + // revision event; this loop only renews derived CultMesh freshness. + interval.tick().await; + loop { + interval.tick().await; + if let Err(error) = refresh_mesh_projection(&state).await { + tracing::warn!(%error, "derived CultMesh projection remains degraded"); + } + } +} + +async fn revision_events(State(state): State) -> impl IntoResponse { + let mut revisions = state.revisions.subscribe(); + let stream = async_stream::stream! { + loop { + match revisions.recv().await { + Ok(version) => yield Ok::(SseEvent::default().event("revision").data(version.to_string())), + Err(broadcast::error::RecvError::Lagged(_)) => continue, + Err(broadcast::error::RecvError::Closed) => break, + } + } + }; + Sse::new(stream).keep_alive(KeepAlive::default()) +} + +async fn authenticated_principal( + headers: &HeaderMap, + state: &AppState, +) -> Option { + let raw = cookie_value(headers)?; + match state + .sessions + .lock() + .await + .account_for_cookie(raw, Utc::now()) + { + Ok(account) => account, + Err(error) => { + signal_fatal(state, "app-session custody", &error); + None + } + } +} + +fn signal_fatal(state: &AppState, organ: &str, error: &impl std::fmt::Display) { + let detail = format!("{organ}: {error}"); + tracing::error!(%detail, "runtime owner can no longer uphold its invariant"); + let _ = state.fatal.send(detail); +} + +fn cookie_value(headers: &HeaderMap) -> Option<&str> { + headers + .get(header::COOKIE)? + .to_str() + .ok()? + .split(';') + .map(str::trim) + .find_map(|cookie| cookie.strip_prefix(&format!("{COOKIE_NAME}="))) +} + +fn session_cookie(raw: &str, expires_at: DateTime, now: DateTime) -> HeaderValue { + HeaderValue::from_str(&format!( + "{COOKIE_NAME}={raw}; Max-Age={}; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/", + (expires_at - now).num_seconds().max(0) + )) + .expect("generated session cookie must be valid") +} + +async fn maintain_session_refresh(state: AppState) -> anyhow::Result<()> { + let mut interval = tokio::time::interval(Duration::from_secs(60)); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + interval.tick().await; + let candidates = state + .sessions + .lock() + .await + .sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2)) + .context("app-session refresh scan lost custody")?; + for candidate in candidates { + let idempotency = format!( + "refresh:{}:{}", + candidate.heimdall_session_id, candidate.access_revision + ); + let completion = match state + .heimdall + .refresh(&candidate.refresh_claim, &idempotency) + .await + { + Ok(value) => value, + Err(error) => { + tracing::warn!(%error, "Heimdall refresh transport unavailable"); + continue; + } + }; + let verified = match state.heimdall.verify_refresh(completion).await { + Ok(value) => value, + Err(error) => { + tracing::warn!(%error, "Heimdall refresh receipt was invalid"); + let mut sessions = state.sessions.lock().await; + if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) { + return Err(revoke_error) + .context("invalid Heimdall refresh could not revoke local custody"); + } + continue; + } + }; + if verified.heimdall_session_id() != candidate.heimdall_session_id + || crate::app_session::secret_hash(&format!( + "heimdall-account:{}", + verified.account_id() + )) != candidate.account_subject_hash + { + tracing::warn!("Heimdall refresh changed local session custody"); + let mut sessions = state.sessions.lock().await; + if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) { + return Err(revoke_error) + .context("changed Heimdall custody could not revoke local session"); + } + continue; + } + let mut sessions = state.sessions.lock().await; + if let Err(error) = + sessions.apply_refresh(&candidate.cookie_hash, candidate.access_revision, verified) + { + if sessions.is_healthy() { + tracing::warn!(%error, "local app session rejected Heimdall refresh"); + } else { + return Err(error).context("app-session refresh commit lost custody"); + } + } + } + } +} + +async fn initialize_production_admission( + identity: &MeshRuntimeIdentity, +) -> anyhow::Result> { + let endpoint = match std::env::var("GHOSTLIGHT_IDUNN_RUDP") { + Ok(endpoint) => endpoint, + Err(_) => { + #[cfg(target_os = "linux")] + bail!("GHOSTLIGHT_IDUNN_RUDP is mandatory for the Linux Ghostlight runtime"); + #[cfg(not(target_os = "linux"))] + return Ok(None); + } + }; + let identity_store = std::env::var_os("GHOSTLIGHT_IDUNN_HEALTH_IDENTITY") + .map(PathBuf::from) + .context("GHOSTLIGHT_IDUNN_HEALTH_IDENTITY is required with GHOSTLIGHT_IDUNN_RUDP")?; + let daemon_id = + std::env::var("GHOSTLIGHT_IDUNN_DAEMON").unwrap_or_else(|_| "yggdrasil-ghostlight".into()); + if daemon_id != "yggdrasil-ghostlight" { + bail!("signed Ghostlight health daemon id is not the canonical Idunn identity"); + } + let release = release_health_binding()?; + let activation = active_activation_binding(&release)?; + let mut publisher = IdunnHealthPublisher::open( + endpoint.parse()?, + daemon_id, + identity.runtime_id.clone(), + std::env::var("GHOSTLIGHT_IDUNN_HEALTH_CONTRACT") + .unwrap_or_else(|_| GHOSTLIGHT_IDUNN_HEALTH_CONTRACT.into()), + identity_store, + release.clone(), + activation.clone(), + )?; + let startup = publisher + .publish("warming", "traffic-admission-pending") + .context("publishing initial warming Idunn health")?; + let traffic = + GhostlightTrafficAdmissionGate::from_environment(&release, &activation, &startup)?; + traffic.wait_until_granted(Duration::from_secs(120)).await?; + Ok(Some(ProductionAdmission { + traffic: Arc::new(traffic), + health: publisher, + })) +} + +fn release_health_binding() -> anyhow::Result { + let executable = std::env::current_exe().context("locating the active Ghostlight binary")?; + let release_root = executable + .parent() + .context("active Ghostlight binary has no release directory")?; + let witness_path = release_root.join("DEPLOYMENT"); + let witness = std::fs::read(&witness_path) + .with_context(|| format!("reading sealed release witness {}", witness_path.display()))?; + let witness_text = std::str::from_utf8(&witness).context("release witness is not UTF-8")?; + let source_commit = exact_release_field(witness_text, "source_commit")?.to_owned(); + let compiled_commit = option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development"); + if source_commit != compiled_commit || !is_lower_hex(&source_commit, 40) { + bail!("release witness does not bind the compiled Ghostlight source commit"); + } + let expected_binary_sha = exact_release_field(witness_text, "binary_sha256")?; + let binary_sha = hex(&Sha256::digest( + std::fs::read(&executable).context("reading the active Ghostlight binary")?, + )); + if expected_binary_sha != binary_sha { + bail!("release witness does not bind the active Ghostlight executable"); + } + let deployment_id = std::env::var("GHOSTLIGHT_IDUNN_DEPLOYMENT_REQUEST_ID") + .context("GHOSTLIGHT_IDUNN_DEPLOYMENT_REQUEST_ID is required for signed health")?; + if deployment_id.len() > 256 + || !deployment_id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')) + { + bail!("Idunn deployment request identity is malformed"); + } + Ok(IdunnReleaseBinding { + release_id: source_commit.clone(), + release_witness_sha256: format!("sha256-{}", hex(&Sha256::digest(&witness))), + source_commit, + deployment_id, + }) +} + +fn exact_release_field<'a>(witness: &'a str, name: &str) -> anyhow::Result<&'a str> { + let prefix = format!("{name}="); + let mut values = witness + .lines() + .filter_map(|line| line.strip_prefix(&prefix)); + let value = values + .next() + .with_context(|| format!("release witness has no {name}"))?; + if value.is_empty() + || value.trim() != value + || value.chars().any(char::is_control) + || values.next().is_some() + { + bail!("release witness has an invalid or duplicate {name}"); + } + Ok(value) +} + +fn is_lower_hex(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) +} + +async fn maintain_runtime_health( + publisher: Option, + state: AppState, +) -> anyhow::Result<()> { + let mut publisher = publisher; + let mut interval = tokio::time::interval(Duration::from_secs(10)); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + interval.tick().await; + canonical_readiness(&state) + .await + .context("runtime is not ready for signed health")?; + if let Some(mut owned) = publisher.take() { + let published = tokio::task::spawn_blocking(move || { + let result = owned.publish("active", "world-owner-serving"); + (owned, result) + }) + .await; + let Ok((returned, result)) = published else { + tracing::warn!("signed Idunn health worker panicked; publication is disabled"); + continue; + }; + publisher = Some(returned); + if let Err(error) = result { + tracing::warn!(%error, "signed Idunn health publication failed"); + } + } + } +} + +async fn maintain_traffic_admission( + admission: Arc, +) -> anyhow::Result<()> { + let mut interval = tokio::time::interval(Duration::from_millis(100)); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + interval.tick().await; + admission + .require_current() + .context("root traffic admission was revoked or substituted")?; + } +} + +fn require_current_traffic_admission( + admission: Option<&RequestTrafficAdmission>, + phase: &str, +) -> anyhow::Result<()> { + let Some(admission) = admission else { + return Ok(()); + }; + admission + .traffic + .require_current() + .with_context(|| format!("root traffic admission changed {phase}")) +} + +fn require_no_runtime_custody_failure( + failures: &mut mpsc::UnboundedReceiver, +) -> anyhow::Result<()> { + match failures.try_recv() { + Ok(detail) => bail!("runtime custody failed before serving: {detail}"), + Err(mpsc::error::TryRecvError::Empty) => Ok(()), + Err(mpsc::error::TryRecvError::Disconnected) => { + bail!("runtime custody signal channel closed before serving") + } + } +} + +fn default_runtime_root() -> PathBuf { + #[cfg(windows)] + { + PathBuf::from(r"F:\GameCult\GhostlightDungeon") + } + #[cfg(not(windows))] + { + PathBuf::from("/var/lib/gamecult/ghostlight-dungeon") + } +} + +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 +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::{body::Body, http::Request}; + use tower::ServiceExt; + + fn controller_commit() -> crate::world::CommitReceipt { + crate::world::CommitReceipt { + command_id: CommandId::new(), + resulting_revision: 9, + resulting_state_digest: "sha256:declined-state".into(), + commit_digest: "sha256:decline-commit".into(), + } + } + + #[test] + fn no_proposal_projection_carries_the_canonical_world_commit() { + let commit = controller_commit(); + let (applied, changed) = controller_submission(SubmissionDisposition::NoProposal( + SubmitReceipt::Applied(commit.clone()), + )); + assert!(changed); + assert_eq!(applied["kind"], "no_proposal"); + assert_eq!(applied["commit"]["kind"], "applied"); + assert_eq!(applied["commit"]["revision"], 9); + + let (replayed, changed) = controller_submission(SubmissionDisposition::NoProposal( + SubmitReceipt::AlreadyApplied(commit), + )); + assert!(!changed); + assert_eq!(replayed["kind"], "no_proposal"); + assert_eq!(replayed["commit"]["kind"], "already_applied"); + } + + struct Fixture { + _directory: tempfile::TempDir, + state: AppState, + cookie: String, + } + + async fn fixture() -> Fixture { + let directory = tempfile::tempdir().unwrap(); + let key = directory.path().join("session.key"); + std::fs::write(&key, [17_u8; 32]).unwrap(); + let mut sessions = + AppSessionOwner::open(directory.path().join("sessions.cc"), &key).unwrap(); + let cookie = sessions + .create_session(heimdall::VerifiedSessionAdmission::fixture( + "operator-account", + "heimdall-session", + 1, + Utc::now() + chrono::Duration::hours(1), + Utc::now() + chrono::Duration::days(1), + "fixture-refresh", + )) + .unwrap(); + let (world, _owner) = WorldMailbox::open(directory.path().join("world.cc")).unwrap(); + let controller_key = directory.path().join("controller.key"); + std::fs::write(&controller_key, "runtime-test-controller-key").unwrap(); + let controllers = ControllerRunner::open( + world.clone(), + "127.0.0.1:9".parse().unwrap(), + &controller_key, + "ghostlight-runtime-test", + directory.path().join("controller-work.cc"), + ControllerModels { + projector: "gpt-5.6-luna".into(), + persona: "gpt-5.6-sol".into(), + interpreter: "gpt-5.6-terra".into(), + operational_agent: "gpt-5.6-terra".into(), + }, + ) + .unwrap(); + let mesh = MeshPublisher::open( + directory.path().join("mesh.cc"), + None, + MeshRuntimeIdentity::default(), + ) + .unwrap(); + let mesh_identity = MeshRuntimeIdentity::default(); + let (revisions, _) = broadcast::channel(8); + let (fatal, _fatal_events) = mpsc::unbounded_channel(); + let state = AppState { + world, + controllers: Arc::new(Mutex::new(Some(controllers))), + sessions: Arc::new(Mutex::new(sessions)), + heimdall: Arc::new(HeimdallClient::fixture()), + mesh: Some(mesh), + mesh_identity, + revisions, + fatal, + traffic: None, + }; + publish_projection(&state).await.unwrap(); + Fixture { + _directory: directory, + state, + cookie, + } + } + + fn invocation(operation: &str, schema: &str, version: u64, payload: Value, id: &str) -> Value { + json!({ + "schema":"gamecult.eve.command_invocation.v1", + "providerId":mesh::PROVIDER_ID, + "surfaceId":mesh::SURFACE_ID, + "operation":{ + "operationId":operation, + "schemaId":schema, + "idempotencyKey":id, + "routeHint":{"sourceVersion":version,"transport":"https-json"} + }, + "payload":payload, + "issuedAt":Utc::now().to_rfc3339(), + "clientId":"runtime-test", + "commandBoundary":mesh::COMMAND_BOUNDARY, + "receiptSchema":mesh::COMMAND_RESULT_SCHEMA + }) + } + + async fn post(state: &AppState, cookie: &str, body: Value) -> Value { + let response = api_router(state.clone()) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/eve/commands") + .header(header::CONTENT_TYPE, "application/json") + .header(header::COOKIE, format!("{COOKIE_NAME}={cookie}")) + .body(Body::from(serde_json::to_vec(&body).unwrap())) + .unwrap(), + ) + .await + .unwrap(); + let bytes = axum::body::to_bytes(response.into_body(), 1024 * 1024) + .await + .unwrap(); + serde_json::from_slice(&bytes).unwrap() + } + + #[tokio::test] + async fn http_eve_journey_uses_one_world_owner() { + let fixture = fixture().await; + let created = post( + &fixture.state, + &fixture.cookie, + invocation( + "world.create", + "ghostlight.world_create.v1", + 0, + json!({"title":"Cutover World","subject_label":"Operator"}), + &uuid::Uuid::new_v4().to_string(), + ), + ) + .await; + assert_eq!(created["state"], "accepted"); + assert_eq!(created["sourceVersion"], 1); + + let approved = post( + &fixture.state, + &fixture.cookie, + invocation( + "world.approve", + "ghostlight.world_approve.v0", + 1, + json!({}), + &uuid::Uuid::new_v4().to_string(), + ), + ) + .await; + assert_eq!(approved["sourceVersion"], 2); + let activated = post( + &fixture.state, + &fixture.cookie, + invocation( + "world.activate", + "ghostlight.world_activate.v0", + 2, + json!({}), + &uuid::Uuid::new_v4().to_string(), + ), + ) + .await; + assert_eq!(activated["sourceVersion"], 3); + + let world = current_world(&fixture.state).await.unwrap().unwrap(); + let opportunity = world.opportunities[0].clone(); + let affordance = world.subjects[0].affordances[&AffordanceKind::Speak]; + let spoken = post( + &fixture.state, + &fixture.cookie, + invocation( + "world.speak", + "ghostlight.world_speak.v0", + 3, + json!({ + "text":"The new owner speaks.", + "opportunity":opportunity, + "affordance_id":affordance + }), + &uuid::Uuid::new_v4().to_string(), + ), + ) + .await; + assert_eq!(spoken["sourceVersion"], 4); + let world = current_world(&fixture.state).await.unwrap().unwrap(); + assert_eq!(world.events.len(), 1); + } + + #[tokio::test] + async fn exact_stale_retry_returns_journal_receipt_without_app_cache() { + let fixture = fixture().await; + let id = uuid::Uuid::new_v4().to_string(); + let command = invocation( + "world.create", + "ghostlight.world_create.v1", + 0, + json!({"title":"Retry World","subject_label":"Operator"}), + &id, + ); + let first = post(&fixture.state, &fixture.cookie, command.clone()).await; + let second = post(&fixture.state, &fixture.cookie, command).await; + assert_eq!( + first["receipt"]["commitDigest"], + second["receipt"]["commitDigest"] + ); + assert_eq!( + current_world(&fixture.state) + .await + .unwrap() + .unwrap() + .revision, + 0 + ); + } + + #[tokio::test] + async fn logout_retry_clears_a_revoked_cookie_without_reauthentication() { + let fixture = fixture().await; + let id = uuid::Uuid::new_v4().to_string(); + let command = invocation( + "app.auth.logout", + "ghostlight.app_logout.v2", + 0, + json!({}), + &id, + ); + let first = post(&fixture.state, &fixture.cookie, command.clone()).await; + let retry = post(&fixture.state, &fixture.cookie, command).await; + assert_eq!(first["state"], "accepted"); + assert_eq!(retry["state"], "accepted"); + assert_eq!(retry["pluginPayload"]["payload"]["status"], "anonymous"); + } + + #[tokio::test] + async fn removed_legacy_operation_is_denied_before_dispatch() { + let fixture = fixture().await; + let result = post( + &fixture.state, + &fixture.cookie, + invocation( + "session_zero.begin", + "ghostlight.session_zero_begin.v1", + 0, + json!({}), + &uuid::Uuid::new_v4().to_string(), + ), + ) + .await; + assert_eq!(result["state"], "denied"); + assert!( + result["message"] + .as_str() + .unwrap() + .contains("not advertised") + ); + } + + #[tokio::test] + async fn authentication_commands_reject_ignored_authority_payloads() { + let fixture = fixture().await; + let result = post( + &fixture.state, + &fixture.cookie, + invocation( + "heimdall.auth.begin", + "heimdall.auth_begin_command.v1", + 0, + json!({"caller":{"principal":"legacy-owner"}}), + &uuid::Uuid::new_v4().to_string(), + ), + ) + .await; + assert_eq!(result["state"], "denied"); + assert!( + result["message"] + .as_str() + .unwrap() + .contains("invalid command payload") + ); + } +} diff --git a/crates/ghostlight-dungeon/src/scheduler.rs b/crates/ghostlight-dungeon/src/scheduler.rs deleted file mode 100644 index 26980d5..0000000 --- a/crates/ghostlight-dungeon/src/scheduler.rs +++ /dev/null @@ -1,3336 +0,0 @@ -use crate::{ - domain::{ - AgencyAxis, AgencySubjectKind, Campaign, GestaltIndividuation, GestaltMemberDelta, - ResolutionDemand, ResolutionWaveCommit, SimulationCell, StrategicGestaltIndividuation, - }, - follow_through::{ - NEMESIS_STAGE, assignments_for_cell, causal_anchor_summary, causal_follow_through_snapshot, - nemesis_admission_binding, propose_causal_follow_through, validate_causal_follow_through, - }, - model::{ - MODEL_FAST, ModelPort, ModelStageOutput, ModelStageReceipt, ModelStageRequest, - run_validated_stage, - }, - outcome::{ - StrategicOutcomeResolutionFailure, activity_outcome_binding, - resolve_activity_outcomes_with_causal_assignments, - }, - persona::{ - CellActivityTargetSlice, CellCausalFollowThroughSlice, CellConstituentSlice, - CellMemberSlice, CellMigrationDestinationSlice, CellPerceivedEventSlice, - CellPipelineFailure, CellProjectionEngine, ExecutionPermit, PermittedCellSlice, - }, - resolution::{ - cell_action_digest, cell_action_limit, default_demand, plan_cover, plan_receipt, - select_resolution_wave, validate_and_resolve_wave, validate_cover, validate_demand, - }, - session_zero::{AggregatedBoundary, CampaignContract}, -}; -use anyhow::{Context, Result, anyhow}; -use chrono::{DateTime, Utc}; -use schemars::{JsonSchema, schema_for}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; -use std::sync::Arc; - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -struct DemandProjection { - axis_weights: DemandAxisWeights, - focal_subject_ids: BTreeSet, - rationale: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -struct DemandAxisWeights { - geography: f32, - ideology: f32, - authority: f32, - economy_role: f32, - species_body: f32, - information: f32, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -struct StrategicPersonDraft { - action_digest: String, - gestalt_id: String, - member_id: String, - /// Stable personal self-identifier suitable to the setting, never a role, - /// office, condition, manifest category, or descriptive placeholder. - name: String, - goals: Vec, - obligations: BTreeSet, - relationships: BTreeMap, - memories: Vec, - rationale: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -struct StrategicPersonSelection { - proposals: Vec, -} - -impl DemandAxisWeights { - fn into_map(self) -> BTreeMap { - BTreeMap::from([ - (AgencyAxis::Geography, self.geography), - (AgencyAxis::Ideology, self.ideology), - (AgencyAxis::Authority, self.authority), - (AgencyAxis::EconomyRole, self.economy_role), - (AgencyAxis::SpeciesBody, self.species_body), - (AgencyAxis::Information, self.information), - ]) - } -} - -#[derive(Clone, Debug, Default, Serialize)] -struct RelationDemandSummary { - edges: u64, - total_strength: u64, - max_strength: u8, -} - -pub struct StrategicResolutionOutput { - pub wave: ResolutionWaveCommit, - pub stages: Vec, - pub private_cell_traces: Vec, - pub aggregate_receipt_hash: String, - pub checkpoint: ResolutionWaveCheckpoint, -} - -#[derive(Clone, Debug, Serialize)] -pub struct PrivateCellTrace { - pub cell_id: String, - pub terminal_pipeline_receipt_hashes: Vec, - pub lived_stream: String, - pub persona_output: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct ResolutionCellTerminalCheckpoint { - cell_id: String, - terminal: crate::persona::CellTerminalBundle, -} - -/// Durable, non-canonical progress for one immutable strategic wave. -/// -/// The scheduler owns this shape because only it can prove that a completed -/// cell terminal belongs to the exact cover and campaign snapshot. Consumers -/// may persist it, but may not merge, edit, or reinterpret its cell outputs. -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ResolutionWaveCheckpoint { - schema: String, - campaign_id: uuid::Uuid, - world_revision: u64, - resolution_epoch: u64, - cover: crate::domain::ResolutionCover, - plan_receipt: crate::domain::ResolutionPlanReceipt, - planning_stage_receipts: Vec, - campaign_contract: Option, - aggregate_boundaries: Vec, - completed_cells: Vec, - failed_cell_ids: BTreeSet, - digest: String, -} - -#[derive(Clone, Debug)] -pub struct ResolutionWavePipelineFailure { - pub pipeline_errors: Vec, - pub stage_receipts: Vec, - pub checkpoint: Option, -} - -impl std::fmt::Display for ResolutionWavePipelineFailure { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - formatter, - "resolution wave rejected after {} pipeline failure(s): {}", - self.pipeline_errors.len(), - self.pipeline_errors.join("; ") - ) - } -} - -impl std::error::Error for ResolutionWavePipelineFailure {} - -#[derive(Debug)] -struct CellPipelineExhaustion { - cell_id: Option, - diagnostic: String, - stage_receipts: Vec, -} - -pub async fn propose_resolution_wave( - model: Arc, - permit: Arc, - campaign: &Campaign, -) -> Result { - propose_resolution_wave_with_policy(model, permit, campaign, None, &[]).await -} - -pub async fn propose_resolution_wave_with_policy( - model: Arc, - permit: Arc, - campaign: &Campaign, - campaign_contract: Option<&CampaignContract>, - aggregate_boundaries: &[AggregatedBoundary], -) -> Result { - let (demand, mut stages) = project_resolution_demand( - model.as_ref(), - campaign, - campaign_contract, - aggregate_boundaries, - ) - .await; - let mut cover = plan_cover(campaign, demand)?; - let follow_through_binding = causal_follow_through_snapshot(campaign, &cover)?; - permit - .require( - "strategic-follow-through", - &follow_through_binding, - NEMESIS_STAGE, - ) - .await?; - let follow_through = propose_causal_follow_through(model.as_ref(), campaign, &cover).await; - match follow_through { - Ok(Some(proposal)) => { - cover.causal_follow_through = proposal.admission.assignments; - stages.extend( - proposal - .receipts - .into_iter() - .map(|receipt| ModelStageOutput { - narrative: String::new(), - structured: None, - receipt, - }), - ); - } - Ok(None) => {} - Err(failure) => { - let mut stage_receipts = stages - .iter() - .map(|stage| stage.receipt.clone()) - .collect::>(); - stage_receipts.extend(failure.receipts); - return Err(anyhow::Error::new(ResolutionWavePipelineFailure { - pipeline_errors: vec![failure.message], - stage_receipts, - checkpoint: None, - })); - } - } - validate_causal_follow_through(campaign, &cover)?; - let checkpoint = seal_resolution_wave_checkpoint(ResolutionWaveCheckpoint { - schema: "ghostlight.resolution_wave_checkpoint.v1".into(), - campaign_id: campaign.id, - world_revision: campaign.revision, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - plan_receipt: plan_receipt(campaign, &cover), - failed_cell_ids: cover.cells.iter().map(|cell| cell.id.clone()).collect(), - cover, - planning_stage_receipts: stages.into_iter().map(|stage| stage.receipt).collect(), - campaign_contract: campaign_contract.cloned(), - aggregate_boundaries: aggregate_boundaries.to_vec(), - completed_cells: Vec::new(), - digest: String::new(), - })?; - resume_resolution_wave_from_checkpoint(model, permit, campaign, checkpoint).await -} - -/// Resume one exact strategic wave from scheduler-owned typed cell terminals. -/// Only cells still named in `failed_cell_ids` may invoke the model again. -pub async fn resume_resolution_wave( - model: Arc, - permit: Arc, - campaign: &Campaign, - checkpoint: ResolutionWaveCheckpoint, -) -> Result { - resume_resolution_wave_from_checkpoint(model, permit, campaign, checkpoint).await -} - -async fn resume_resolution_wave_from_checkpoint( - model: Arc, - permit: Arc, - campaign: &Campaign, - mut checkpoint: ResolutionWaveCheckpoint, -) -> Result { - validate_resolution_wave_checkpoint(campaign, &checkpoint)?; - let cover = checkpoint.cover.clone(); - let receipt = checkpoint.plan_receipt.clone(); - let mut stages = checkpoint - .planning_stage_receipts - .iter() - .cloned() - .map(|receipt| ModelStageOutput { - narrative: String::new(), - structured: None, - receipt, - }) - .collect::>(); - let outcome_model = model.clone(); - let outcome_permit = permit.clone(); - let engine = CellProjectionEngine { - model, - permit, - projector_model: MODEL_FAST.into(), - persona_model: MODEL_FAST.into(), - interpreter_model: MODEL_FAST.into(), - campaign_contract: checkpoint.campaign_contract.clone(), - aggregate_boundaries: checkpoint.aggregate_boundaries.clone(), - }; - let semaphore = Arc::new(tokio::sync::Semaphore::new(usize::from( - campaign.resolution_policy.provider_parallelism.max(1), - ))); - let mut jobs = tokio::task::JoinSet::new(); - for cell in cover - .cells - .iter() - .filter(|cell| checkpoint.failed_cell_ids.contains(&cell.id)) - .cloned() - { - let engine = engine.clone(); - let semaphore = semaphore.clone(); - let slice = cell_slice(campaign, &cover, &cell)?; - jobs.spawn(async move { - let cell_id = cell.id; - let subject_ids = cell.subject_ids; - let Ok(_provider_slot) = semaphore.acquire_owned().await else { - return Err(CellPipelineExhaustion { - cell_id: Some(cell_id), - diagnostic: "provider concurrency gate closed".into(), - stage_receipts: Vec::new(), - }); - }; - let terminal = engine.execute(slice).await.map_err(|error| { - let stage_receipts = error - .downcast_ref::() - .map(|failure| failure.stage_receipts.clone()) - .unwrap_or_default(); - CellPipelineExhaustion { - diagnostic: format!( - "simulation cell {cell_id} subjects {} pipeline failed: {error:#}", - serde_json::to_string(&subject_ids) - .unwrap_or_else(|_| "[unavailable]".into()) - ), - cell_id: Some(cell_id.clone()), - stage_receipts, - } - })?; - Ok::<_, CellPipelineExhaustion>((cell_id, terminal)) - }); - } - let mut terminals = checkpoint - .completed_cells - .iter() - .cloned() - .map(|completed| (completed.cell_id, completed.terminal)) - .collect::>(); - let mut cell_failures = Vec::new(); - while let Some(result) = jobs.join_next().await { - match result { - Ok(Ok(terminal)) => terminals.push(terminal), - Ok(Err(failure)) => cell_failures.push(failure), - Err(error) => cell_failures.push(CellPipelineExhaustion { - cell_id: None, - diagnostic: format!("cell Persona task failed: {error}"), - stage_receipts: Vec::new(), - }), - } - } - if !cell_failures.is_empty() { - let mut stage_receipts = stages - .iter() - .map(|stage| stage.receipt.clone()) - .chain( - terminals - .iter() - .flat_map(|(_, terminal)| terminal.stage_receipts.iter().cloned()), - ) - .collect::>(); - stage_receipts.extend( - cell_failures - .iter() - .flat_map(|failure| failure.stage_receipts.iter().cloned()), - ); - let pipeline_errors = cell_failures - .iter() - .map(|failure| failure.diagnostic.clone()) - .collect(); - let failed_cell_ids = cell_failures - .iter() - .filter_map(|failure| failure.cell_id.clone()) - .collect::>(); - terminals.sort_by(|left, right| left.0.cmp(&right.0)); - let resumable_checkpoint = if failed_cell_ids.len() == cell_failures.len() { - checkpoint.completed_cells = terminals - .into_iter() - .map(|(cell_id, terminal)| ResolutionCellTerminalCheckpoint { cell_id, terminal }) - .collect(); - checkpoint.failed_cell_ids = failed_cell_ids; - Some(seal_resolution_wave_checkpoint(checkpoint)?) - } else { - None - }; - return Err(anyhow::Error::new(ResolutionWavePipelineFailure { - pipeline_errors, - stage_receipts, - checkpoint: resumable_checkpoint, - })); - } - terminals.sort_by(|left, right| left.0.cmp(&right.0)); - checkpoint.completed_cells = terminals - .iter() - .cloned() - .map(|(cell_id, terminal)| ResolutionCellTerminalCheckpoint { cell_id, terminal }) - .collect(); - checkpoint.failed_cell_ids.clear(); - checkpoint = seal_resolution_wave_checkpoint(checkpoint)?; - validate_resolution_wave_checkpoint(campaign, &checkpoint)?; - let appraisals = terminals - .iter() - .map(|(_, terminal)| terminal.appraisal.clone()) - .collect(); - let private_cell_traces = terminals - .iter() - .map(|(cell_id, terminal)| PrivateCellTrace { - cell_id: cell_id.clone(), - terminal_pipeline_receipt_hashes: terminal - .stage_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect(), - lived_stream: terminal.lived_stream.text.clone(), - persona_output: terminal.persona_output.clone(), - }) - .collect(); - let mut committed_stages = stages.clone(); - for (_, terminal) in terminals { - let terminal_stages = terminal - .stage_receipts - .into_iter() - .map(|receipt| ModelStageOutput { - narrative: String::new(), - structured: None, - receipt, - }) - .collect::>(); - committed_stages.extend(terminal_stages.clone()); - stages.extend(terminal_stages); - } - let cell_model_receipt_hashes = distinct_model_receipt_hashes(&committed_stages); - let mut wave = ResolutionWaveCommit { - schema: "ghostlight.resolution_wave_commit.v1".into(), - world_revision: campaign.revision, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - cover, - plan_receipt: receipt, - appraisals, - activity_outcomes: Vec::new(), - strategic_individuations: Vec::new(), - model_receipt_hashes: cell_model_receipt_hashes, - }; - let selection = select_resolution_wave(campaign, &wave)?; - let outcome_digests = selection - .activity_proposals - .iter() - .map(cell_action_digest) - .collect::>>()?; - let outcome_binding = activity_outcome_binding( - campaign.id, - campaign.revision, - campaign.resolution_policy.resolution_epoch, - &outcome_digests, - ); - if !outcome_digests.is_empty() { - outcome_permit - .require( - "strategic-outcomes", - &outcome_binding, - "strategic_outcome_resolver", - ) - .await?; - } - let outcome_resolution = resolve_activity_outcomes_with_causal_assignments( - outcome_model.clone(), - campaign, - &selection.activity_proposals, - &wave.cover.causal_follow_through, - ) - .await; - let (activity_outcomes, outcome_stages) = match outcome_resolution { - Ok(resolution) => resolution, - Err(error) => { - let mut stage_receipts = stages - .iter() - .map(|stage| stage.receipt.clone()) - .collect::>(); - if let Some(failure) = error.downcast_ref::() { - stage_receipts.extend(failure.stage_receipts.clone()); - } - return Err(anyhow::Error::new(ResolutionWavePipelineFailure { - pipeline_errors: vec![error.to_string()], - stage_receipts, - checkpoint: Some(checkpoint), - })); - } - }; - if !outcome_digests.is_empty() { - outcome_permit - .require( - "strategic-outcomes", - &outcome_binding, - "strategic_outcome_terminal", - ) - .await?; - } - committed_stages.extend(outcome_stages.clone()); - stages.extend(outcome_stages); - wave.activity_outcomes = activity_outcomes; - let individuation_candidate_digests = - strategic_individuation_candidate_digests(campaign, &selection.plan.selected_actions); - if !individuation_candidate_digests.is_empty() { - outcome_permit - .require( - "strategic-individuation", - &strategic_individuation_binding(campaign, &individuation_candidate_digests, None), - "strategic_individuation_selector", - ) - .await?; - } - let (strategic_individuations, individuation_stages) = propose_strategic_individuation( - outcome_model.as_ref(), - campaign, - &selection.plan.selected_actions, - ) - .await; - if !individuation_candidate_digests.is_empty() { - let proposal_digest = strategic_individuations - .first() - .map(strategic_individuation_proposal_digest) - .transpose()?; - outcome_permit - .require( - "strategic-individuation", - &strategic_individuation_binding( - campaign, - &individuation_candidate_digests, - proposal_digest.as_deref(), - ), - "strategic_individuation_terminal", - ) - .await?; - } - committed_stages.extend(individuation_stages.clone()); - stages.extend(individuation_stages); - wave.strategic_individuations = strategic_individuations; - wave.model_receipt_hashes = distinct_model_receipt_hashes(&committed_stages); - validate_and_resolve_wave(campaign, &wave)?; - let aggregate_receipt_hash = format!( - "sha256:{:x}", - Sha256::digest(wave.model_receipt_hashes.join("|").as_bytes()) - ); - Ok(StrategicResolutionOutput { - wave, - stages, - private_cell_traces, - aggregate_receipt_hash, - checkpoint, - }) -} - -fn validate_resolution_wave_checkpoint( - campaign: &Campaign, - checkpoint: &ResolutionWaveCheckpoint, -) -> Result<()> { - if checkpoint.digest != resolution_wave_checkpoint_digest(checkpoint)? { - return Err(anyhow!( - "strategic wave checkpoint digest does not bind its complete typed state" - )); - } - if checkpoint.schema != "ghostlight.resolution_wave_checkpoint.v1" - || checkpoint.campaign_id != campaign.id - || checkpoint.world_revision != campaign.revision - || checkpoint.resolution_epoch != campaign.resolution_policy.resolution_epoch - || checkpoint.cover.campaign_id != campaign.id - || checkpoint.cover.world_revision != campaign.revision - || checkpoint.cover.resolution_epoch != campaign.resolution_policy.resolution_epoch - { - return Err(anyhow!( - "strategic wave checkpoint belongs to a different campaign snapshot" - )); - } - validate_demand(campaign, &checkpoint.cover.demand)?; - validate_cover(campaign, &checkpoint.cover.demand, &checkpoint.cover.cells)?; - validate_causal_follow_through(campaign, &checkpoint.cover)?; - let planning_binding = format!( - "campaign:{}:revision:{}:resolution:{}", - campaign.id, campaign.revision, campaign.resolution_policy.resolution_epoch - ); - let planning_sources = campaign - .branch_origin - .evidence_receipt_ids - .iter() - .cloned() - .collect::>(); - let causal_binding = causal_follow_through_snapshot(campaign, &checkpoint.cover)?; - let admitted_causal_binding = nemesis_admission_binding(campaign, &checkpoint.cover)?; - let mut planning_receipt_keys = BTreeSet::new(); - let mut accepted_causal_receipt = false; - for receipt in &checkpoint.planning_stage_receipts { - if receipt.schema != "ghostlight.persona_stage_receipt.v1" - || !model_receipt_hashes_are_well_formed(receipt) - || planning_receipt_keys.contains(receipt.storage_key()) - || !receipt.source_receipt_ids.iter().all(|source| { - planning_sources.contains(source) || planning_receipt_keys.contains(source) - }) - { - return Err(anyhow!( - "strategic wave checkpoint contains invalid planning receipt provenance" - )); - } - match receipt.stage.as_str() { - "resolution_demand" => { - if receipt.snapshot_binding != planning_binding - || receipt - .source_receipt_ids - .iter() - .cloned() - .collect::>() - != planning_sources - { - return Err(anyhow!( - "strategic wave checkpoint contains misbound demand provenance" - )); - } - } - NEMESIS_STAGE => { - if receipt.snapshot_binding != causal_binding - && receipt.snapshot_binding != admitted_causal_binding - { - return Err(anyhow!( - "strategic wave checkpoint contains misbound causal follow-through provenance" - )); - } - accepted_causal_receipt |= receipt.snapshot_binding == admitted_causal_binding; - } - _ => { - return Err(anyhow!( - "strategic wave checkpoint contains an unknown planning authority" - )); - } - } - planning_receipt_keys.insert(receipt.storage_key().to_owned()); - } - if !checkpoint.cover.causal_follow_through.is_empty() && !accepted_causal_receipt { - return Err(anyhow!( - "strategic wave checkpoint lacks the receipt admitted for its exact causal agenda" - )); - } - let expected_plan = plan_receipt(campaign, &checkpoint.cover); - if checkpoint.plan_receipt.campaign_id != expected_plan.campaign_id - || checkpoint.plan_receipt.world_revision != expected_plan.world_revision - || checkpoint.plan_receipt.resolution_epoch != expected_plan.resolution_epoch - || checkpoint.plan_receipt.configured_budget != expected_plan.configured_budget - || checkpoint.plan_receipt.effective_budget != expected_plan.effective_budget - || checkpoint.plan_receipt.cell_ids != expected_plan.cell_ids - || checkpoint.plan_receipt.mandatory_overage != expected_plan.mandatory_overage - || checkpoint.plan_receipt.preserved_cell_ids != expected_plan.preserved_cell_ids - || checkpoint.plan_receipt.collapsed_boundaries != expected_plan.collapsed_boundaries - || checkpoint.plan_receipt.merge_losses != expected_plan.merge_losses - || checkpoint.plan_receipt.rationale != expected_plan.rationale - { - return Err(anyhow!( - "strategic wave checkpoint plan does not bind its exact cover" - )); - } - let cells = checkpoint - .cover - .cells - .iter() - .map(|cell| (cell.id.as_str(), cell)) - .collect::>(); - let mut completed_ids = BTreeSet::new(); - for completed in &checkpoint.completed_cells { - let cell = cells.get(completed.cell_id.as_str()).ok_or_else(|| { - anyhow!("strategic wave checkpoint contains a terminal for an unknown cell") - })?; - if !completed_ids.insert(completed.cell_id.as_str()) { - return Err(anyhow!( - "strategic wave checkpoint contains duplicate completed cell authority" - )); - } - validate_resolution_cell_terminal(campaign, &checkpoint.cover, cell, completed)?; - } - if checkpoint.failed_cell_ids.iter().any(|cell_id| { - !cells.contains_key(cell_id.as_str()) || completed_ids.contains(cell_id.as_str()) - }) { - return Err(anyhow!( - "strategic wave checkpoint has overlapping or unknown failed cell authority" - )); - } - let accounted = completed_ids.len() + checkpoint.failed_cell_ids.len(); - if accounted != cells.len() { - return Err(anyhow!( - "strategic wave checkpoint does not account for every exact cover cell" - )); - } - Ok(()) -} - -fn validate_resolution_cell_terminal( - campaign: &Campaign, - cover: &crate::domain::ResolutionCover, - cell: &crate::domain::SimulationCell, - completed: &ResolutionCellTerminalCheckpoint, -) -> Result<()> { - let slice = cell_slice(campaign, cover, cell)?; - let terminal = &completed.terminal; - if terminal.appraisal.cell_id != completed.cell_id - || terminal.appraisal.world_revision != campaign.revision - || terminal.appraisal.resolution_epoch != campaign.resolution_policy.resolution_epoch - || terminal.lived_stream.snapshot_binding != slice.snapshot_binding - || terminal.lived_stream.projector_receipt.snapshot_binding != slice.snapshot_binding - || terminal.lived_stream.projector_receipt.stage != "cell_projector" - { - return Err(anyhow!( - "strategic wave checkpoint contains a stale or misbound cell terminal" - )); - } - let base_sources = slice - .source_receipt_ids - .iter() - .cloned() - .collect::>(); - let all_receipt_keys = terminal - .stage_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - if all_receipt_keys.len() != terminal.stage_receipts.len() { - return Err(anyhow!( - "strategic wave checkpoint contains duplicate cell receipt authority" - )); - } - let mut seen_receipt_keys = BTreeSet::new(); - let mut projector_receipt_keys = BTreeSet::new(); - let mut persona_receipt_keys = BTreeSet::new(); - let mut interpreter_receipt_keys = BTreeSet::new(); - let mut verifier_receipts = Vec::new(); - let mut persona_output_is_bound = false; - let persona_output_hash = format!( - "sha256:{:x}", - Sha256::digest(terminal.persona_output.as_bytes()) - ); - for receipt in &terminal.stage_receipts { - if receipt.schema != "ghostlight.persona_stage_receipt.v1" - || !model_receipt_hashes_are_well_formed(receipt) - || receipt - .source_receipt_ids - .iter() - .any(|source| !base_sources.contains(source) && !seen_receipt_keys.contains(source)) - { - return Err(anyhow!( - "strategic wave checkpoint contains invalid or noncausal cell receipts" - )); - } - let source_ids = receipt - .source_receipt_ids - .iter() - .map(String::as_str) - .collect::>(); - let cites_any = - |keys: &BTreeSet| keys.iter().any(|key| source_ids.contains(key.as_str())); - match receipt.stage.as_str() { - "cell_projector" if receipt.snapshot_binding == slice.snapshot_binding => { - projector_receipt_keys.insert(receipt.storage_key().to_owned()); - } - "cell_persona" - if receipt.snapshot_binding == slice.snapshot_binding - && cites_any(&projector_receipt_keys) => - { - if receipt.validation_result == "valid" - && receipt.output_hash == persona_output_hash - { - persona_output_is_bound = true; - } - persona_receipt_keys.insert(receipt.storage_key().to_owned()); - } - "cell_interpreter" - if receipt.snapshot_binding == slice.snapshot_binding - && cites_any(&projector_receipt_keys) - && cites_any(&persona_receipt_keys) => - { - interpreter_receipt_keys.insert(receipt.storage_key().to_owned()); - } - "cell_effect_verifier" - if receipt - .snapshot_binding - .starts_with(&format!("{}:effects:sha256:", slice.snapshot_binding)) - && cites_any(&projector_receipt_keys) - && cites_any(&persona_receipt_keys) - && cites_any(&interpreter_receipt_keys) => - { - verifier_receipts.push(receipt); - } - _ => { - return Err(anyhow!( - "strategic wave checkpoint contains an invalid cell receipt stage or binding" - )); - } - } - seen_receipt_keys.insert(receipt.storage_key().to_owned()); - } - if projector_receipt_keys.is_empty() - || persona_receipt_keys.is_empty() - || interpreter_receipt_keys.is_empty() - || !persona_output_is_bound - || !terminal - .stage_receipts - .iter() - .any(|receipt| receipt.same_receipted_content(&terminal.lived_stream.projector_receipt)) - { - return Err(anyhow!( - "strategic wave checkpoint cell terminal lacks its exact membrane receipts" - )); - } - for action in &terminal.appraisal.actions { - let binding = crate::persona::cell_effect_verification_binding( - &slice.snapshot_binding, - std::slice::from_ref(action), - )?; - if !verifier_receipts.iter().any(|receipt| { - receipt.snapshot_binding == binding - && receipt.validation_result == "valid" - && receipt.local_validation_error.is_none() - }) { - return Err(anyhow!( - "strategic wave checkpoint action lacks an accepted exact verifier receipt" - )); - } - } - Ok(()) -} - -fn model_receipt_hashes_are_well_formed(receipt: &ModelStageReceipt) -> bool { - [ - receipt.storage_key(), - receipt.request_hash.as_str(), - receipt.output_hash.as_str(), - ] - .into_iter() - .all(|value| { - value.strip_prefix("sha256:").is_some_and(|digest| { - digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()) - }) - }) -} - -fn seal_resolution_wave_checkpoint( - mut checkpoint: ResolutionWaveCheckpoint, -) -> Result { - checkpoint.digest = resolution_wave_checkpoint_digest(&checkpoint)?; - Ok(checkpoint) -} - -fn resolution_wave_checkpoint_digest(checkpoint: &ResolutionWaveCheckpoint) -> Result { - let mut unsigned = checkpoint.clone(); - unsigned.digest.clear(); - crate::legacy_transition::digest_serializable(&( - "ghostlight.resolution_wave_checkpoint.v1", - unsigned, - )) -} - -pub fn strategic_individuation_binding( - campaign: &Campaign, - action_digests: &[String], - proposal_digest: Option<&str>, -) -> String { - format!( - "campaign:{}:revision:{}:resolution:{}:strategic-individuation:{}:proposal:{}", - campaign.id, - campaign.revision, - campaign.resolution_policy.resolution_epoch, - action_digests.join(","), - proposal_digest.unwrap_or("none") - ) -} - -pub fn strategic_individuation_candidate_digests( - campaign: &Campaign, - selected_actions: &[crate::domain::CellActionProposal], -) -> Vec { - selected_actions - .iter() - .filter(|action| { - campaign.gestalts.contains_key(&action.subject_id) - && campaign - .agency_profiles - .get(&action.subject_id) - .is_some_and(|profile| { - profile.active_leaf - && profile.simulation_eligible - && profile.location_ids.len() == 1 - }) - }) - .filter_map(|action| cell_action_digest(action).ok()) - .collect() -} - -pub fn strategic_individuation_proposal_digest( - proposal: &StrategicGestaltIndividuation, -) -> Result { - Ok(format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(proposal)?) - )) -} - -async fn propose_strategic_individuation( - model: &dyn ModelPort, - campaign: &Campaign, - selected_actions: &[crate::domain::CellActionProposal], -) -> (Vec, Vec) { - let candidates = selected_actions - .iter() - .filter_map(|action| { - let gestalt = campaign.gestalts.get(&action.subject_id)?; - let profile = campaign.agency_profiles.get(&action.subject_id)?; - (profile.active_leaf && profile.simulation_eligible && profile.location_ids.len() == 1) - .then(|| { - ( - action, - gestalt, - profile.location_ids.iter().next().unwrap().clone(), - ) - }) - }) - .filter_map(|(action, gestalt, location_id)| { - cell_action_digest(action) - .ok() - .map(|digest| (digest, action, gestalt, location_id)) - }) - .collect::>(); - if candidates.is_empty() { - return (Vec::new(), Vec::new()); - } - let digests = candidates - .iter() - .map(|(digest, ..)| digest.clone()) - .collect::>(); - let context = candidates - .iter() - .map(|(digest, action, gestalt, location_id)| { - serde_json::json!({ - "action_digest":digest, - "gestalt_id":gestalt.id, - "gestalt_name":gestalt.name, - "location_id":location_id, - "goals":gestalt.goals, - "pressures":gestalt.pressures, - "selected_action":action, - }) - }) - .collect::>(); - let mut schema = match serde_json::to_value(schema_for!(StrategicPersonSelection)) { - Ok(schema) => schema, - Err(_) => return (Vec::new(), Vec::new()), - }; - if let Some(value) = schema.pointer_mut("/$defs/StrategicPersonDraft/properties/action_digest") - { - *value = serde_json::json!({"type":"string","enum":digests}); - } - if let Some(value) = schema.pointer_mut("/$defs/StrategicPersonDraft/properties/gestalt_id") { - *value = serde_json::json!({"type":"string","enum":candidates.iter().map(|(_, _, gestalt, _)| gestalt.id.clone()).collect::>()}); - } - if let Some(proposals) = schema - .pointer_mut("/properties/proposals") - .and_then(serde_json::Value::as_object_mut) - { - proposals.insert("maxItems".into(), 1.into()); - } - let request = ModelStageRequest { - stage: "strategic_individuation_selector".into(), - model: MODEL_FAST.into(), - snapshot_binding: strategic_individuation_binding(campaign, &digests, None), - lived_stream: format!( - "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nReturn zero or one proposal. Choose one person only when a selected Gestalt action has created concrete political work that cannot remain anonymous: an envoy, organizer, claimant, conspirator, commander, broker, or dissident. Identity content is a proposal only. Give that person a stable personal self-identifier suitable to the setting; name must never be a role, office, condition, manifest category, or descriptive placeholder. Use a short stable lowercase member_id derived from that personal name without a member: prefix. Do not invent authority, location, or state beyond the supplied Gestalt. Return an empty proposals list when nobody needs to emerge.\nCANDIDATES:\n{}", - serde_json::to_string(&schema).unwrap_or_default(), - serde_json::to_string(&context).unwrap_or_default(), - ), - output_schema: Some(schema), - source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), - temperature: Some(0.2), - max_output_tokens: Some(768), - }; - let Ok(mut output) = run_validated_stage(model, &request).await else { - return (Vec::new(), Vec::new()); - }; - let Some(mut selection) = output - .structured - .clone() - .and_then(|value| serde_json::from_value::(value).ok()) - else { - return (Vec::new(), vec![output]); - }; - if selection.proposals.is_empty() { - return (Vec::new(), vec![output]); - } - if selection.proposals.len() != 1 { - output.receipt.validation_result = "semantic_invalid".into(); - output.receipt.local_validation_error = - Some("strategic selector exceeded its one-person budget".into()); - return (Vec::new(), vec![output]); - } - let draft = selection.proposals.remove(0); - let Some((_, _, gestalt, location_id)) = candidates.iter().find(|(digest, _, gestalt, _)| { - digest == &draft.action_digest && gestalt.id == draft.gestalt_id - }) else { - output.receipt.validation_result = "semantic_invalid".into(); - output.receipt.local_validation_error = - Some("proposed person crossed the selected Gestalt action boundary".into()); - return (Vec::new(), vec![output]); - }; - let member_id = crate::domain::canonical_gestalt_member_local_id(&draft.member_id); - if member_id.is_empty() - || draft.name.trim().is_empty() - || campaign.gestalt_members.contains_key(&member_id) - { - output.receipt.validation_result = "semantic_invalid".into(); - output.receipt.local_validation_error = - Some("proposed person has an empty or occupied identity".into()); - return (Vec::new(), vec![output]); - } - let member = GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: member_id, - gestalt_id: gestalt.id.clone(), - version: 0, - name: draft.name, - capability_additions: BTreeSet::new(), - capability_removals: BTreeSet::new(), - knowledge_additions: BTreeSet::new(), - knowledge_removals: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: draft.obligations, - relationships: draft.relationships, - goals: draft.goals, - memories: draft.memories, - last_location_id: Some(location_id.clone()), - materialized_actor_id: None, - last_relevant_revision: campaign.revision, - relevance_lease_until_revision: campaign.revision.saturating_add(4), - }; - let proposal = StrategicGestaltIndividuation { - schema: "ghostlight.strategic_gestalt_individuation.v1".into(), - action_digest: draft.action_digest, - rationale: draft.rationale, - individuation: GestaltIndividuation { - gestalt_id: gestalt.id.clone(), - expected_gestalt_version: gestalt.version, - member, - location_id: location_id.clone(), - }, - }; - if let Err(error) = crate::resolution::validate_strategic_individuation_proposals( - campaign, - std::slice::from_ref(&proposal), - selected_actions, - ) { - output.receipt.validation_result = "semantic_invalid".into(); - output.receipt.local_validation_error = Some(error.to_string()); - return (Vec::new(), vec![output]); - } - let proposal_digest = match strategic_individuation_proposal_digest(&proposal) { - Ok(digest) => digest, - Err(_) => return (Vec::new(), vec![output]), - }; - output - .receipt - .rebind_snapshot(strategic_individuation_binding( - campaign, - &digests, - Some(&proposal_digest), - )); - (vec![proposal], vec![output]) -} - -fn distinct_model_receipt_hashes(stages: &[ModelStageOutput]) -> Vec { - let mut seen = BTreeSet::new(); - stages - .iter() - .filter_map(|stage| { - let hash = stage.receipt.storage_key().to_owned(); - seen.insert(hash.clone()).then_some(hash) - }) - .collect() -} - -async fn project_resolution_demand( - model: &dyn ModelPort, - campaign: &Campaign, - campaign_contract: Option<&CampaignContract>, - aggregate_boundaries: &[AggregatedBoundary], -) -> (ResolutionDemand, Vec) { - let fallback = || { - campaign - .resolution_cover - .as_ref() - .map(|cover| { - let mut demand = cover.demand.clone(); - demand.world_revision = campaign.revision; - demand.resolution_epoch = campaign.resolution_policy.resolution_epoch; - demand.rationale = format!("last accepted demand: {}", demand.rationale); - demand - }) - .unwrap_or_else(|| default_demand(campaign, "default geography/authority demand")) - }; - let (focal_candidate_ids, agency_summary) = resolution_demand_context(campaign); - let context = serde_json::json!({ - "campaign_id": campaign.id, - "world_revision": campaign.revision, - "resolution_epoch": campaign.resolution_policy.resolution_epoch, - "horizon_minutes": campaign.tick_hours.saturating_mul(60), - "clocks": campaign.clocks.values().map(|clock| serde_json::json!({ - "id":clock.id, - "label":clock.label, - "progress":clock.progress, - "threshold":clock.threshold, - "consequence":clock.consequence, - })).collect::>(), - "agency_summary": agency_summary, - "campaign_contract":campaign_contract, - "aggregate_content_boundaries":aggregate_boundaries, - }); - let mut schema = match serde_json::to_value(schema_for!(DemandProjection)) { - Ok(value) => value, - Err(_) => return (fallback(), vec![]), - }; - if let Some(items) = schema.pointer_mut("/properties/focal_subject_ids/items") { - *items = serde_json::json!({"type":"string","enum":focal_candidate_ids}); - } - if let Some(focal) = schema - .pointer_mut("/properties/focal_subject_ids") - .and_then(serde_json::Value::as_object_mut) - { - focal.insert("uniqueItems".into(), true.into()); - focal.insert( - "maxItems".into(), - usize::from(campaign.resolution_policy.active_cell_budget) - .min(focal_candidate_ids.len()) - .into(), - ); - } - let base_prompt = format!( - "OUTPUT JSON SCHEMA (follow exactly):\n{}\n\nProject which boundaries best predict different strategic behavior for the next horizon. Return all six axis weights (geography, ideology, authority, economy_role, species_body, information), each from 0 to 1 and summing to 1. The focal-subject enum contains only candidates that committed state has locally distinguished. Choose only genuinely exceptional candidates and return an empty list when the enum is empty. Focal hints cannot force partition boundaries or budget overage. This stage proposes relevance and cannot change world state.\nSTATE:\n{}", - serde_json::to_string(&schema).unwrap_or_default(), - serde_json::to_string(&context).unwrap_or_default(), - ); - let mut request = ModelStageRequest { - stage: "resolution_demand".into(), - model: MODEL_FAST.into(), - snapshot_binding: format!( - "campaign:{}:revision:{}:resolution:{}", - campaign.id, campaign.revision, campaign.resolution_policy.resolution_epoch - ), - lived_stream: base_prompt, - output_schema: Some(schema), - source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), - temperature: Some(0.0), - max_output_tokens: Some(512), - }; - let mut outputs = Vec::new(); - for attempt in 0..2 { - let Ok(mut output) = run_validated_stage(model, &request).await else { - return (fallback(), outputs); - }; - let projection = output - .structured - .clone() - .and_then(|value| serde_json::from_value::(value).ok()); - if let Some(projection) = projection { - let demand = ResolutionDemand { - schema: "ghostlight.resolution_demand.v1".into(), - campaign_id: campaign.id, - world_revision: campaign.revision, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - axis_weights: projection.axis_weights.into_map(), - focal_subject_ids: projection.focal_subject_ids, - horizon_minutes: campaign.tick_hours.saturating_mul(60), - rationale: projection.rationale, - }; - match validate_demand(campaign, &demand) { - Ok(()) => { - outputs.push(output); - return (demand, outputs); - } - Err(error) => { - output.receipt.validation_result = "semantic_invalid".into(); - output.receipt.local_validation_error = - Some(error.to_string().chars().take(1_000).collect()); - } - } - } else { - output.receipt.validation_result = "semantic_invalid".into(); - output.receipt.local_validation_error = - Some("resolution demand could not be decoded".into()); - } - outputs.push(output); - if attempt == 0 { - request.lived_stream.push_str( - "\n\nLOCAL VALIDATOR: The prior projection omitted an axis, used an unknown subject, had invalid weights, failed to sum to one, or had no rationale. Return one corrected object against the same snapshot.", - ); - } - } - (fallback(), outputs) -} - -fn resolution_demand_context(campaign: &Campaign) -> (Vec, serde_json::Value) { - let profiles = campaign - .agency_profiles - .values() - .filter(|profile| profile.active_leaf && profile.simulation_eligible) - .collect::>(); - let active_ids = profiles - .iter() - .map(|profile| profile.subject_id.clone()) - .collect::>(); - let active_id_set = active_ids.iter().cloned().collect::>(); - let axes = [ - AgencyAxis::Geography, - AgencyAxis::Ideology, - AgencyAxis::Authority, - AgencyAxis::EconomyRole, - AgencyAxis::SpeciesBody, - AgencyAxis::Information, - ]; - let mut facet_value_counts: BTreeMap> = axes - .iter() - .cloned() - .map(|axis| (axis, BTreeMap::new())) - .collect(); - let mut collective_authority_counts = BTreeMap::::new(); - for profile in &profiles { - for axis in &axes { - let buckets = facet_value_counts - .get_mut(axis) - .expect("all six agency axes were initialized"); - match profile.facets.get(axis).filter(|values| !values.is_empty()) { - Some(values) => { - for value in values { - *buckets.entry(value.clone()).or_default() += 1; - } - } - None => { - *buckets.entry("unknown".into()).or_default() += 1; - } - } - } - let authority = profile - .collective_authority_id - .clone() - .unwrap_or_else(|| "none".into()); - *collective_authority_counts.entry(authority).or_default() += 1; - } - let mut relation_summary = BTreeMap::::new(); - for relation in campaign - .agency_relations - .values() - .filter(|relation| relation.active) - { - let kind = serde_json::to_value(&relation.kind) - .ok() - .and_then(|value| value.as_str().map(str::to_owned)) - .unwrap_or_else(|| "unknown".into()); - let summary = relation_summary.entry(kind).or_default(); - summary.edges += 1; - summary.total_strength += u64::from(relation.strength); - summary.max_strength = summary.max_strength.max(relation.strength); - } - let recent_events = campaign - .events - .iter() - .rev() - .take(12) - .map(|event| { - serde_json::json!({ - "id":event.id, - "kind":event.kind, - "summary":event.summary, - "actor_ids":event.actor_ids, - "institution_ids":event.institution_ids, - "gestalt_ids":event.gestalt_ids, - "location_ids":event.location_ids, - "public_channels":event.public_channels, - }) - }) - .collect::>(); - let recent_participant_ids = campaign - .events - .iter() - .rev() - .take(12) - .flat_map(|event| { - event - .actor_ids - .iter() - .chain(event.institution_ids.iter()) - .chain(event.gestalt_ids.iter()) - }) - .filter(|id| campaign.agency_profiles.contains_key(*id)) - .cloned() - .collect::>(); - let mut highest_detail_debt = profiles - .iter() - .filter(|profile| profile.detail_debt > 0) - .map(|profile| (profile.subject_id.clone(), profile.detail_debt)) - .collect::>(); - highest_detail_debt - .sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0))); - highest_detail_debt - .truncate(usize::from(campaign.resolution_policy.active_cell_budget).max(4) * 2); - let mut focal_candidate_ids = highest_detail_debt - .iter() - .map(|(subject_id, _)| subject_id.clone()) - .collect::>(); - if !recent_participant_ids.is_empty() && recent_participant_ids.len() < active_id_set.len() { - focal_candidate_ids.extend(recent_participant_ids.iter().cloned()); - } - let focal_candidate_ids = focal_candidate_ids.into_iter().collect::>(); - ( - focal_candidate_ids.clone(), - serde_json::json!({ - "active_subject_count": profiles.len(), - "facet_value_counts": facet_value_counts, - "collective_authority_counts": collective_authority_counts, - "relation_summary": relation_summary, - "recent_events": recent_events, - "recent_participant_ids": recent_participant_ids, - "focal_candidate_ids": focal_candidate_ids, - "highest_detail_debt": highest_detail_debt.iter().map(|(subject_id, detail_debt)| serde_json::json!({ - "subject_id":subject_id, - "detail_debt":detail_debt, - })).collect::>(), - }), - ) -} - -fn cell_slice( - campaign: &Campaign, - cover: &crate::domain::ResolutionCover, - cell: &SimulationCell, -) -> Result { - let member_candidates = member_exceptions(campaign, cell)?; - let causal_assignments = assignments_for_cell(campaign, cover, cell); - let decision_owner_ids = - select_cell_decision_owners(campaign, cell, &member_candidates, &causal_assignments)?; - let mut member_exceptions = member_candidates - .into_iter() - .filter(|member| decision_owner_ids.contains(&member.subject_id)) - .collect::>(); - let selected_member_ids = member_exceptions - .iter() - .map(|member| member.subject_id.clone()) - .collect::>(); - let mut constituents = cell - .subject_ids - .iter() - .map(|id| constituent_slice(campaign, id)) - .collect::>>()?; - let causal_follow_through = causal_assignments - .iter() - .map(|assignment| { - let summary = causal_anchor_summary(campaign, &assignment.anchor_reference) - .ok_or_else(|| anyhow!("causal response anchor vanished from campaign state"))?; - Ok(CellCausalFollowThroughSlice { - anchor_reference: assignment.anchor_reference.clone(), - responder_subject_id: assignment.responder_subject_id.clone(), - summary, - }) - }) - .collect::>>()?; - for focus in &causal_follow_through { - if let Some(subject) = constituents - .iter_mut() - .find(|subject| subject.subject_id == focus.responder_subject_id) - { - subject - .permitted_state_references - .insert(focus.anchor_reference.clone()); - } else if let Some(member) = member_exceptions - .iter_mut() - .find(|member| member.subject_id == focus.responder_subject_id) - { - member - .permitted_state_references - .insert(focus.anchor_reference.clone()); - } else { - return Err(anyhow!( - "causal response owner {} is absent from exact cell {}", - focus.responder_subject_id, - cell.id - )); - } - } - for subject in &mut constituents { - subject.activity_targets.retain(|target, _| { - !target.starts_with("member:") || selected_member_ids.contains(target) - }); - } - for member in &mut member_exceptions { - member.activity_targets.retain(|target, _| { - !target.starts_with("member:") || selected_member_ids.contains(target) - }); - } - let shared_knowledge = intersection( - constituents - .iter() - .map(|subject| &subject.knowledge) - .collect(), - ); - let shared_capabilities = intersection( - constituents - .iter() - .map(|subject| &subject.capabilities) - .collect(), - ); - let perceived_events = cell_perceived_events(campaign, &constituents, &member_exceptions); - let canonical_locations = constituents - .iter() - .flat_map(|subject| subject.location_ids.iter()) - .chain( - member_exceptions - .iter() - .map(|member| &member.source_location_id), - ) - .map(|location_id| { - let location = campaign - .locations - .get(location_id) - .ok_or_else(|| anyhow!("simulation cell location vanished from campaign"))?; - Ok((location_id.clone(), location.name.clone())) - }) - .collect::>>()?; - Ok(PermittedCellSlice { - cell_id: cell.id.clone(), - mode: cell.mode.clone(), - world_revision: campaign.revision, - resolution_epoch: campaign.resolution_policy.resolution_epoch, - snapshot_binding: format!( - "campaign:{}:revision:{}:resolution:{}:cell:{}", - campaign.id, campaign.revision, campaign.resolution_policy.resolution_epoch, cell.id - ), - constituents, - member_exceptions, - shared_knowledge, - shared_capabilities, - perceived_events, - causal_follow_through, - world_clock_pressure: campaign - .clocks - .values() - .map(project_world_clock_pressure) - .collect(), - canonical_locations, - detail_focus_subject_id: cell.detail_focus_subject_id.clone(), - decision_owner_ids, - max_actions: cell_action_limit(cell), - source_receipt_ids: campaign.branch_origin.evidence_receipt_ids.clone(), - }) -} - -fn select_cell_decision_owners( - campaign: &Campaign, - cell: &SimulationCell, - member_candidates: &[CellMemberSlice], - causal_assignments: &[&crate::domain::CausalFollowThroughAssignment], -) -> Result> { - let quota = cell_action_limit(cell); - if quota == 0 || cell.subject_ids.is_empty() { - return Err(anyhow!("simulation cell has no bounded decision capacity")); - } - if let Some(focus) = cell.detail_focus_subject_id.as_deref() - && !cell.subject_ids.contains(focus) - { - return Err(anyhow!("simulation cell detail focus is outside the cell")); - } - - let canonical = cell.subject_ids.iter().cloned().collect::>(); - let mut owners = causal_assignments - .iter() - .map(|assignment| assignment.responder_subject_id.clone()) - .collect::>(); - if owners.len() != causal_assignments.len() || owners.len() > quota { - return Err(anyhow!( - "causal response agenda duplicates an owner or exceeds this cell's quota" - )); - } - let represented_canonical = |owners: &BTreeSet| { - owners - .iter() - .map(|owner| { - owner - .strip_prefix("member:") - .and_then(|member_id| campaign.gestalt_members.get(member_id)) - .map(|member| member.gestalt_id.clone()) - .unwrap_or_else(|| owner.clone()) - }) - .collect::>() - }; - if let Some(focus) = cell.detail_focus_subject_id.as_ref() - && owners.len() < quota - && !represented_canonical(&owners).contains(focus) - { - owners.insert(focus.clone()); - } - let represented = represented_canonical(&owners); - let available = canonical - .iter() - .filter(|subject_id| !represented.contains(*subject_id)) - .cloned() - .collect::>(); - let remaining = quota.saturating_sub(owners.len()).min(available.len()); - let selected = if remaining == available.len() { - available - } else if remaining > 0 { - let start = - (campaign.strategic_tick_count as usize).saturating_mul(remaining) % available.len(); - (0..remaining) - .map(|offset| available[(start + offset) % available.len()].clone()) - .collect() - } else { - Vec::new() - }; - - for subject_id in selected { - if cell.detail_focus_subject_id.as_deref() == Some(subject_id.as_str()) - || !campaign.gestalts.contains_key(&subject_id) - { - owners.insert(subject_id); - continue; - } - let mut alternatives = std::iter::once(subject_id.clone()) - .chain( - member_candidates - .iter() - .filter(|member| member.source_gestalt_id == subject_id) - .map(|member| member.subject_id.clone()), - ) - .collect::>(); - alternatives.dedup(); - let index = campaign.strategic_tick_count as usize % alternatives.len(); - owners.insert(alternatives.swap_remove(index)); - } - if owners.is_empty() || owners.len() > quota { - return Err(anyhow!( - "resolution produced an invalid exact decision-owner set" - )); - } - Ok(owners) -} - -fn project_world_clock_pressure(clock: &crate::domain::WorldClock) -> String { - if clock.progress >= clock.threshold { - format!( - "{}: threshold reached ({}/{}); declared consequence: {}", - clock.label, clock.progress, clock.threshold, clock.consequence - ) - } else { - format!( - "{}: progress {} of {}; {} step(s) remain before declared consequence: {}", - clock.label, - clock.progress, - clock.threshold, - clock.threshold.saturating_sub(clock.progress), - clock.consequence - ) - } -} - -fn cell_perceived_events( - campaign: &Campaign, - constituents: &[CellConstituentSlice], - member_exceptions: &[CellMemberSlice], -) -> Vec { - campaign - .events - .iter() - .rev() - .take(12) - .filter_map(|event| { - let mut perceived_by_subject_ids = constituents - .iter() - .filter(|subject| { - subject_perceives_event( - &subject.subject_id, - &subject.location_ids, - &subject.information_channels, - event, - ) - }) - .map(|subject| subject.subject_id.clone()) - .collect::>(); - perceived_by_subject_ids.extend( - member_exceptions - .iter() - .filter(|member| { - event.actor_ids.contains(&member.subject_id) - || event.location_ids.contains(&member.source_location_id) - || !event - .public_channels - .iter() - .all(|channel| !member.information_channels.contains(channel)) - }) - .map(|member| member.subject_id.clone()), - ); - (!perceived_by_subject_ids.is_empty()).then(|| CellPerceivedEventSlice { - event_id: event.id.clone(), - summary: event.summary.clone(), - perceived_by_subject_ids, - }) - }) - .collect() -} - -pub(crate) fn subject_perceives_event( - subject_id: &str, - location_ids: &BTreeSet, - information_channels: &BTreeSet, - event: &crate::domain::Event, -) -> bool { - event.actor_ids.iter().any(|id| id == subject_id) - || event.institution_ids.iter().any(|id| id == subject_id) - || event.gestalt_ids.iter().any(|id| id == subject_id) - || event - .location_ids - .iter() - .any(|location_id| location_ids.contains(location_id)) - || event - .public_channels - .iter() - .any(|channel| information_channels.contains(channel)) -} - -fn member_exceptions(campaign: &Campaign, cell: &SimulationCell) -> Result> { - let player_id = &campaign.player_actor_id; - let mut candidates = campaign - .gestalt_members - .values() - .filter(|member| { - member.materialized_actor_id.is_none() && cell.subject_ids.contains(&member.gestalt_id) - }) - .filter_map(|member| { - let source = campaign.gestalts.get(&member.gestalt_id)?; - let origin = member - .last_location_id - .clone() - .unwrap_or_else(|| source.home_location_id.clone()); - let destinations = crate::resolution::gestalt_migration_destinations( - campaign, - &member.gestalt_id, - &origin, - ); - let activity_targets = - crate::resolution::member_activity_targets(campaign, &member.id).ok()?; - let player_relationship = member.relationships.contains_key(player_id) as u8; - let personal_pressure = (!member.conditions.is_empty() - || !member.obligations.is_empty() - || !member.goals.is_empty()) as u8; - Some(( - player_relationship, - personal_pressure, - member.last_relevant_revision, - member.id.clone(), - origin, - destinations, - activity_targets, - )) - }) - .collect::>(); - candidates.sort_by(|left, right| { - right - .0 - .cmp(&left.0) - .then_with(|| right.1.cmp(&left.1)) - .then_with(|| right.2.cmp(&left.2)) - .then_with(|| left.3.cmp(&right.3)) - }); - candidates - .into_iter() - .map( - |(_, _, _, member_id, origin, destinations, activity_target_ids)| { - let member = &campaign.gestalt_members[&member_id]; - let source = &campaign.gestalts[&member.gestalt_id]; - let capabilities = overlay( - &source.shared_capabilities, - &member.capability_additions, - &member.capability_removals, - ); - let knowledge = overlay( - &source.shared_knowledge, - &member.knowledge_additions, - &member.knowledge_removals, - ); - let information_channels = - crate::resolution::effective_member_information_channels(campaign, &member.id)?; - let goals = if member.goals.is_empty() { - source.goals.clone() - } else { - member.goals.clone() - }; - let mut permitted_state_references = BTreeSet::from([ - crate::domain::gestalt_member_subject_id(&member.id), - crate::domain::gestalt_state_reference(&member.gestalt_id), - format!("location:{origin}"), - ]); - permitted_state_references.extend( - capabilities - .iter() - .map(|value| format!("capability:{value}")), - ); - permitted_state_references - .extend(knowledge.iter().map(|value| format!("knowledge:{value}"))); - permitted_state_references.extend( - member - .equipment - .iter() - .map(|value| format!("resource:{value}")), - ); - for (gestalt_id, location_id) in &destinations { - permitted_state_references - .insert(crate::domain::gestalt_state_reference(gestalt_id)); - permitted_state_references.insert(format!("location:{location_id}")); - } - let migration_destinations = migration_destination_slices(campaign, &destinations)?; - let activity_targets = activity_target_slices(campaign, &activity_target_ids)?; - Ok(CellMemberSlice { - subject_id: crate::domain::gestalt_member_subject_id(&member.id), - member_id: member.id.clone(), - name: member.name.clone(), - source_gestalt_id: member.gestalt_id.clone(), - source_location_id: origin, - knowledge: knowledge.clone(), - capabilities, - resources: member.equipment.clone(), - information_channels, - permitted_state_references, - migration_destinations, - activity_targets, - goals, - pressures: member - .conditions - .iter() - .chain(&member.obligations) - .cloned() - .collect(), - relationships: member.relationships.clone(), - memories: member.memories.clone(), - }) - }, - ) - .collect() -} - -fn overlay( - baseline: &BTreeSet, - additions: &BTreeSet, - removals: &BTreeSet, -) -> BTreeSet { - baseline - .union(additions) - .filter(|value| !removals.contains(*value)) - .cloned() - .collect() -} - -fn constituent_slice(campaign: &Campaign, id: &str) -> Result { - let profile = campaign - .agency_profiles - .get(id) - .ok_or_else(|| anyhow!("simulation cell subject lacks an agency profile"))?; - let activity_target_ids = crate::resolution::strategic_activity_targets(campaign, id); - let mut value = CellConstituentSlice { - subject_id: id.into(), - subject_kind: profile.subject_kind.clone(), - name: id.into(), - collective_authority_id: profile.collective_authority_id.clone(), - location_ids: profile.location_ids.clone(), - knowledge: BTreeSet::new(), - capabilities: BTreeSet::new(), - resources: BTreeSet::new(), - information_channels: profile.information_channels.clone(), - permitted_state_references: crate::resolution::subject_state_references(campaign, id)?, - reachable_destinations: BTreeMap::new(), - migration_destinations: BTreeMap::new(), - activity_targets: activity_target_slices(campaign, &activity_target_ids)?, - goals: vec![], - relationships: BTreeMap::new(), - memories: vec![], - current_posture: None, - pressures: vec![], - }; - match profile.subject_kind { - AgencySubjectKind::Actor => { - let actor = campaign.actors.get(id).context("cell actor vanished")?; - value.name = actor.name.clone(); - value.knowledge = actor.knowledge.clone(); - value.capabilities = actor.capabilities.clone(); - value.resources = actor.equipment.clone(); - value.goals = actor.goals.clone(); - value.relationships = actor.relationships.clone(); - value.memories = actor.memories.clone(); - value.pressures = actor - .conditions - .iter() - .chain(&actor.obligations) - .cloned() - .collect(); - value.reachable_destinations = campaign - .locations - .get(&actor.location_id) - .into_iter() - .flat_map(|location| location.routes.values()) - .filter(|route| route.travel_minutes <= campaign.tick_hours.saturating_mul(60)) - .map(|route| { - let destination = campaign - .locations - .get(&route.destination_id) - .ok_or_else(|| anyhow!("reachable destination vanished from topology"))?; - Ok((route.destination_id.clone(), destination.name.clone())) - }) - .collect::>>()?; - } - AgencySubjectKind::Institution => { - let institution = campaign - .institutions - .get(id) - .context("cell institution vanished")?; - value.name = institution.name.clone(); - value.resources = institution.resources.iter().cloned().collect(); - value.goals = institution.goals.clone(); - value.current_posture = Some(institution.posture.clone()); - } - AgencySubjectKind::Gestalt => { - let gestalt = campaign.gestalts.get(id).context("cell gestalt vanished")?; - value.name = gestalt.name.clone(); - value.knowledge = gestalt.shared_knowledge.clone(); - value.capabilities = gestalt.shared_capabilities.clone(); - value.resources = gestalt.resources.clone(); - value.goals = gestalt.goals.clone(); - value.pressures = gestalt.pressures.clone(); - let mut destinations = crate::resolution::gestalt_migration_destinations( - campaign, - id, - &gestalt.home_location_id, - ); - destinations.retain(|_, location_id| location_id != &gestalt.home_location_id); - for (destination_id, location_id) in &destinations { - value - .permitted_state_references - .insert(crate::domain::gestalt_state_reference(destination_id)); - value - .permitted_state_references - .insert(format!("location:{location_id}")); - } - value.migration_destinations = migration_destination_slices(campaign, &destinations)?; - } - } - Ok(value) -} - -fn activity_target_slices( - campaign: &Campaign, - target_ids: &BTreeSet, -) -> Result> { - target_ids - .iter() - .map(|target_id| { - let (name, location_ids) = - if let Some(profile) = campaign.agency_profiles.get(target_id) { - let name = campaign - .actors - .get(target_id) - .map(|actor| actor.name.clone()) - .or_else(|| { - campaign - .institutions - .get(target_id) - .map(|institution| institution.name.clone()) - }) - .or_else(|| { - campaign - .gestalts - .get(target_id) - .map(|gestalt| gestalt.name.clone()) - }) - .ok_or_else(|| { - anyhow!("activity target {target_id} has no canonical named subject") - })?; - (name, profile.location_ids.clone()) - } else if let Some(member_id) = - crate::resolution::dormant_member_id_for_subject(campaign, target_id) - { - let member = campaign.gestalt_members.get(member_id).ok_or_else(|| { - anyhow!("activity target {target_id} has no member state") - })?; - ( - member.name.clone(), - BTreeSet::from([crate::resolution::dormant_member_location( - campaign, member_id, - )?]), - ) - } else { - return Err(anyhow!("activity target {target_id} has no agency profile")); - }; - let locations = location_ids - .into_iter() - .map(|location_id| { - let location = campaign.locations.get(&location_id).ok_or_else(|| { - anyhow!("activity target location {location_id} vanished") - })?; - Ok((location_id, location.name.clone())) - }) - .collect::>>()?; - Ok(( - target_id.clone(), - CellActivityTargetSlice { name, locations }, - )) - }) - .collect() -} - -fn migration_destination_slices( - campaign: &Campaign, - destinations: &BTreeMap, -) -> Result> { - destinations - .iter() - .map(|(gestalt_id, location_id)| { - let population = campaign - .gestalts - .get(gestalt_id) - .ok_or_else(|| anyhow!("migration destination {gestalt_id} vanished"))?; - let location = campaign - .locations - .get(location_id) - .ok_or_else(|| anyhow!("migration destination location {location_id} vanished"))?; - Ok(( - gestalt_id.clone(), - CellMigrationDestinationSlice { - population_name: population.name.clone(), - location_id: location_id.clone(), - location_name: location.name.clone(), - }, - )) - }) - .collect() -} - -fn intersection(sets: Vec<&BTreeSet>) -> BTreeSet { - let Some(first) = sets.first() else { - return BTreeSet::new(); - }; - sets.iter().skip(1).fold((*first).clone(), |current, next| { - current.intersection(next).cloned().collect() - }) -} - -pub fn due_tick_target(now: DateTime, last_player_activity: DateTime) -> u8 { - let idle = now - last_player_activity; - if idle < chrono::Duration::minutes(15) { - 0 - } else { - (idle.num_hours().max(0) as u8).min(8) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::model::ModelPort; - use crate::persona::AllowAllPermit; - use async_trait::async_trait; - use std::sync::{ - Mutex, - atomic::{AtomicUsize, Ordering}, - }; - - struct CellFixtureModel { - active: AtomicUsize, - maximum: AtomicUsize, - malformed_cell: bool, - } - - struct TransientCellFixtureModel { - fixture: CellFixtureModel, - target_binding: Mutex>, - failures_remaining: AtomicUsize, - calls: Mutex>, - projector_prompts: Mutex>, - } - - struct TransientOutcomeFixtureModel { - fixture: CellFixtureModel, - failures_remaining: AtomicUsize, - calls: Mutex>, - } - - struct PersonFixtureModel { - invalid_relationship: bool, - } - - #[test] - fn gestalt_state_references_qualify_canonical_ids_exactly_once() { - assert_eq!( - crate::domain::gestalt_state_reference("raincross_households"), - "gestalt:raincross_households" - ); - assert_eq!( - crate::domain::gestalt_state_reference("gestalt:raincross_households"), - "gestalt:raincross_households" - ); - } - - #[test] - fn demand_schema_preserves_all_six_weights_for_strict_providers() { - let mut schema = serde_json::to_value(schema_for!(DemandProjection)).unwrap(); - crate::model_connector::project_strict_responses_schema(&mut schema).unwrap(); - let properties = schema["$defs"]["DemandAxisWeights"]["properties"] - .as_object() - .unwrap(); - assert_eq!( - properties.keys().cloned().collect::>(), - BTreeSet::from([ - "authority".into(), - "economy_role".into(), - "geography".into(), - "ideology".into(), - "information".into(), - "species_body".into(), - ]) - ); - } - - #[test] - fn clock_projection_distinguishes_remaining_time_from_reached_consequence() { - let mut clock = crate::domain::WorldClock { - id: "ferry".into(), - label: "Last protected ferry".into(), - progress: 3, - threshold: 4, - consequence: "the camp is cut off by the storm".into(), - consequence_scope: Default::default(), - }; - assert_eq!( - project_world_clock_pressure(&clock), - "Last protected ferry: progress 3 of 4; 1 step(s) remain before declared consequence: the camp is cut off by the storm" - ); - clock.progress = 4; - assert_eq!( - project_world_clock_pressure(&clock), - "Last protected ferry: threshold reached (4/4); declared consequence: the camp is cut off by the storm" - ); - } - - impl CellFixtureModel { - fn enter(&self) -> ActiveCall<'_> { - let active = self.active.fetch_add(1, Ordering::SeqCst) + 1; - self.maximum.fetch_max(active, Ordering::SeqCst); - ActiveCall(self) - } - } - - struct ActiveCall<'a>(&'a CellFixtureModel); - impl Drop for ActiveCall<'_> { - fn drop(&mut self) { - self.0.active.fetch_sub(1, Ordering::SeqCst); - } - } - - fn fixture_interpreter_subject_ids(request: &ModelStageRequest) -> Result> { - request - .output_schema - .as_ref() - .and_then(|schema| { - schema - .pointer("/properties/command/oneOf/0/properties/decisions/properties") - .and_then(serde_json::Value::as_object) - }) - .map(|properties| properties.keys().cloned().collect::>()) - .filter(|subject_ids| !subject_ids.is_empty()) - .ok_or_else(|| anyhow!("fixture Interpreter lacks a bound subject")) - } - - fn fixture_interpreter_response(request: &ModelStageRequest) -> Result { - let decisions = fixture_interpreter_subject_ids(request)? - .into_iter() - .map(|subject_id| { - let decision = serde_json::json!({"inaction":{ - "subject_id":subject_id.clone(), - "reason":"No justified move this horizon." - }}); - (subject_id, decision) - }) - .collect::>(); - Ok(serde_json::json!({ - "command":{ - "kind":"submit", - "decisions":decisions - } - }) - .to_string()) - } - - fn fixture_actor_interpreter_response(request: &ModelStageRequest) -> Result { - let decisions = fixture_interpreter_subject_ids(request)? - .into_iter() - .map(|subject_id| { - ( - subject_id.clone(), - serde_json::json!({"action":{ - "subject_id":subject_id, - "intent":"build a public ration board at the current location", - "intended_effect":"prepare the ration board locally", - "priority":50, - "state_references":[], - "public_channels":[], - "effects":{"actor_activities":{"prepare":[{ - "target_subject_ids":[], - "location_ids":["center"] - }]}} - }}), - ) - }) - .collect::>(); - Ok(serde_json::json!({ - "command":{ - "kind":"submit", - "decisions":decisions - } - }) - .to_string()) - } - - #[async_trait] - impl ModelPort for CellFixtureModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - let _active = self.enter(); - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - match request.stage.as_str() { - "resolution_demand" => Ok(serde_json::json!({ - "axis_weights": { - "geography":0.25, - "ideology":0.20, - "authority":0.25, - "economy_role":0.15, - "species_body":0.05, - "information":0.10 - }, - "focal_subject_ids":[], - "rationale":"fixture pressure" - }) - .to_string()), - "cell_projector" => { - let subject_ids = request - .output_schema - .as_ref() - .and_then(|schema| { - schema - .pointer("/$defs/CellPerspectiveSegment/properties/subject_id/enum") - }) - .and_then(serde_json::Value::as_array) - .map(|values| { - values - .iter() - .filter_map(serde_json::Value::as_str) - .collect::>() - }) - .filter(|values| !values.is_empty()) - .ok_or_else(|| anyhow!("fixture projector lacks bound subjects"))?; - Ok(serde_json::json!({ - "segments":subject_ids.into_iter().map(|subject_id| serde_json::json!({ - "subject_id":subject_id, - "narrative":"The horizon tightens around this subject's own unresolved choice." - })).collect::>() - }) - .to_string()) - } - "cell_persona" => Ok("Each constituent watches and deliberately holds.".into()), - "cell_interpreter" if self.malformed_cell => Ok("not-json".into()), - "cell_interpreter" => fixture_interpreter_response(request), - stage => Err(anyhow!("unexpected fixture stage {stage}")), - } - } - - fn provider(&self) -> &'static str { - "fixture" - } - } - - #[async_trait] - impl ModelPort for TransientCellFixtureModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.calls - .lock() - .unwrap() - .push((request.stage.clone(), request.snapshot_binding.clone())); - if request.stage == "cell_projector" { - self.projector_prompts - .lock() - .unwrap() - .push(request.lived_stream.clone()); - } - if request.stage == "cell_persona" { - let target_binding = { - let mut target = self.target_binding.lock().unwrap(); - target - .get_or_insert_with(|| request.snapshot_binding.clone()) - .clone() - }; - if request.snapshot_binding == target_binding - && self - .failures_remaining - .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |remaining| { - if remaining > 0 { - Some(remaining - 1) - } else { - None - } - }) - .is_ok() - { - return Err(anyhow!("transient fixture cell failure")); - } - } - self.fixture.run(request).await - } - - fn provider(&self) -> &'static str { - "fixture" - } - } - - #[async_trait] - impl ModelPort for TransientOutcomeFixtureModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - self.calls.lock().unwrap().push(request.stage.clone()); - match request.stage.as_str() { - "cell_persona" => { - Ok("The worker now builds a public ration board at this location.".into()) - } - "cell_interpreter" => fixture_actor_interpreter_response(request), - "cell_effect_verifier" => Ok(serde_json::json!({ - "verdicts":[{ - "action_index":0, - "result":"match", - "findings":[] - }] - }) - .to_string()), - "strategic_outcome_resolver" => { - if self - .failures_remaining - .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |remaining| { - (remaining > 0).then_some(remaining.saturating_sub(1)) - }) - .is_ok() - { - return Err(anyhow!("transient fixture outcome failure")); - } - let (_, payload) = request - .lived_stream - .rsplit_once("OUTCOME_CONTEXT:\n") - .ok_or_else(|| anyhow!("fixture request omitted outcome context"))?; - let context: serde_json::Value = serde_json::from_str(payload)?; - let digest = context["actions"][0]["action_digest"] - .as_str() - .ok_or_else(|| anyhow!("fixture outcome context omitted action digest"))?; - Ok(serde_json::json!({ - "outcomes":[{ - "action_digest":digest, - "band":"mixed", - "effect_kind":"no_material_change", - "supporting_state_references":[], - "reason":"The publication attempt establishes no further durable state." - }] - }) - .to_string()) - } - _ => self.fixture.run(request).await, - } - } - - fn provider(&self) -> &'static str { - "fixture" - } - } - - #[async_trait] - impl ModelPort for PersonFixtureModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - let digest = request - .output_schema - .as_ref() - .and_then(|schema| { - schema.pointer("/$defs/StrategicPersonDraft/properties/action_digest/enum/0") - }) - .and_then(serde_json::Value::as_str) - .ok_or_else(|| anyhow!("person fixture lacks action digest"))?; - let gestalt_id = request - .output_schema - .as_ref() - .and_then(|schema| { - schema.pointer("/$defs/StrategicPersonDraft/properties/gestalt_id/enum/0") - }) - .and_then(serde_json::Value::as_str) - .ok_or_else(|| anyhow!("person fixture lacks Gestalt"))?; - let relationships = if self.invalid_relationship { - serde_json::json!({"unknown-court":"owes a private favor"}) - } else { - serde_json::json!({}) - }; - Ok(serde_json::json!({"proposals":[{ - "action_digest":digest, - "gestalt_id":gestalt_id, - "member_id":"veska-rill", - "name":"Veska Rill", - "goals":["control the grain delegation"], - "obligations":["answer to the river wards"], - "relationships":relationships, - "memories":["the lower road vanished after the dwarven excavation"], - "rationale":"The delegation needs one accountable broker." - }]}) - .to_string()) - } - - fn provider(&self) -> &'static str { - "fixture" - } - } - - #[test] - fn away_budget_waits_and_caps_at_eight() { - let now = Utc::now(); - assert_eq!(due_tick_target(now, now - chrono::Duration::minutes(14)), 0); - assert_eq!(due_tick_target(now, now - chrono::Duration::minutes(59)), 0); - assert_eq!(due_tick_target(now, now - chrono::Duration::hours(1)), 1); - assert_eq!(due_tick_target(now, now - chrono::Duration::hours(30)), 8); - } - - #[test] - fn demand_projection_receives_aggregate_boundaries_not_full_subject_state() { - let mut campaign = crate::resolution::tests::campaign(1_000, 8); - let (focal_candidates, context) = resolution_demand_context(&campaign); - let encoded = serde_json::to_string(&context).unwrap(); - assert_eq!(context["active_subject_count"], 1_000); - assert!(focal_candidates.is_empty()); - assert_eq!(context["facet_value_counts"].as_object().unwrap().len(), 6); - assert!( - encoded.len() < 100_000, - "aggregate context was {} chars", - encoded.len() - ); - assert!(!encoded.contains("permitted_state_references")); - assert!(!encoded.contains("information_channels")); - assert!(!encoded.contains("evidence_receipt_ids")); - - campaign.events.push(crate::domain::Event { - id: "exceptional-pressure".into(), - at: Utc::now(), - kind: "test".into(), - summary: "One faction receives an exceptional warning.".into(), - actor_ids: vec![], - institution_ids: vec!["faction-0007".into()], - gestalt_ids: vec![], - location_ids: vec![], - public_channels: vec![], - }); - let (focal_candidates, context) = resolution_demand_context(&campaign); - assert_eq!(focal_candidates, vec!["faction-0007"]); - assert_eq!(context["focal_candidate_ids"][0], "faction-0007"); - - campaign.events[0].institution_ids = (0..1_000) - .map(|index| format!("faction-{index:04}")) - .collect(); - let (focal_candidates, context) = resolution_demand_context(&campaign); - assert!(focal_candidates.is_empty()); - assert!( - context["focal_candidate_ids"] - .as_array() - .unwrap() - .is_empty() - ); - } - - #[test] - fn canonical_actor_cell_slice_preserves_memory_and_relationship_context() { - let mut campaign = crate::resolution::tests::campaign(0, 1); - let expected_goals = vec!["keep the twelve patients together".into()]; - let expected_memories = vec!["Promised Ash to stay with the twelve.".into()]; - let expected_relationships = - BTreeMap::from([("ash".into(), "trusted with a responsibility".into())]); - { - let actor = campaign.actors.get_mut("player").unwrap(); - actor.goals = expected_goals.clone(); - actor.memories = expected_memories.clone(); - actor.relationships = expected_relationships.clone(); - } - - let slice = constituent_slice(&campaign, "player").unwrap(); - assert_eq!(slice.goals, expected_goals); - assert_eq!(slice.memories, expected_memories); - assert_eq!(slice.relationships, expected_relationships); - } - - #[test] - fn actor_slice_names_reachable_places_and_a_target_already_at_the_current_location() { - use crate::domain::{ActorState, Location, Route}; - - let mut campaign = crate::resolution::tests::campaign(0, 1); - campaign.actors.insert( - "reed".into(), - ActorState { - id: "reed".into(), - name: "Reed".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!["keep the twelve together".into()], - memories: vec![], - }, - ); - campaign.locations.insert( - "garrison".into(), - Location { - id: "garrison".into(), - name: "Garrison Outpost".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - ); - campaign.locations.get_mut("center").unwrap().routes.insert( - "garrison".into(), - Route { - destination_id: "garrison".into(), - distance: "3 km".into(), - travel_minutes: 20, - }, - ); - crate::resolution::ensure_agency_profiles(&mut campaign); - - let slice = constituent_slice(&campaign, "player").unwrap(); - assert_eq!( - slice - .reachable_destinations - .get("garrison") - .map(String::as_str), - Some("Garrison Outpost") - ); - let reed = slice.activity_targets.get("reed").unwrap(); - assert_eq!(reed.name, "Reed"); - assert_eq!( - reed.locations.get("center").map(String::as_str), - Some("Center") - ); - assert!(!reed.locations.contains_key("garrison")); - } - - #[test] - fn materialized_gestalt_member_is_projected_as_an_actor_target() { - use crate::domain::{ActorState, GestaltMemberDelta, GestaltPersonaState}; - - let mut campaign = crate::resolution::tests::campaign(0, 2); - 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( - "sable".into(), - GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: "sable".into(), - gestalt_id: "refugees".into(), - version: 1, - name: "Sable".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:sable".into()), - last_relevant_revision: 0, - relevance_lease_until_revision: 5, - }, - ); - campaign.actors.insert( - "member:sable".into(), - ActorState { - id: "member:sable".into(), - name: "Sable".into(), - location_id: "center".into(), - capabilities: BTreeSet::from(["route scouting".into()]), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec![], - memories: vec![], - }, - ); - crate::resolution::ensure_agency_profiles(&mut campaign); - - let slice = constituent_slice(&campaign, "player").unwrap(); - let sable = slice.activity_targets.get("member:sable").unwrap(); - assert_eq!(sable.name, "Sable"); - assert_eq!( - sable.locations.get("center").map(String::as_str), - Some("Center") - ); - } - - #[test] - fn cell_slice_rotates_exact_member_decision_owners_without_hiding_the_cell() { - use crate::domain::*; - let mut campaign = crate::resolution::tests::campaign(0, 1); - campaign.locations.insert( - "unsliced".into(), - Location { - id: "unsliced".into(), - name: "Remote Unsliced Court".into(), - container_id: None, - routes: BTreeMap::new(), - persistent_features: vec![], - }, - ); - let gestalt = |id: &str, name: &str| GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: id.into(), - name: name.into(), - version: 0, - home_location_id: "center".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec![], - pressures: vec![], - }; - campaign - .gestalts - .insert("refugees".into(), gestalt("refugees", "Refugees")); - campaign - .gestalts - .insert("neighbors".into(), gestalt("neighbors", "Neighbors")); - let member = |id: &str, player_relationship: bool| GestaltMemberDelta { - schema: "ghostlight.gestalt_member_delta.v1".into(), - id: id.into(), - gestalt_id: "refugees".into(), - version: 1, - name: id.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: if player_relationship { - BTreeMap::from([("player".into(), "trusted rescuer".into())]) - } else { - BTreeMap::new() - }, - goals: vec!["find a home".into()], - memories: vec![], - last_location_id: Some("center".into()), - materialized_actor_id: None, - last_relevant_revision: 1, - relevance_lease_until_revision: 0, - }; - campaign - .gestalt_members - .insert("mira".into(), member("mira", true)); - campaign - .gestalt_members - .insert("other".into(), member("other", false)); - for member_id in ["third", "fourth", "fifth", "sixth", "seventh"] { - campaign - .gestalt_members - .insert(member_id.into(), member(member_id, false)); - } - campaign.strategic_tick_count = 1; - crate::resolution::ensure_agency_profiles(&mut campaign); - campaign.agency_relations.insert( - "migration".into(), - AgencyRelation { - schema: "ghostlight.agency_relation.v1".into(), - id: "migration".into(), - from_subject_id: "refugees".into(), - to_subject_id: "neighbors".into(), - kind: AgencyRelationKind::Migration, - strength: 90, - active: true, - evidence_receipt_ids: vec![], - }, - ); - let cover = crate::resolution::plan_cover( - &campaign, - crate::resolution::default_demand(&campaign, "resettlement"), - ) - .unwrap(); - let slice = cell_slice(&campaign, &cover, &cover.cells[0]).unwrap(); - assert_eq!( - slice.canonical_locations.get("center").map(String::as_str), - Some("Center") - ); - assert!(!slice.canonical_locations.contains_key("unsliced")); - assert_eq!(slice.member_exceptions.len(), 1); - assert_eq!(slice.member_exceptions[0].member_id, "mira"); - assert!(slice.decision_owner_ids.contains("member:mira")); - assert!(slice.decision_owner_ids.contains("neighbors")); - assert!(!slice.decision_owner_ids.contains("refugees")); - assert_eq!( - slice.member_exceptions[0] - .migration_destinations - .get("neighbors") - .map(|destination| destination.location_id.as_str()), - Some("center") - ); - assert_eq!( - slice.member_exceptions[0] - .migration_destinations - .get("neighbors") - .map(|destination| destination.population_name.as_str()), - Some("Neighbors") - ); - assert!( - slice.member_exceptions[0] - .permitted_state_references - .contains("member:mira") - ); - assert!( - slice.member_exceptions[0] - .activity_targets - .contains_key("refugees") - ); - assert_eq!( - slice.member_exceptions[0] - .activity_targets - .get("refugees") - .map(|target| target.name.as_str()), - Some("Refugees") - ); - assert_eq!( - slice.member_exceptions[0] - .activity_targets - .get("refugees") - .and_then(|target| target.locations.get("center")) - .map(String::as_str), - Some("Center") - ); - let selected_member_ids = slice - .member_exceptions - .iter() - .map(|member| member.subject_id.clone()) - .collect::>(); - assert!(selected_member_ids.contains("member:mira")); - assert!(slice.constituents.iter().all(|constituent| { - constituent - .activity_targets - .keys() - .filter(|target| target.starts_with("member:")) - .all(|target| selected_member_ids.contains(target)) - })); - assert!(slice.member_exceptions.iter().all(|member| { - member - .activity_targets - .keys() - .filter(|target| target.starts_with("member:")) - .all(|target| selected_member_ids.contains(target)) - })); - assert!( - !serde_json::to_string(&slice) - .unwrap() - .contains("member:seventh") - ); - assert!( - !serde_json::to_string(&slice) - .unwrap() - .contains("private dock code") - ); - - let mut focused_cell = cover.cells[0].clone(); - focused_cell.detail_focus_subject_id = Some("refugees".into()); - let focused = cell_slice(&campaign, &cover, &focused_cell).unwrap(); - assert!(focused.decision_owner_ids.contains("refugees")); - assert!(!focused.decision_owner_ids.contains("member:mira")); - - campaign.agency_relations.clear(); - let local_only_cover = crate::resolution::plan_cover( - &campaign, - crate::resolution::default_demand(&campaign, "ordinary local work"), - ) - .unwrap(); - let local_only = - cell_slice(&campaign, &local_only_cover, &local_only_cover.cells[0]).unwrap(); - assert!( - local_only - .member_exceptions - .iter() - .any(|member| member.member_id == "mira" - && member.migration_destinations.is_empty() - && member.activity_targets.contains_key("refugees")) - ); - } - - #[test] - fn institution_slice_does_not_disguise_committed_posture_as_pressure() { - let campaign = crate::resolution::tests::campaign(1, 1); - let institution = &campaign.institutions["faction-0000"]; - let slice = constituent_slice(&campaign, "faction-0000").unwrap(); - assert_eq!( - slice.current_posture.as_deref(), - Some(institution.posture.as_str()) - ); - assert!(slice.pressures.is_empty()); - } - - #[test] - fn arena_event_projection_preserves_exact_viewers_including_named_members() { - use crate::domain::*; - let mut campaign = crate::resolution::tests::campaign(2, 1); - campaign - .agency_profiles - .get_mut("faction-0000") - .unwrap() - .location_ids = BTreeSet::from(["east".into()]); - let west = campaign.agency_profiles.get_mut("faction-0001").unwrap(); - west.location_ids = BTreeSet::from(["west".into()]); - west.information_channels.insert("west-wire".into()); - campaign.events = vec![ - Event { - id: "direct-east".into(), - at: Utc::now(), - kind: "test".into(), - summary: "East receives a private order.".into(), - actor_ids: vec![], - institution_ids: vec!["faction-0000".into()], - gestalt_ids: vec![], - location_ids: vec![], - public_channels: vec![], - }, - Event { - id: "west-wire".into(), - at: Utc::now(), - kind: "test".into(), - summary: "A warning travels on the west wire.".into(), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec![], - public_channels: vec!["west-wire".into()], - }, - Event { - id: "mira-witnessed".into(), - at: Utc::now(), - kind: "test".into(), - summary: "Mira witnesses the departure.".into(), - actor_ids: vec!["member:mira".into()], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec![], - public_channels: vec![], - }, - Event { - id: "unseen".into(), - at: Utc::now(), - kind: "test".into(), - summary: "Nobody in this arena can know this.".into(), - actor_ids: vec![], - institution_ids: vec![], - gestalt_ids: vec![], - location_ids: vec!["far-away".into()], - public_channels: vec!["sealed-channel".into()], - }, - ]; - let constituents = ["faction-0000", "faction-0001"] - .iter() - .map(|id| constituent_slice(&campaign, id).unwrap()) - .collect::>(); - let members = vec![CellMemberSlice { - subject_id: "member:mira".into(), - member_id: "mira".into(), - name: "Mira".into(), - source_gestalt_id: "refugees".into(), - source_location_id: "east".into(), - knowledge: BTreeSet::new(), - capabilities: BTreeSet::new(), - resources: BTreeSet::new(), - information_channels: BTreeSet::from(["refugee-wire".into()]), - permitted_state_references: BTreeSet::new(), - migration_destinations: BTreeMap::new(), - activity_targets: BTreeMap::new(), - goals: vec![], - pressures: vec![], - relationships: BTreeMap::new(), - memories: vec![], - }]; - - let events = cell_perceived_events(&campaign, &constituents, &members) - .into_iter() - .map(|event| (event.event_id, event.perceived_by_subject_ids)) - .collect::>(); - assert_eq!( - events["direct-east"], - BTreeSet::from(["faction-0000".into()]) - ); - assert_eq!(events["west-wire"], BTreeSet::from(["faction-0001".into()])); - assert_eq!( - events["mira-witnessed"], - BTreeSet::from(["member:mira".into()]) - ); - assert!(!events.contains_key("unseen")); - } - - #[tokio::test] - async fn every_selected_cell_runs_one_membrane_pipeline() { - let mut campaign = crate::resolution::tests::campaign(6, 2); - campaign.resolution_policy.provider_parallelism = 2; - let model = Arc::new(CellFixtureModel { - active: AtomicUsize::new(0), - maximum: AtomicUsize::new(0), - malformed_cell: false, - }); - let output = propose_resolution_wave(model.clone(), Arc::new(AllowAllPermit), &campaign) - .await - .unwrap(); - assert_eq!(output.wave.cover.cells.len(), 2); - assert_eq!(output.wave.appraisals.len(), 2); - assert_eq!(output.stages.len(), 7); - assert_eq!( - output.wave.model_receipt_hashes.len(), - output - .wave - .model_receipt_hashes - .iter() - .collect::>() - .len() - ); - let mut repeated_stage = output.stages.clone(); - repeated_stage.push(output.stages[0].clone()); - assert_eq!( - distinct_model_receipt_hashes(&repeated_stage), - output.wave.model_receipt_hashes - ); - assert!(model.maximum.load(Ordering::SeqCst) <= 2); - assert!( - output - .private_cell_traces - .iter() - .all(|trace| !trace.terminal_pipeline_receipt_hashes.is_empty()) - ); - validate_and_resolve_wave(&campaign, &output.wave).unwrap(); - } - - #[tokio::test] - async fn cell_failure_is_terminal_and_does_not_replay_the_membrane() { - let mut campaign = crate::resolution::tests::campaign(6, 2); - campaign.resolution_policy.provider_parallelism = 2; - let model = Arc::new(TransientCellFixtureModel { - fixture: CellFixtureModel { - active: AtomicUsize::new(0), - maximum: AtomicUsize::new(0), - malformed_cell: false, - }, - target_binding: Mutex::new(None), - failures_remaining: AtomicUsize::new(4), - calls: Mutex::new(Vec::new()), - projector_prompts: Mutex::new(Vec::new()), - }); - - let error = - match propose_resolution_wave(model.clone(), Arc::new(AllowAllPermit), &campaign).await - { - Ok(_) => panic!("the scheduler replayed a failed cell membrane"), - Err(error) => error, - }; - let failure = error - .downcast_ref::() - .expect("cell failure must retain pipeline receipts"); - - assert_eq!(failure.pipeline_errors.len(), 1); - assert!(failure.pipeline_errors[0].contains( - "cell Persona model stage failed: model stage cell_persona transport failed on both permitted attempts against the same snapshot" - )); - assert_eq!( - model.failures_remaining.load(Ordering::SeqCst), - 2, - "the provider may perform its bounded transport retry, but the scheduler must not replay Projector and Persona" - ); - assert!(model.fixture.maximum.load(Ordering::SeqCst) <= 2); - } - - #[tokio::test] - async fn partial_wave_checkpoint_resumes_only_failed_cells() { - let mut campaign = crate::resolution::tests::campaign(6, 2); - campaign.resolution_policy.provider_parallelism = 2; - let model = Arc::new(TransientCellFixtureModel { - fixture: CellFixtureModel { - active: AtomicUsize::new(0), - maximum: AtomicUsize::new(0), - malformed_cell: false, - }, - target_binding: Mutex::new(None), - failures_remaining: AtomicUsize::new(2), - calls: Mutex::new(Vec::new()), - projector_prompts: Mutex::new(Vec::new()), - }); - let contract = CampaignContract { - campaign_name: "POLICY-SIGNAL-EMBER".into(), - ..Default::default() - }; - let boundaries = vec![AggregatedBoundary { - normalized_topic: "policy-signal-ash".into(), - display_topic: "POLICY-SIGNAL-ASH".into(), - level: crate::session_zero::BoundaryLevel::Veil, - }]; - - let error = match propose_resolution_wave_with_policy( - model.clone(), - Arc::new(AllowAllPermit), - &campaign, - Some(&contract), - &boundaries, - ) - .await - { - Ok(_) => panic!("one exact cell must exhaust its bounded transport attempts"), - Err(error) => error, - }; - let failure = error - .downcast_ref::() - .expect("cell failure must publish a resumable wave checkpoint"); - let checkpoint = failure.checkpoint.clone().expect("checkpoint"); - assert_eq!(checkpoint.completed_cells.len(), 1); - assert_eq!(checkpoint.failed_cell_ids.len(), 1); - let mut overlapping = checkpoint.clone(); - overlapping - .failed_cell_ids - .insert(overlapping.completed_cells[0].cell_id.clone()); - let overlapping = seal_resolution_wave_checkpoint(overlapping).unwrap(); - let calls_before_rejection = model.calls.lock().unwrap().len(); - let overlap_error = match resume_resolution_wave( - model.clone(), - Arc::new(AllowAllPermit), - &campaign, - overlapping, - ) - .await - { - Ok(_) => panic!("overlapping checkpoint authority must fail closed"), - Err(error) => error, - }; - assert!(overlap_error.to_string().contains("overlapping")); - assert_eq!(model.calls.lock().unwrap().len(), calls_before_rejection); - let preserved_receipts = checkpoint.completed_cells[0] - .terminal - .stage_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - let checkpoint: ResolutionWaveCheckpoint = - serde_json::from_slice(&serde_json::to_vec(&checkpoint).unwrap()).unwrap(); - - let output = resume_resolution_wave( - model.clone(), - Arc::new(AllowAllPermit), - &campaign, - checkpoint, - ) - .await - .unwrap(); - assert_eq!(output.wave.appraisals.len(), 2); - assert!( - preserved_receipts - .is_subset(&output.wave.model_receipt_hashes.iter().cloned().collect()) - ); - let calls = model.calls.lock().unwrap(); - let count = |stage: &str| calls.iter().filter(|(called, _)| called == stage).count(); - assert_eq!(count("resolution_demand"), 1, "resume replanned the wave"); - assert_eq!( - count("cell_projector"), - 3, - "resume replayed a successful cell" - ); - assert_eq!( - count("cell_persona"), - 4, - "resume replayed a successful cell" - ); - assert_eq!( - count("cell_interpreter"), - 2, - "resume replayed a successful cell" - ); - assert!( - model - .projector_prompts - .lock() - .unwrap() - .iter() - .all(|prompt| { - prompt.contains("POLICY-SIGNAL-EMBER") && prompt.contains("POLICY-SIGNAL-ASH") - }) - ); - validate_and_resolve_wave(&campaign, &output.wave).unwrap(); - } - - #[tokio::test] - async fn outcome_failure_resume_reuses_every_completed_cell_terminal() { - use crate::domain::{ActorState, AgencySubjectKind}; - let mut campaign = crate::resolution::tests::campaign(1, 1); - campaign.resolution_policy.provider_parallelism = 1; - let mut worker_profile = campaign.agency_profiles["faction-0000"].clone(); - campaign - .agency_profiles - .get_mut("faction-0000") - .unwrap() - .simulation_eligible = false; - worker_profile.subject_id = "fixture-worker".into(); - worker_profile.subject_kind = AgencySubjectKind::Actor; - worker_profile.location_ids = BTreeSet::from(["center".into()]); - worker_profile.active_leaf = true; - worker_profile.simulation_eligible = true; - campaign - .agency_profiles - .insert(worker_profile.subject_id.clone(), worker_profile); - campaign.actors.insert( - "fixture-worker".into(), - ActorState { - id: "fixture-worker".into(), - name: "Fixture Worker".into(), - location_id: "center".into(), - capabilities: BTreeSet::from(["carpentry".into()]), - knowledge: BTreeSet::new(), - equipment: BTreeSet::new(), - conditions: BTreeSet::new(), - obligations: BTreeSet::new(), - relationships: BTreeMap::new(), - goals: vec!["make rationing legible".into()], - memories: Vec::new(), - }, - ); - let model = Arc::new(TransientOutcomeFixtureModel { - fixture: CellFixtureModel { - active: AtomicUsize::new(0), - maximum: AtomicUsize::new(0), - malformed_cell: false, - }, - failures_remaining: AtomicUsize::new(2), - calls: Mutex::new(Vec::new()), - }); - - let error = match propose_resolution_wave( - model.clone(), - Arc::new(AllowAllPermit), - &campaign, - ) - .await - { - Ok(output) => panic!( - "the first downstream outcome request must exhaust transport; calls={:?}; appraisals={:?}", - model.calls.lock().unwrap(), - output.wave.appraisals - ), - Err(error) => error, - }; - let checkpoint = error - .downcast_ref::() - .and_then(|failure| failure.checkpoint.clone()) - .expect("downstream failure must preserve a complete cell checkpoint"); - assert!(checkpoint.failed_cell_ids.is_empty()); - assert_eq!(checkpoint.completed_cells.len(), 1); - let terminal_receipts = checkpoint.completed_cells[0] - .terminal - .stage_receipts - .iter() - .map(|receipt| receipt.storage_key().to_owned()) - .collect::>(); - let calls_before_resume = model.calls.lock().unwrap().clone(); - - let output = resume_resolution_wave( - model.clone(), - Arc::new(AllowAllPermit), - &campaign, - checkpoint, - ) - .await - .unwrap(); - let calls_after_resume = model.calls.lock().unwrap().clone(); - for stage in [ - "resolution_demand", - "cell_projector", - "cell_persona", - "cell_interpreter", - "cell_effect_verifier", - ] { - assert_eq!( - calls_before_resume - .iter() - .filter(|called| called.as_str() == stage) - .count(), - calls_after_resume - .iter() - .filter(|called| called.as_str() == stage) - .count(), - "downstream resume replayed {stage}" - ); - } - assert!( - terminal_receipts - .is_subset(&output.wave.model_receipt_hashes.iter().cloned().collect()) - ); - validate_and_resolve_wave(&campaign, &output.wave).unwrap(); - } - - #[tokio::test] - async fn two_hundred_cell_wave_dispatches_in_parallel_under_one_provider_gate() { - let mut campaign = crate::resolution::tests::campaign(1_000, 200); - campaign.resolution_policy.provider_parallelism = 7; - let model = Arc::new(CellFixtureModel { - active: AtomicUsize::new(0), - maximum: AtomicUsize::new(0), - malformed_cell: false, - }); - let output = propose_resolution_wave(model.clone(), Arc::new(AllowAllPermit), &campaign) - .await - .unwrap(); - assert_eq!(output.wave.cover.cells.len(), 200); - assert_eq!(output.wave.appraisals.len(), 200); - assert_eq!(output.stages.len(), 601); - let maximum = model.maximum.load(Ordering::SeqCst); - assert!(maximum > 1, "the wave never dispatched concurrently"); - assert!( - maximum <= 7, - "provider concurrency escaped its gate: {maximum}" - ); - validate_and_resolve_wave(&campaign, &output.wave).unwrap(); - } - - #[tokio::test] - async fn strategic_gestalt_pressure_can_propose_one_action_bound_named_person() { - use crate::domain::{AgencySubjectKind, GestaltPersonaState, StrategicCellEffect}; - let mut campaign = crate::resolution::tests::campaign(1, 1); - let mut profile = campaign.agency_profiles["faction-0000"].clone(); - profile.subject_id = "river-wards".into(); - profile.subject_kind = AgencySubjectKind::Gestalt; - profile.location_ids = BTreeSet::from(["center".into()]); - let location_id = profile.location_ids.iter().next().unwrap().clone(); - campaign - .agency_profiles - .insert(profile.subject_id.clone(), profile); - campaign.gestalts.insert( - "river-wards".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "river-wards".into(), - name: "River Wards".into(), - version: 0, - home_location_id: location_id.clone(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::from(["grain barges".into()]), - goals: vec!["keep the river wards fed".into()], - pressures: vec!["dwarven excavation diverted the lower road".into()], - }, - ); - let action = crate::domain::CellActionProposal { - subject_id: "river-wards".into(), - intent: "Send a grain delegation around the broken lower road.".into(), - intended_effect: "Negotiate a politically accountable detour.".into(), - priority: 80, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::Gestalt { - gestalt_id: "river-wards".into(), - pressure_additions: vec!["the delegation needs an accountable broker".into()], - pressure_resolutions: vec![], - }], - }; - let digest = cell_action_digest(&action).unwrap(); - let institution_action = crate::domain::CellActionProposal { - subject_id: "faction-0000".into(), - intent: "Publish the existing ration posture.".into(), - intended_effect: "Keep the institution legible.".into(), - priority: 20, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::Institution { - institution_id: "faction-0000".into(), - posture: "publishing ration posture".into(), - location_ids: vec![], - }], - }; - let selected_actions = vec![action, institution_action]; - let (proposals, stages) = propose_strategic_individuation( - &PersonFixtureModel { - invalid_relationship: false, - }, - &campaign, - &selected_actions, - ) - .await; - assert_eq!(proposals.len(), 1); - assert_eq!(stages.len(), 1); - assert_eq!(proposals[0].action_digest, digest); - assert_eq!(proposals[0].individuation.gestalt_id, "river-wards"); - assert_eq!(proposals[0].individuation.location_id, location_id); - assert_eq!(proposals[0].individuation.member.name, "Veska Rill"); - assert_eq!(proposals[0].individuation.expected_gestalt_version, 0); - let candidate_digests = - strategic_individuation_candidate_digests(&campaign, &selected_actions); - assert_eq!(candidate_digests, vec![digest]); - let proposal_digest = strategic_individuation_proposal_digest(&proposals[0]).unwrap(); - assert_eq!( - stages[0].receipt.snapshot_binding, - strategic_individuation_binding(&campaign, &candidate_digests, Some(&proposal_digest),) - ); - } - - #[tokio::test] - async fn invalid_strategic_person_is_rejected_before_wave_admission() { - use crate::domain::{AgencySubjectKind, GestaltPersonaState, StrategicCellEffect}; - let mut campaign = crate::resolution::tests::campaign(1, 1); - let mut profile = campaign.agency_profiles["faction-0000"].clone(); - profile.subject_id = "river-wards".into(); - profile.subject_kind = AgencySubjectKind::Gestalt; - profile.location_ids = BTreeSet::from(["center".into()]); - campaign - .agency_profiles - .insert(profile.subject_id.clone(), profile); - campaign.gestalts.insert( - "river-wards".into(), - GestaltPersonaState { - schema: "ghostlight.gestalt_persona_state.v1".into(), - id: "river-wards".into(), - name: "River Wards".into(), - version: 0, - home_location_id: "center".into(), - shared_capabilities: BTreeSet::new(), - shared_knowledge: BTreeSet::new(), - resources: BTreeSet::new(), - goals: vec!["keep the wards fed".into()], - pressures: vec!["the lower road failed".into()], - }, - ); - let action = crate::domain::CellActionProposal { - subject_id: "river-wards".into(), - intent: "Send a delegation.".into(), - intended_effect: "Find an accountable route broker.".into(), - priority: 80, - state_references: vec![], - public_channels: vec![], - effects: vec![StrategicCellEffect::Gestalt { - gestalt_id: "river-wards".into(), - pressure_additions: vec!["a broker must answer publicly".into()], - pressure_resolutions: vec![], - }], - }; - let (proposals, stages) = propose_strategic_individuation( - &PersonFixtureModel { - invalid_relationship: true, - }, - &campaign, - &[action], - ) - .await; - assert!(proposals.is_empty()); - assert_eq!(stages.len(), 1); - assert_eq!(stages[0].receipt.validation_result, "semantic_invalid"); - assert!( - stages[0] - .receipt - .local_validation_error - .as_deref() - .is_some_and(|error| error.contains("exact Gestalt action authority")) - ); - } - - #[tokio::test] - async fn one_malformed_cell_aborts_the_whole_wave() { - let campaign = crate::resolution::tests::campaign(6, 2); - let before = campaign.clone(); - let model = Arc::new(CellFixtureModel { - active: AtomicUsize::new(0), - maximum: AtomicUsize::new(0), - malformed_cell: true, - }); - let error = match propose_resolution_wave(model, Arc::new(AllowAllPermit), &campaign).await - { - Ok(_) => panic!("permanently malformed cells must reject the wave"), - Err(error) => error, - }; - let failure = error - .downcast_ref::() - .expect("terminal cell failure must preserve wave failure evidence"); - assert!(!failure.pipeline_errors.is_empty()); - assert!( - failure - .pipeline_errors - .iter() - .all(|error| error.contains("pipeline failed: cell Interpreter agent failed")) - ); - assert!(failure.stage_receipts.len() >= 5); - assert!( - failure - .stage_receipts - .iter() - .any(|receipt| receipt.stage == "resolution_demand") - ); - assert_eq!( - failure - .stage_receipts - .iter() - .filter(|receipt| receipt.stage == "cell_projector") - .count(), - 2, - "the scheduler must not replay a completed Projector" - ); - assert_eq!( - failure - .stage_receipts - .iter() - .filter(|receipt| receipt.stage == "cell_persona") - .count(), - 2, - "the scheduler must not replay a completed Persona" - ); - assert_eq!(campaign, before); - } -} diff --git a/crates/ghostlight-dungeon/src/session_zero.rs b/crates/ghostlight-dungeon/src/session_zero.rs deleted file mode 100644 index 26cdadc..0000000 --- a/crates/ghostlight-dungeon/src/session_zero.rs +++ /dev/null @@ -1,7607 +0,0 @@ -use crate::{ - domain::{ActorState, Campaign, EvidenceCoverage, WorldCompilePreview}, - model::{ModelPort, ModelStageReceipt, ModelStageRequest, run_validated_stage}, - persistence::CampaignStore, -}; -use anyhow::{Result, anyhow}; -use chrono::{DateTime, Duration, Utc}; -use schemars::{JsonSchema, generate::SchemaSettings, schema_for}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::{ - collections::{BTreeMap, BTreeSet}, - fs, - path::{Path, PathBuf}, - sync::Arc, -}; -use tokio::sync::{RwLock, mpsc, oneshot}; -use uuid::Uuid; - -pub const MAX_SESSION_ZERO_MEMBERS: usize = 8; -pub const FIXTURE_CELL_ALLOWANCE: u8 = 8; -pub const OPERATOR_CELL_CEILING: u8 = crate::resolution::MAX_ACTIVE_CELL_BUDGET; - -pub trait EntitlementPort: Send + Sync { - fn persona_cell_allowance(&self, account_hash: &str) -> u8; -} - -#[derive(Default)] -pub struct FixtureEntitlementPort; - -impl EntitlementPort for FixtureEntitlementPort { - fn persona_cell_allowance(&self, _account_hash: &str) -> u8 { - FIXTURE_CELL_ALLOWANCE - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum SessionZeroStatus { - Drafting, - RosterLocked, - Compiling, - Review, - Published, - Archived, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum SessionZeroChannelKind { - SharedTable, - PrivateDm, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum SessionZeroSpeakerKind { - Player, - Dm, - System, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)] -#[serde(rename_all = "snake_case")] -pub enum BoundaryLevel { - AskFirst, - Veil, - Line, -} - -impl BoundaryLevel { - fn severity(&self) -> u8 { - match self { - Self::AskFirst => 1, - Self::Veil => 2, - Self::Line => 3, - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct ContentBoundary { - pub schema: String, - pub id: String, - pub owner_member_id: String, - pub topic: String, - pub normalized_topic: String, - pub level: BoundaryLevel, - pub created_at: DateTime, - pub updated_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct AggregatedBoundary { - pub normalized_topic: String, - pub display_topic: String, - pub level: BoundaryLevel, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct ActiveContractBoundaryPolicy { - pub schema: String, - pub campaign_id: Uuid, - pub review_session_zero_id: Uuid, - pub aggregate_boundaries: Vec, - pub updated_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] -pub struct CampaignContract { - pub schema: String, - pub vault_provider: String, - pub campaign_name: String, - pub premise: String, - pub canon_horizon: String, - pub starting_where: String, - pub starting_when: String, - pub starting_pressure: String, - pub desired_goal: String, - pub tone: Vec, - pub themes: Vec, - pub pacing: String, - pub consequence_style: String, - pub narrative_focus: String, - pub party_bonds: Vec, - pub internal_tension: String, - pub dm_style: String, - pub time_advance_policy: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct ExtraordinaryPermission { - pub schema: String, - pub id: String, - pub actor_id: String, - pub name: String, - pub reliable_scope: String, - pub prerequisites: Vec, - pub costs: Vec, - pub limits: Vec, - #[serde(default)] - pub opposition: Vec, - pub exposure: Vec, - pub effect_ceiling: String, - pub evidence_receipt_ids: Vec, - pub branch_local: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] -pub struct CharacterDraft { - pub schema: String, - pub member_id: String, - pub actor_id: String, - pub name: String, - pub public_premise: String, - pub private_history: Vec, - pub secrets: Vec, - pub capabilities: Vec, - pub knowledge: Vec, - pub equipment: Vec, - pub relationships: BTreeMap, - pub obligations: Vec, - pub vulnerabilities: Vec, - pub goals: Vec, - pub extraordinary_permissions: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct SessionZeroMember { - pub schema: String, - pub id: String, - #[schemars(skip)] - pub account_hash: String, - pub display_name: String, - pub is_host: bool, - pub active: bool, - pub cell_allowance: u8, - pub joined_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct SessionZeroChannel { - pub schema: String, - pub id: String, - pub kind: SessionZeroChannelKind, - pub member_id: Option, - pub revision: u64, - pub message_ids: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct SessionZeroMessage { - pub schema: String, - pub id: String, - pub channel_id: String, - pub author_member_id: Option, - pub speaker: SessionZeroSpeakerKind, - pub text: String, - pub session_revision: u64, - pub created_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct SessionZeroDecision { - pub schema: String, - pub id: String, - pub owner_member_id: Option, - pub prompt: String, - pub proposed_resolution: String, - #[serde(default)] - pub proposed_extraordinary_permission: Option, - #[serde(default)] - pub proposed_contract_patch: Option, - #[serde(default)] - pub proposed_character_patch: Option, - #[serde(default)] - pub evidence_receipt_ids: Vec, - #[serde(default)] - pub pending_counter: Option, - pub material: bool, - pub resolved: bool, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum SessionZeroDecisionResolution { - Accept, - Decline, - Counter, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct SessionZeroApproval { - pub schema: String, - pub member_id: String, - pub shared_digest: String, - pub character_digest: String, - #[serde(default)] - pub world_preview_digest: String, - pub approved_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct SessionZeroInvite { - pub schema: String, - pub id: String, - #[schemars(skip)] - pub token_hash: String, - pub expires_at: DateTime, - pub consumed_by_member_id: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct CampaignDmPersona { - pub schema: String, - pub id: String, - pub name: String, - pub voice: String, - pub shared_memories: Vec, - pub private_member_memories: BTreeMap>, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct CampaignMember { - pub member_id: String, - #[schemars(skip)] - pub account_hash: String, - pub display_name: String, - pub actor_id: String, - pub is_host: bool, - pub active: bool, - pub cell_allowance: u8, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct CampaignMembership { - pub schema: String, - pub campaign_id: Uuid, - pub governance_epoch: u64, - pub host_member_id: String, - pub members: BTreeMap, - pub extraordinary_permissions: BTreeMap>, -} - -impl CampaignMembership { - pub fn member_for_account(&self, account_hash: &str) -> Option<&CampaignMember> { - self.members - .values() - .find(|member| member.active && member.account_hash == account_hash) - } - - pub fn controlled_actor_ids(&self) -> BTreeSet { - self.members - .values() - .filter(|member| member.active) - .map(|member| member.actor_id.clone()) - .collect() - } - - pub fn pooled_cell_allowance(&self) -> u8 { - self.members - .values() - .filter(|member| member.active) - .fold(0_u8, |total, member| { - total.saturating_add(member.cell_allowance) - }) - .min(OPERATOR_CELL_CEILING) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct CampaignGovernance { - pub schema: String, - pub campaign_id: Uuid, - pub governance_epoch: u64, - pub time_advance_policy: String, - pub pooled_cell_ceiling: u8, - pub cooperative_shared_scene_only: bool, - pub pvp_enabled: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct TimeAdvanceProposal { - pub schema: String, - pub id: String, - pub campaign_id: Uuid, - pub expected_world_revision: u64, - pub minutes: u32, - pub proposer_member_id: String, - pub approvals: BTreeSet, - pub committed: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct GroupTravelProposal { - pub schema: String, - pub id: String, - pub campaign_id: Uuid, - pub expected_world_revision: u64, - pub origin_location_id: String, - pub destination_location_id: String, - pub travel_minutes: u32, - pub proposer_member_id: String, - pub approvals: BTreeSet, - pub committed: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct CellBudgetProposal { - pub schema: String, - pub id: String, - pub campaign_id: Uuid, - pub expected_world_revision: u64, - pub expected_resolution_epoch: u64, - pub active_cell_budget: u8, - pub proposer_member_id: String, - pub approvals: BTreeSet, - pub committed: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct PublishedSessionZeroSeed { - pub schema: String, - pub session_zero_id: Uuid, - pub approved_seed_digest: String, - pub contract: CampaignContract, - pub membership: CampaignMembership, - pub governance: CampaignGovernance, - pub dm_persona: CampaignDmPersona, - pub approvals: Vec, - pub approved_brief: ApprovedCampaignBrief, - #[serde(default)] - pub approved_world_preview_digest: String, - #[serde(default)] - pub approved_evidence_gaps: Vec, - #[serde(default)] - pub approved_branch_assumptions: Vec, - #[serde(default)] - pub boundaries: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct ApprovedCampaignBrief { - pub schema: String, - pub session_zero_id: Uuid, - pub host_member_id: String, - pub contract: CampaignContract, - pub aggregate_boundaries: Vec, - pub characters: Vec, - pub member_actor_ids: BTreeMap, - pub shared_digest: String, - pub character_digests: BTreeMap, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] -pub struct CampaignContractPatch { - pub premise: Option, - pub canon_horizon: Option, - pub starting_where: Option, - pub starting_when: Option, - pub starting_pressure: Option, - pub desired_goal: Option, - pub tone: Option>, - pub themes: Option>, - pub pacing: Option, - pub consequence_style: Option, - pub narrative_focus: Option, - pub party_bonds: Option>, - pub internal_tension: Option, - pub dm_style: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] -pub struct CharacterDraftPatch { - pub name: Option, - pub public_premise: Option, - pub private_history_add: Vec, - #[serde(default)] - pub private_history_remove: Vec, - pub secrets_add: Vec, - #[serde(default)] - pub secrets_remove: Vec, - pub capabilities_add: Vec, - #[serde(default)] - pub capabilities_remove: Vec, - pub knowledge_add: Vec, - #[serde(default)] - pub knowledge_remove: Vec, - pub equipment_add: Vec, - #[serde(default)] - pub equipment_remove: Vec, - #[serde( - serialize_with = "serialize_relationship_patch_entries", - deserialize_with = "deserialize_relationship_patch_entries" - )] - #[schemars(with = "Vec")] - pub relationships: BTreeMap, - #[serde(default)] - pub relationship_removals: Vec, - pub obligations_add: Vec, - #[serde(default)] - pub obligations_remove: Vec, - pub vulnerabilities_add: Vec, - #[serde(default)] - pub vulnerabilities_remove: Vec, - pub goals_add: Vec, - #[serde(default)] - pub goals_remove: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct RelationshipPatchEntry { - pub subject: String, - pub relationship: String, -} - -fn serialize_relationship_patch_entries( - relationships: &BTreeMap, - serializer: S, -) -> std::result::Result -where - S: serde::Serializer, -{ - relationships - .iter() - .map(|(subject, relationship)| RelationshipPatchEntry { - subject: subject.clone(), - relationship: relationship.clone(), - }) - .collect::>() - .serialize(serializer) -} - -fn deserialize_relationship_patch_entries<'de, D>( - deserializer: D, -) -> std::result::Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - #[derive(Deserialize)] - #[serde(untagged)] - enum RelationshipPatchWire { - Entries(Vec), - LegacyMap(BTreeMap), - } - - match RelationshipPatchWire::deserialize(deserializer)? { - RelationshipPatchWire::LegacyMap(relationships) => Ok(relationships), - RelationshipPatchWire::Entries(entries) => { - let mut relationships = BTreeMap::new(); - for entry in entries { - match relationships.entry(entry.subject) { - std::collections::btree_map::Entry::Vacant(slot) => { - slot.insert(entry.relationship); - } - std::collections::btree_map::Entry::Occupied(mut slot) => { - if slot.get() != &entry.relationship { - slot.get_mut().push_str("; "); - slot.get_mut().push_str(&entry.relationship); - } - } - } - } - Ok(relationships) - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] -pub struct SessionZeroDelta { - pub contract_patch: CampaignContractPatch, - pub character_patch: Option, - pub decisions: Vec, - pub dm_speech: String, - pub suggested_replies: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)] -struct SessionZeroInterpretation { - pub contract_patch: CampaignContractPatch, - pub character_patch: Option, - pub decisions: Vec, - pub suggested_replies: Vec, -} - -/// Model-facing decision content. Durable identity, channel ownership, -/// materiality, evidence custody, and lifecycle state belong to Ghostlight. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -#[serde(deny_unknown_fields)] -struct SessionZeroDecisionProposal { - pub prompt: String, - pub proposed_resolution: String, - pub proposed_extraordinary_permission: Option, - pub proposed_contract_patch: Option, - pub proposed_character_patch: Option, -} - -/// Model-facing typed extraction. The Persona owns the natural DM utterance; -/// the Interpreter may only propose typed state and reply affordances. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)] -#[serde(deny_unknown_fields)] -struct SessionZeroModelInterpretation { - #[serde(default)] - pub contract_patch: CampaignContractPatch, - pub character_patch: Option, - pub decisions: Vec, - pub suggested_replies: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct FocusedPermissionTerms { - pub name: String, - pub reliable_scope: String, - pub prerequisites: Vec, - pub costs: Vec, - pub limits: Vec, - pub opposition: Vec, - pub exposure: Vec, - pub effect_ceiling: String, - pub branch_local: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] -pub struct SessionZeroState { - pub schema: String, - pub id: Uuid, - pub name: String, - pub status: SessionZeroStatus, - pub revision: u64, - pub shared_epoch: u64, - pub boundary_epoch: u64, - pub host_member_id: String, - pub roster_locked: bool, - pub members: BTreeMap, - pub channels: BTreeMap, - pub messages: BTreeMap, - pub contract: CampaignContract, - pub character_drafts: BTreeMap, - pub character_epochs: BTreeMap, - pub boundaries: BTreeMap, - pub aggregate_boundaries: Vec, - pub decisions: BTreeMap, - pub approvals: BTreeMap, - pub invites: BTreeMap, - pub dm_persona: CampaignDmPersona, - pub preview: Option, - #[serde(default)] - pub model_receipts: Vec, - #[serde(default)] - pub preview_model_receipts: Vec, - pub preview_evidence_coverage: Vec, - pub preview_shared_digest: Option, - pub preview_character_digests: BTreeMap, - pub published_campaign_id: Option, - pub published_seed_digest: Option, - #[serde(default)] - pub review_campaign_id: Option, - #[serde(default)] - pub review_world_revision: Option, - #[serde(default)] - pub inherited_aggregate_boundaries: Vec, - pub created_at: DateTime, - pub updated_at: DateTime, -} - -impl SessionZeroState { - pub fn new( - name: String, - vault_provider: String, - account_hash: String, - display_name: String, - ) -> Result { - Self::new_with_allowance( - name, - vault_provider, - account_hash, - display_name, - FIXTURE_CELL_ALLOWANCE, - ) - } - - pub fn new_with_allowance( - name: String, - vault_provider: String, - account_hash: String, - display_name: String, - cell_allowance: u8, - ) -> Result { - validate_bounded("session name", &name, 1, 80)?; - validate_bounded("vault provider", &vault_provider, 1, 120)?; - validate_bounded("display name", &display_name, 1, 80)?; - if cell_allowance == 0 || cell_allowance > OPERATOR_CELL_CEILING { - return Err(anyhow!("Persona-cell entitlement is out of range")); - } - let id = Uuid::new_v4(); - let member_id = format!("member:{}", Uuid::new_v4().simple()); - let now = Utc::now(); - let mut members = BTreeMap::new(); - members.insert( - member_id.clone(), - SessionZeroMember { - schema: "ghostlight.session_zero_member.v1".into(), - id: member_id.clone(), - account_hash, - display_name: display_name.clone(), - is_host: true, - active: true, - cell_allowance, - joined_at: now, - }, - ); - let shared_id = "shared:table".to_string(); - let private_id = format!("private:{member_id}"); - let channels = BTreeMap::from([ - ( - shared_id.clone(), - SessionZeroChannel { - schema: "ghostlight.session_zero_channel.v1".into(), - id: shared_id, - kind: SessionZeroChannelKind::SharedTable, - member_id: None, - revision: 0, - message_ids: vec![], - }, - ), - ( - private_id.clone(), - SessionZeroChannel { - schema: "ghostlight.session_zero_channel.v1".into(), - id: private_id, - kind: SessionZeroChannelKind::PrivateDm, - member_id: Some(member_id.clone()), - revision: 0, - message_ids: vec![], - }, - ), - ]); - let actor_id = format!("player:{}", Uuid::new_v4().simple()); - Ok(Self { - schema: "ghostlight.session_zero.v1".into(), - id, - name: name.clone(), - status: SessionZeroStatus::Drafting, - revision: 0, - shared_epoch: 0, - boundary_epoch: 0, - host_member_id: member_id.clone(), - roster_locked: false, - members, - channels, - messages: BTreeMap::new(), - contract: CampaignContract { - schema: "ghostlight.campaign_contract.v1".into(), - vault_provider, - campaign_name: name, - time_advance_policy: "unanimous".into(), - ..CampaignContract::default() - }, - character_drafts: BTreeMap::from([( - member_id.clone(), - CharacterDraft { - schema: "ghostlight.character_draft.v1".into(), - member_id: member_id.clone(), - actor_id, - name: display_name, - ..CharacterDraft::default() - }, - )]), - character_epochs: BTreeMap::from([(member_id.clone(), 0)]), - boundaries: BTreeMap::new(), - aggregate_boundaries: vec![], - decisions: BTreeMap::new(), - approvals: BTreeMap::new(), - invites: BTreeMap::new(), - dm_persona: CampaignDmPersona { - schema: "ghostlight.campaign_dm_persona.v1".into(), - id: format!("dm:{}", id.simple()), - name: "Ghostlight".into(), - voice: "Curious, candid, fiction-first, and willing to negotiate for meaningful stakes.".into(), - shared_memories: vec![], - private_member_memories: BTreeMap::new(), - }, - preview: None, - model_receipts: vec![], - preview_model_receipts: vec![], - preview_evidence_coverage: vec![], - preview_shared_digest: None, - preview_character_digests: BTreeMap::new(), - published_campaign_id: None, - published_seed_digest: None, - review_campaign_id: None, - review_world_revision: None, - inherited_aggregate_boundaries: vec![], - created_at: now, - updated_at: now, - }) - } - - pub fn for_contract_review( - campaign: &Campaign, - membership: &CampaignMembership, - contract: CampaignContract, - dm_persona: CampaignDmPersona, - previous_brief: Option<&ApprovedCampaignBrief>, - boundaries: Vec, - ) -> Result { - if membership.campaign_id != campaign.id { - return Err(anyhow!( - "contract review membership targets another campaign" - )); - } - let id = Uuid::new_v4(); - let now = Utc::now(); - let mut members = BTreeMap::new(); - let mut channels = BTreeMap::from([( - "shared:table".to_string(), - SessionZeroChannel { - schema: "ghostlight.session_zero_channel.v1".into(), - id: "shared:table".into(), - kind: SessionZeroChannelKind::SharedTable, - member_id: None, - revision: 0, - message_ids: vec![], - }, - )]); - let mut character_drafts = BTreeMap::new(); - let mut character_epochs = BTreeMap::new(); - for member in membership.members.values().filter(|member| member.active) { - let actor = campaign - .actors - .get(&member.actor_id) - .ok_or_else(|| anyhow!("campaign member actor is missing"))?; - let previous = previous_brief.and_then(|brief| { - brief - .characters - .iter() - .find(|draft| draft.actor_id == member.actor_id) - }); - members.insert( - member.member_id.clone(), - SessionZeroMember { - schema: "ghostlight.session_zero_member.v1".into(), - id: member.member_id.clone(), - account_hash: member.account_hash.clone(), - display_name: member.display_name.clone(), - is_host: member.is_host, - active: true, - cell_allowance: member.cell_allowance, - joined_at: now, - }, - ); - let channel_id = format!("private:{}", member.member_id); - channels.insert( - channel_id.clone(), - SessionZeroChannel { - schema: "ghostlight.session_zero_channel.v1".into(), - id: channel_id, - kind: SessionZeroChannelKind::PrivateDm, - member_id: Some(member.member_id.clone()), - revision: 0, - message_ids: vec![], - }, - ); - character_drafts.insert( - member.member_id.clone(), - CharacterDraft { - schema: "ghostlight.character_draft.v1".into(), - member_id: member.member_id.clone(), - actor_id: member.actor_id.clone(), - name: actor.name.clone(), - public_premise: previous - .map(|value| value.public_premise.clone()) - .unwrap_or_default(), - private_history: previous - .map(|value| value.private_history.clone()) - .unwrap_or_else(|| actor.memories.clone()), - secrets: previous - .map(|value| value.secrets.clone()) - .unwrap_or_default(), - capabilities: actor.capabilities.iter().cloned().collect(), - knowledge: actor.knowledge.iter().cloned().collect(), - equipment: actor.equipment.iter().cloned().collect(), - relationships: actor.relationships.clone(), - obligations: actor.obligations.iter().cloned().collect(), - vulnerabilities: actor.conditions.iter().cloned().collect(), - goals: actor.goals.clone(), - extraordinary_permissions: membership - .extraordinary_permissions - .get(&member.actor_id) - .cloned() - .unwrap_or_default(), - }, - ); - character_epochs.insert(member.member_id.clone(), 0); - } - let exact_boundaries = boundaries - .into_iter() - .map(|boundary| (boundary.id.clone(), boundary)) - .collect::>(); - let inherited_aggregate_boundaries = previous_brief - .map(|brief| brief.aggregate_boundaries.clone()) - .unwrap_or_default(); - let aggregate_boundaries = - aggregate_boundaries_with_inherited(&exact_boundaries, &inherited_aggregate_boundaries); - Ok(Self { - schema: "ghostlight.session_zero.v1".into(), - id, - name: format!("{} — Contract Review", campaign.name), - status: SessionZeroStatus::RosterLocked, - revision: 0, - shared_epoch: 0, - boundary_epoch: 0, - host_member_id: membership.host_member_id.clone(), - roster_locked: true, - members, - channels, - messages: BTreeMap::new(), - contract, - character_drafts, - character_epochs, - boundaries: exact_boundaries, - aggregate_boundaries, - decisions: BTreeMap::new(), - approvals: BTreeMap::new(), - invites: BTreeMap::new(), - dm_persona, - preview: None, - model_receipts: vec![], - preview_model_receipts: vec![], - preview_evidence_coverage: vec![], - preview_shared_digest: None, - preview_character_digests: BTreeMap::new(), - published_campaign_id: None, - published_seed_digest: None, - review_campaign_id: Some(campaign.id), - review_world_revision: Some(campaign.revision), - inherited_aggregate_boundaries, - created_at: now, - updated_at: now, - }) - } - - pub fn member_for_account(&self, account_hash: &str) -> Option<&SessionZeroMember> { - self.members - .values() - .find(|member| member.active && member.account_hash == account_hash) - } - - pub fn shared_digest(&self) -> Result { - digest(&( - &self.contract, - &self.aggregate_boundaries, - self.members - .values() - .filter(|member| member.active) - .map(|member| { - let draft = &self.character_drafts[&member.id]; - ( - &member.id, - &member.display_name, - &draft.name, - &draft.public_premise, - ) - }) - .collect::>(), - )) - } - - pub fn character_digest(&self, member_id: &str) -> Result { - let draft = self - .character_drafts - .get(member_id) - .ok_or_else(|| anyhow!("character draft is missing"))?; - let boundaries = self - .boundaries - .values() - .filter(|boundary| boundary.owner_member_id == member_id) - .collect::>(); - digest(&(draft, boundaries)) - } - - pub fn world_preview_digest(&self) -> Result { - let preview = self - .preview - .as_ref() - .ok_or_else(|| anyhow!("session zero has no compiled world preview"))?; - digest(preview) - } - - pub fn pooled_cell_allowance(&self) -> u8 { - self.members - .values() - .filter(|member| member.active) - .fold(0_u8, |total, member| { - total.saturating_add(member.cell_allowance) - }) - .min(OPERATOR_CELL_CEILING) - } - - pub fn approved_brief(&self) -> Result { - if self.status != SessionZeroStatus::Review || self.preview.is_none() { - return Err(anyhow!("session zero has no final review preview")); - } - let brief = self.compilation_brief()?; - let world_preview_digest = self.world_preview_digest()?; - for member in self.members.values().filter(|member| member.active) { - let character_digest = self.character_digest(&member.id)?; - let approval = self - .approvals - .get(&member.id) - .ok_or_else(|| anyhow!("{} has not approved", member.display_name))?; - if approval.shared_digest != brief.shared_digest - || approval.character_digest != character_digest - || approval.world_preview_digest != world_preview_digest - { - return Err(anyhow!("{} approval is stale", member.display_name)); - } - } - Ok(brief) - } - - pub fn compilation_brief(&self) -> Result { - if !self.roster_locked { - return Err(anyhow!("roster must be locked before compilation")); - } - if self - .decisions - .values() - .any(|decision| decision.material && !decision.resolved) - { - return Err(anyhow!("material decisions remain unresolved")); - } - let gaps = self.compilation_gaps(); - if !gaps.is_empty() { - return Err(anyhow!( - "Session Zero draft is incomplete: {}", - gaps.join("; ") - )); - } - let shared_digest = self.shared_digest()?; - let active = self - .members - .values() - .filter(|member| member.active) - .collect::>(); - let mut character_digests = BTreeMap::new(); - let mut characters = Vec::new(); - let mut member_actor_ids = BTreeMap::new(); - for member in active { - let character_digest = self.character_digest(&member.id)?; - character_digests.insert(member.id.clone(), character_digest); - let draft = self.character_drafts[&member.id].clone(); - member_actor_ids.insert(member.id.clone(), draft.actor_id.clone()); - characters.push(draft); - } - Ok(ApprovedCampaignBrief { - schema: "ghostlight.approved_campaign_brief.v1".into(), - session_zero_id: self.id, - host_member_id: self.host_member_id.clone(), - contract: self.contract.clone(), - aggregate_boundaries: self.aggregate_boundaries.clone(), - characters, - member_actor_ids, - shared_digest, - character_digests, - }) - } - - fn compilation_gaps(&self) -> Vec { - let mut gaps = Vec::new(); - for (label, value) in [ - ("campaign premise", self.contract.premise.as_str()), - ("canon horizon", self.contract.canon_horizon.as_str()), - ("starting location", self.contract.starting_where.as_str()), - ("starting time", self.contract.starting_when.as_str()), - ( - "starting pressure", - self.contract.starting_pressure.as_str(), - ), - ("desired goal", self.contract.desired_goal.as_str()), - ("pacing", self.contract.pacing.as_str()), - ( - "consequence style", - self.contract.consequence_style.as_str(), - ), - ("narrative focus", self.contract.narrative_focus.as_str()), - ("DM style", self.contract.dm_style.as_str()), - ] { - if value.trim().is_empty() { - gaps.push(label.to_string()); - } - } - if self.contract.tone.is_empty() { - gaps.push("tone".into()); - } - let active_members = self - .members - .values() - .filter(|member| member.active) - .collect::>(); - if active_members.len() > 1 && self.contract.party_bonds.is_empty() { - gaps.push("party bonds".into()); - } - for member in active_members { - let Some(character) = self.character_drafts.get(&member.id) else { - gaps.push(format!("{} character draft", member.display_name)); - continue; - }; - if character.name.trim().is_empty() { - gaps.push(format!("{} character name", member.display_name)); - } - if character.public_premise.trim().is_empty() { - gaps.push(format!("{} public character premise", member.display_name)); - } - if character.capabilities.is_empty() { - gaps.push(format!("{} capabilities", member.display_name)); - } - if character.goals.is_empty() { - gaps.push(format!("{} goals", member.display_name)); - } - if character.obligations.is_empty() && character.vulnerabilities.is_empty() { - gaps.push(format!( - "{} obligation or vulnerability", - member.display_name - )); - } - } - gaps - } -} - -#[derive(Clone, Debug)] -pub enum SessionZeroCommand { - CreateInvites { - actor_account_hash: String, - count: u8, - }, - Join { - token: String, - account_hash: String, - display_name: String, - cell_allowance: u8, - }, - Leave { - actor_account_hash: String, - expected_revision: u64, - }, - RemoveMember { - actor_account_hash: String, - expected_revision: u64, - member_id: String, - }, - PostPlayerMessage { - actor_account_hash: String, - expected_revision: u64, - channel_id: String, - text: String, - }, - ApplyDmTurn { - expected_component_epoch: u64, - expected_channel_revision: u64, - channel_id: String, - member_id: Option, - supersedes_countered_decision_id: Option, - delta: SessionZeroDelta, - model_receipts: Vec, - }, - SetBoundary { - actor_account_hash: String, - expected_revision: u64, - boundary_id: Option, - topic: String, - normalized_topic: String, - level: BoundaryLevel, - }, - RemoveBoundary { - actor_account_hash: String, - expected_revision: u64, - boundary_id: String, - }, - ResolveDecision { - actor_account_hash: String, - expected_revision: u64, - decision_id: String, - resolution: SessionZeroDecisionResolution, - counter: Option, - }, - LockRoster { - actor_account_hash: String, - expected_revision: u64, - }, - BeginCompilation { - actor_account_hash: String, - expected_revision: u64, - }, - ReviewCompilationGaps { - actor_account_hash: String, - expected_revision: u64, - }, - DiscardPreview { - actor_account_hash: String, - expected_revision: u64, - }, - InstallPreview { - expected_revision: u64, - preview: WorldCompilePreview, - model_receipts: Vec, - }, - CompilationFailed { - expected_revision: u64, - message: String, - }, - CompilationEvidenceUnavailable { - expected_revision: u64, - }, - Approve { - actor_account_hash: String, - expected_revision: u64, - }, - MarkPublished { - actor_account_hash: String, - expected_revision: u64, - campaign_id: Uuid, - seed_digest: String, - }, - Archive { - actor_account_hash: String, - expected_revision: u64, - }, -} - -#[derive(Clone, Debug)] -pub struct SessionZeroCommandResult { - pub state: SessionZeroState, - pub invite_tokens: Vec, -} - -#[derive(Clone)] -pub struct SessionZeroKernel { - tx: mpsc::Sender, -} - -struct KernelRequest { - command: SessionZeroCommand, - reply: oneshot::Sender>, -} - -impl SessionZeroKernel { - pub fn initialize(store: &CampaignStore, state: &SessionZeroState) -> Result<()> { - if !store.keys("session_zero.v1")?.is_empty() { - return Err(anyhow!("session zero store is not empty")); - } - store.insert( - "session_zero.v1", - "ghostlight.session_zero.v1", - &state.id.to_string(), - state, - )?; - Ok(()) - } - - pub fn start(store: CampaignStore, state_id: Uuid) -> Self { - let (tx, mut rx) = mpsc::channel::(64); - tokio::spawn(async move { - while let Some(request) = rx.recv().await { - let result = execute(&store, state_id, request.command); - let _ = request.reply.send(result); - } - }); - Self { tx } - } - - pub async fn command(&self, command: SessionZeroCommand) -> Result { - let (reply, receive) = oneshot::channel(); - self.tx - .send(KernelRequest { command, reply }) - .await - .map_err(|_| anyhow!("session zero kernel stopped"))?; - receive - .await - .map_err(|_| anyhow!("session zero kernel stopped"))? - } -} - -#[derive(Clone)] -pub struct SessionZeroRuntime { - pub store: CampaignStore, - pub kernel: SessionZeroKernel, -} - -#[derive(Clone)] -pub struct SessionZeroRegistry { - root: PathBuf, - runtimes: Arc>>, -} - -impl SessionZeroRegistry { - pub fn new(root: impl AsRef) -> Result { - let root = root.as_ref().to_path_buf(); - fs::create_dir_all(&root)?; - Ok(Self { - root, - runtimes: Arc::new(RwLock::new(BTreeMap::new())), - }) - } - - pub async fn load_existing(&self) -> Result<()> { - let mut found = BTreeMap::new(); - for entry in fs::read_dir(&self.root)? { - let entry = entry?; - let Ok(id) = Uuid::parse_str(&entry.file_name().to_string_lossy()) else { - continue; - }; - let path = entry.path().join("session-zero.cc"); - if !path.is_file() { - continue; - } - let store = CampaignStore::open(path)?; - let keys = store.keys("session_zero.v1")?; - if keys != vec![id.to_string()] { - return Err(anyhow!( - "session zero directory must contain its one matching state row" - )); - } - let (row, mut state) = store - .load::("session_zero.v1", &id.to_string())? - .ok_or_else(|| anyhow!("session zero state vanished during load"))?; - let changed = demote_legacy_nonmaterial_decisions(&mut state) - | migrate_legacy_model_receipts(&mut state); - if changed { - store.replace(&row, "ghostlight.session_zero.v1", &state)?; - } - found.insert( - id, - SessionZeroRuntime { - kernel: SessionZeroKernel::start(store.clone(), id), - store, - }, - ); - } - *self.runtimes.write().await = found; - Ok(()) - } - - pub async fn create(&self, state: SessionZeroState) -> Result { - if self.runtimes.read().await.contains_key(&state.id) { - return Err(anyhow!("session zero already exists")); - } - let directory = self.root.join(state.id.to_string()); - if directory.exists() { - return Err(anyhow!("session zero directory already exists")); - } - let staging = self - .root - .join(format!(".creating-{}-{}", state.id, Uuid::new_v4())); - fs::create_dir(&staging)?; - let prepared = (|| -> Result<()> { - let store = CampaignStore::open(staging.join("session-zero.cc"))?; - SessionZeroKernel::initialize(&store, &state)?; - drop(store); - fs::rename(&staging, &directory)?; - Ok(()) - })(); - if let Err(error) = prepared { - cleanup_staging(&self.root, &staging); - return Err(error); - } - let store = CampaignStore::open(directory.join("session-zero.cc"))?; - let runtime = SessionZeroRuntime { - kernel: SessionZeroKernel::start(store.clone(), state.id), - store, - }; - self.runtimes - .write() - .await - .insert(state.id, runtime.clone()); - Ok(runtime) - } - - pub async fn runtime(&self, id: Uuid) -> Result { - self.runtimes - .read() - .await - .get(&id) - .cloned() - .ok_or_else(|| anyhow!("session zero runtime is not loaded")) - } - - pub async fn list(&self) -> Vec { - self.runtimes.read().await.keys().copied().collect() - } - - pub async fn snapshot(&self, id: Uuid) -> Result { - let runtime = self.runtime(id).await?; - runtime - .store - .load::("session_zero.v1", &id.to_string())? - .map(|(_, state)| state) - .ok_or_else(|| anyhow!("session zero state vanished")) - } - - pub async fn session_for_account(&self, account_hash: &str) -> Result> { - let runtimes = self.runtimes.read().await.clone(); - let mut matches = Vec::new(); - for (id, runtime) in runtimes { - let Some((_, state)) = runtime - .store - .load::("session_zero.v1", &id.to_string())? - else { - continue; - }; - if !matches!( - state.status, - SessionZeroStatus::Published | SessionZeroStatus::Archived - ) && state.member_for_account(account_hash).is_some() - { - matches.push((state.created_at, id)); - } - } - matches.sort(); - Ok(matches.last().map(|(_, id)| *id)) - } - - pub async fn session_for_invite(&self, token: &str) -> Result> { - let wanted = secret_hash(token); - let runtimes = self.runtimes.read().await.clone(); - for (id, runtime) in runtimes { - let Some((_, state)) = runtime - .store - .load::("session_zero.v1", &id.to_string())? - else { - continue; - }; - if state.invites.values().any(|invite| { - invite.token_hash == wanted - && invite.consumed_by_member_id.is_none() - && invite.expires_at > Utc::now() - }) { - return Ok(Some(id)); - } - } - Ok(None) - } - - pub async fn active_contract_review_for_account( - &self, - account_hash: &str, - ) -> Result> { - let runtimes = self.runtimes.read().await.clone(); - let mut matches = Vec::new(); - for (id, runtime) in runtimes { - let Some((_, state)) = runtime - .store - .load::("session_zero.v1", &id.to_string())? - else { - continue; - }; - if state.review_campaign_id.is_some() - && !matches!( - state.status, - SessionZeroStatus::Published | SessionZeroStatus::Archived - ) - && state.member_for_account(account_hash).is_some() - { - matches.push((state.created_at, id)); - } - } - matches.sort(); - Ok(matches.last().map(|(_, id)| *id)) - } -} - -fn cleanup_staging(root: &Path, staging: &Path) { - let safe = staging.parent() == Some(root) - && staging - .file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.starts_with(".creating-")); - if safe && staging.exists() { - let _ = fs::remove_dir_all(staging); - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -struct ProjectedLivedStream { - lived_stream: String, -} - -#[derive(Clone)] -pub struct SessionZeroDirector { - model: Arc, - projector_model: String, - persona_model: String, - interpreter_model: String, -} - -impl SessionZeroDirector { - pub fn new( - model: Arc, - projector_model: impl Into, - persona_model: impl Into, - interpreter_model: impl Into, - ) -> Self { - Self { - model, - projector_model: projector_model.into(), - persona_model: persona_model.into(), - interpreter_model: interpreter_model.into(), - } - } - - pub async fn respond( - &self, - state: &SessionZeroState, - channel_id: &str, - member_id: Option<&str>, - supersedes_countered_decision_id: Option<&str>, - ) -> Result<(SessionZeroDelta, Vec)> { - require_channel_access_by_member(state, channel_id, member_id)?; - let permitted = permitted_dm_context( - state, - channel_id, - member_id, - supersedes_countered_decision_id, - )?; - let current_player_turn = if let Some(decision_id) = supersedes_countered_decision_id { - state - .decisions - .get(decision_id) - .and_then(|decision| decision.pending_counter.clone()) - .ok_or_else(|| anyhow!("focused Session Zero turn lost its counterproposal"))? - } else { - current_player_message(state, channel_id)?.text.clone() - }; - let binding = format!( - "session-zero:{}:revision:{}:channel:{}:focus:{}", - state.id, - state.revision, - channel_id, - supersedes_countered_decision_id.unwrap_or("conversation") - ); - let (lived, mut receipts) = if let Some(decision_id) = supersedes_countered_decision_id { - ( - ProjectedLivedStream { - lived_stream: project_focused_counter_lived_stream( - state, - member_id, - decision_id, - )?, - }, - Vec::new(), - ) - } else { - let projector_schema = serde_json::to_value(schema_for!(ProjectedLivedStream))?; - let projector = run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "session_zero_projector".into(), - model: self.projector_model.clone(), - snapshot_binding: binding.clone(), - lived_stream: format!( - "You project permitted typed Session Zero state into a compact private lived stream for the campaign DM. Preserve uncertainty, unresolved decisions, evidence gaps, accepted boundaries, authorship, and the supplied compiler_authority policy. Never invent state. Stable contract:\n- Player speech is discussion, not world truth.\n- Model changes are proposals.\n- Material bargains need explicit acceptance.\n- Private data may not cross channels.\n- Compiler-owned compatible branch-local synthesis is not a player bargain. Only a premise-blocking contradiction, unanchored canon baseline explicitly required by the premise, or approved-capability conflict is a material evidence gap requiring review.\nReturn one complete JSON object matching this schema exactly.\n\nOUTPUT JSON SCHEMA:\n{}\n\nDYNAMIC PERMITTED CONTEXT:\n{}", - serde_json::to_string(&projector_schema)?, - serde_json::to_string(&permitted)? - ), - output_schema: Some(projector_schema), - source_receipt_ids: vec![], - temperature: Some(0.0), - max_output_tokens: Some(1800), - }, - ) - .await?; - let lived: ProjectedLivedStream = serde_json::from_value( - projector - .structured - .clone() - .ok_or_else(|| anyhow!("projector omitted structured output"))?, - )?; - (lived, vec![projector.receipt]) - }; - let focused_persona_instruction = if supersedes_countered_decision_id.is_some() { - " The lived stream is Ghostlight's exact factual rendering of one countered typed proposal. Acknowledge the replacement briefly without restating, renaming, or adding terms; invite the player to review the typed decision." - } else { - "" - }; - let persona = run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "session_zero_dm_persona".into(), - model: self.persona_model.clone(), - snapshot_binding: binding.clone(), - lived_stream: format!( - "You are {}. {} Lead a candid, collaborative Session Zero. Ask only the most useful next questions; synthesize choices; preserve the player's premise while negotiating costs and limits that create stakes. Do not claim changes are accepted. Speak naturally, with no schema or machine-state language.{}\n\nCURRENT PLAYER TURN, VERBATIM:\n{}\n\nPROJECTED LIVED CONTEXT:\n{}", - state.dm_persona.name, - state.dm_persona.voice, - focused_persona_instruction, - current_player_turn, - lived.lived_stream - ), - output_schema: None, - source_receipt_ids: vec![], - temperature: Some(0.7), - max_output_tokens: Some(1200), - }, - ) - .await?; - validate_bounded("DM speech", &persona.narrative, 1, 6_000)?; - let focused = supersedes_countered_decision_id - .and_then(|decision_id| state.decisions.get(decision_id)) - .filter(|decision| decision_has_typed_payload(decision)); - let (interpretation, interpreter_receipt) = if let Some(decision) = focused { - run_focused_counter_interpreter( - self.model.as_ref(), - &self.interpreter_model, - &binding, - decision, - &lived.lived_stream, - &persona.narrative, - ) - .await? - } else { - let interpreter_context = permitted_interpreter_context( - state, - channel_id, - member_id, - supersedes_countered_decision_id, - )?; - let channel_kind = state - .channels - .get(channel_id) - .map(|channel| &channel.kind) - .ok_or_else(|| anyhow!("Session Zero Interpreter channel disappeared"))?; - let interpreter_schema = session_zero_interpreter_schema(channel_kind)?; - let interpreter = run_validated_stage( - self.model.as_ref(), - &ModelStageRequest { - stage: "session_zero_interpreter".into(), - model: self.interpreter_model.clone(), - snapshot_binding: binding, - lived_stream: format!( - "Extract only NEW typed changes proposed by the DM response. You do not own or reproduce the DM's speech. The exact current_player_message is the factual basis for a change only when the DM response clearly offers or endorses that change for review. Never copy current contract fields or existing unresolved decisions into the interpretation during ordinary conversation. Do not infer acceptance from mere discussion. Every material contract change, character change, or extraordinary bargain offered for player review must exist only inside one unresolved decision. Choose exactly one ownership lane for each change: when decisions contains a proposed_contract_patch, contract_patch must remain the all-null empty patch; when decisions contains a proposed_character_patch, character_patch must remain null. Never duplicate a proposed change into a direct patch. Every decision must carry at least one non-null typed proposed_extraordinary_permission, proposed_contract_patch, or proposed_character_patch payload; questions without an exact state change stay in DM speech or suggested replies. Ghostlight owns durable decision IDs, channel ownership, actor binding, permission IDs, materiality, evidence custody, and lifecycle state, so they are absent from your output. If turn_focus is present, it is the one exception: use countered_decision as the exact basis, preserve its unchanged typed fields, apply the pending counter, and emit exactly one replacement decision. Do not emit unrelated decisions or a direct patch. Shared channels cannot alter private character state. Private channels cannot alter the shared contract. Use empty arrays, empty objects, or null for sections with no new change. Return one complete JSON object matching this schema exactly.\n\nOUTPUT JSON SCHEMA:\n{}\n\nDYNAMIC TYPED EXTRACTION CONTEXT:\n{}\n\nDYNAMIC DM RESPONSE:\n{}", - serde_json::to_string(&interpreter_schema)?, - serde_json::to_string(&interpreter_context)?, - serde_json::to_string(&persona.narrative)? - ), - output_schema: Some(interpreter_schema), - source_receipt_ids: vec![], - temperature: Some(0.0), - max_output_tokens: Some(2600), - }, - ) - .await?; - let proposed: SessionZeroModelInterpretation = serde_json::from_value( - interpreter - .structured - .clone() - .ok_or_else(|| anyhow!("interpreter omitted structured output"))?, - )?; - let interpretation = admit_model_interpretation(state, member_id, proposed)?; - (interpretation, interpreter.receipt) - }; - let delta = SessionZeroDelta { - contract_patch: interpretation.contract_patch, - character_patch: interpretation.character_patch, - decisions: interpretation.decisions, - dm_speech: persona.narrative, - suggested_replies: interpretation.suggested_replies, - }; - validate_dm_delta(state, channel_id, member_id, &delta)?; - receipts.push(persona.receipt); - receipts.push(interpreter_receipt); - Ok((delta, receipts)) - } -} - -fn admit_model_interpretation( - state: &SessionZeroState, - member_id: Option<&str>, - proposed: SessionZeroModelInterpretation, -) -> Result { - let actor_id = member_id - .map(|member_id| { - state - .character_drafts - .get(member_id) - .map(|draft| draft.actor_id.clone()) - .ok_or_else(|| anyhow!("private character draft is missing")) - }) - .transpose()?; - let decisions = proposed - .decisions - .into_iter() - .map(|proposal| { - let permission = proposal - .proposed_extraordinary_permission - .map(|terms| { - let actor_id = actor_id.clone().ok_or_else(|| { - anyhow!("shared DM decision cannot propose an extraordinary permission") - })?; - Ok::(ExtraordinaryPermission { - schema: "ghostlight.extraordinary_permission.v1".into(), - id: format!("permission:{}", Uuid::new_v4().simple()), - actor_id, - name: terms.name, - reliable_scope: terms.reliable_scope, - prerequisites: terms.prerequisites, - costs: terms.costs, - limits: terms.limits, - opposition: terms.opposition, - exposure: terms.exposure, - effect_ceiling: terms.effect_ceiling, - evidence_receipt_ids: vec![], - branch_local: terms.branch_local, - }) - }) - .transpose()?; - Ok(SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: format!("decision:{}", Uuid::new_v4().simple()), - owner_member_id: member_id.map(str::to_owned), - prompt: proposal.prompt, - proposed_resolution: proposal.proposed_resolution, - proposed_extraordinary_permission: permission, - proposed_contract_patch: proposal.proposed_contract_patch, - proposed_character_patch: proposal.proposed_character_patch, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }) - }) - .collect::>>()?; - Ok(SessionZeroInterpretation { - contract_patch: proposed.contract_patch, - character_patch: proposed.character_patch, - decisions, - suggested_replies: proposed.suggested_replies, - }) -} - -async fn run_focused_counter_interpreter( - model: &dyn ModelPort, - model_id: &str, - binding: &str, - decision: &SessionZeroDecision, - exact_lived_stream: &str, - persona_response: &str, -) -> Result<(SessionZeroInterpretation, ModelStageReceipt)> { - let (lane_name, schema, max_output_tokens) = focused_counter_schema(decision)?; - let interpreter = run_validated_stage( - model, - &ModelStageRequest { - stage: "session_zero_interpreter".into(), - model: model_id.into(), - snapshot_binding: binding.into(), - lived_stream: format!( - "Translate the player's exact counterproposal into one replacement containing exactly these typed lanes: {lane_name}. Preserve every previous typed field the counter does not change; apply every requested removal or replacement exactly; add nothing. When the counter changes one fact that the authoritative owner state currently asserts through several fields, replace or remove every exact stale assertion of that fact while leaving unrelated state untouched. Ghostlight owns decision identity, permission identity, actor binding, owner, materiality, evidence bindings, and speech, so they are absent from your output. Emit only the replacement payload described by this schema. The Persona response is social context only and cannot override the exact factual basis. Return one complete JSON object matching the schema.\n\nOUTPUT JSON SCHEMA:\n{}\n\nEXACT FACTUAL BASIS:\n{}\n\nPERSONA RESPONSE:\n{}", - serde_json::to_string(&schema)?, - exact_lived_stream, - serde_json::to_string(persona_response)?, - ), - output_schema: Some(schema), - source_receipt_ids: decision.evidence_receipt_ids.clone(), - temperature: Some(0.0), - max_output_tokens: Some(max_output_tokens), - }, - ) - .await?; - let structured = interpreter - .structured - .clone() - .ok_or_else(|| anyhow!("focused counter interpreter omitted structured output"))?; - let mut replacement = SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: format!("decision:{}", Uuid::new_v4().simple()), - owner_member_id: decision.owner_member_id.clone(), - prompt: decision.prompt.clone(), - proposed_resolution: decision - .pending_counter - .clone() - .ok_or_else(|| anyhow!("focused counter lost its persisted replacement"))?, - proposed_extraordinary_permission: None, - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: decision.evidence_receipt_ids.clone(), - pending_counter: None, - material: decision.material, - resolved: false, - }; - if let Some(previous) = decision.proposed_extraordinary_permission.as_ref() { - let terms: FocusedPermissionTerms = serde_json::from_value( - structured - .get("proposed_extraordinary_permission") - .cloned() - .ok_or_else(|| anyhow!("focused counter omitted extraordinary-permission terms"))?, - )?; - let mut permission = previous.clone(); - permission.name = terms.name; - permission.reliable_scope = terms.reliable_scope; - permission.prerequisites = terms.prerequisites; - permission.costs = terms.costs; - permission.limits = terms.limits; - permission.opposition = terms.opposition; - permission.exposure = terms.exposure; - permission.effect_ceiling = terms.effect_ceiling; - permission.branch_local = terms.branch_local; - replacement.proposed_extraordinary_permission = Some(permission); - } - if decision.proposed_contract_patch.is_some() { - let patch: CampaignContractPatch = serde_json::from_value( - structured - .get("proposed_contract_patch") - .cloned() - .ok_or_else(|| anyhow!("focused counter omitted campaign-contract patch"))?, - )?; - if patch == CampaignContractPatch::default() { - return Err(anyhow!( - "focused counter interpreter returned an empty contract patch" - )); - } - replacement.proposed_contract_patch = Some(patch); - } - if decision.proposed_character_patch.is_some() { - let patch: CharacterDraftPatch = serde_json::from_value( - structured - .get("proposed_character_patch") - .cloned() - .ok_or_else(|| anyhow!("focused counter omitted private-character patch"))?, - )?; - if patch == CharacterDraftPatch::default() { - return Err(anyhow!( - "focused counter interpreter returned an empty character patch" - )); - } - replacement.proposed_character_patch = Some(patch); - } - Ok(( - SessionZeroInterpretation { - decisions: vec![replacement], - ..Default::default() - }, - interpreter.receipt, - )) -} - -fn focused_counter_schema( - decision: &SessionZeroDecision, -) -> Result<(String, serde_json::Value, u32)> { - let mut properties = serde_json::Map::new(); - let mut required = Vec::new(); - let mut lane_names = Vec::new(); - let mut max_output_tokens = 400; - if decision.proposed_extraordinary_permission.is_some() { - properties.insert( - "proposed_extraordinary_permission".into(), - inline_provider_schema_for::()?, - ); - required.push("proposed_extraordinary_permission"); - lane_names.push("extraordinary-permission terms"); - max_output_tokens += 1400; - } - if decision.proposed_contract_patch.is_some() { - properties.insert( - "proposed_contract_patch".into(), - inline_provider_schema_for::()?, - ); - required.push("proposed_contract_patch"); - lane_names.push("campaign-contract patch"); - max_output_tokens += 800; - } - if decision.proposed_character_patch.is_some() { - properties.insert( - "proposed_character_patch".into(), - inline_provider_schema_for::()?, - ); - required.push("proposed_character_patch"); - lane_names.push("private-character patch"); - max_output_tokens += 1600; - } - if properties.is_empty() { - return Err(anyhow!("focused counter has no typed state lane")); - } - Ok(( - lane_names.join(" and "), - serde_json::json!({ - "type":"object", - "additionalProperties":false, - "properties":properties, - "required":required, - }), - max_output_tokens.min(3600), - )) -} - -fn inline_provider_schema_for() -> Result { - let mut settings = SchemaSettings::default(); - settings.inline_subschemas = true; - let mut generator = settings.into_generator(); - Ok(serde_json::to_value(generator.subschema_for::())?) -} - -fn require_typed_decision_payloads(schema: &mut serde_json::Value) -> Result<()> { - let decision_schema = session_zero_decision_schema_mut(schema)? - .as_object_mut() - .ok_or_else(|| anyhow!("Session Zero Interpreter schema omitted its decision contract"))?; - decision_schema.insert( - "anyOf".into(), - serde_json::json!([ - { - "required": ["proposed_extraordinary_permission"], - "properties": {"proposed_extraordinary_permission": {"type": "object"}} - }, - { - "required": ["proposed_contract_patch"], - "properties": {"proposed_contract_patch": {"type": "object"}} - }, - { - "required": ["proposed_character_patch"], - "properties": {"proposed_character_patch": {"type": "object"}} - } - ]), - ); - Ok(()) -} - -fn session_zero_interpreter_schema( - channel_kind: &SessionZeroChannelKind, -) -> Result { - let mut settings = SchemaSettings::default(); - settings.inline_subschemas = true; - let mut schema = serde_json::to_value( - settings - .into_generator() - .into_root_schema_for::(), - )?; - require_typed_decision_payloads(&mut schema)?; - require_single_lane_ownership(&mut schema)?; - let (root_removals, decision_removals): (&[&str], &[&str]) = match channel_kind { - SessionZeroChannelKind::SharedTable => ( - &["character_patch"], - &[ - "proposed_character_patch", - "proposed_extraordinary_permission", - ], - ), - SessionZeroChannelKind::PrivateDm => (&["contract_patch"], &["proposed_contract_patch"]), - }; - for name in root_removals { - remove_schema_property(&mut schema, name)?; - } - let decision_schema = session_zero_decision_schema_mut(&mut schema)?; - for name in decision_removals { - remove_schema_property(decision_schema, name)?; - } - if channel_kind == &SessionZeroChannelKind::SharedTable { - require_single_decision_lane( - decision_schema, - "proposed_contract_patch", - inline_provider_schema_for::()?, - )?; - } - Ok(schema) -} - -fn require_single_decision_lane( - decision_schema: &mut serde_json::Value, - property_name: &str, - property_schema: serde_json::Value, -) -> Result<()> { - let decision = decision_schema - .as_object_mut() - .ok_or_else(|| anyhow!("Session Zero decision schema is not an object"))?; - let property = decision - .get_mut("properties") - .and_then(serde_json::Value::as_object_mut) - .and_then(|properties| properties.get_mut(property_name)) - .ok_or_else(|| anyhow!("Session Zero decision schema omitted {property_name}"))?; - *property = property_schema; - let required = decision - .entry("required") - .or_insert_with(|| serde_json::json!([])) - .as_array_mut() - .ok_or_else(|| anyhow!("Session Zero decision required list is not an array"))?; - if !required - .iter() - .any(|value| value.as_str() == Some(property_name)) - { - required.push(serde_json::Value::String(property_name.into())); - } - decision.remove("anyOf"); - Ok(()) -} - -fn session_zero_decision_schema_mut( - schema: &mut serde_json::Value, -) -> Result<&mut serde_json::Value> { - if schema - .pointer("/$defs/SessionZeroDecisionProposal") - .is_some() - { - return schema - .pointer_mut("/$defs/SessionZeroDecisionProposal") - .ok_or_else(|| anyhow!("Session Zero decision definition disappeared")); - } - schema - .pointer_mut("/properties/decisions/items") - .ok_or_else(|| anyhow!("Session Zero Interpreter schema omitted inline decisions")) -} - -fn remove_schema_property(schema: &mut serde_json::Value, name: &str) -> Result<()> { - let schema = schema - .as_object_mut() - .ok_or_else(|| anyhow!("Session Zero schema lane is not an object"))?; - schema - .get_mut("properties") - .and_then(serde_json::Value::as_object_mut) - .ok_or_else(|| anyhow!("Session Zero schema lane omitted its properties"))? - .remove(name); - if let Some(required) = schema - .get_mut("required") - .and_then(serde_json::Value::as_array_mut) - { - required.retain(|value| value.as_str() != Some(name)); - } - Ok(()) -} - -fn require_single_lane_ownership(schema: &mut serde_json::Value) -> Result<()> { - let root = schema - .as_object_mut() - .ok_or_else(|| anyhow!("Session Zero Interpreter schema has no object root"))?; - root.insert( - "allOf".into(), - serde_json::json!([ - { - "if": { - "properties": { - "decisions": { - "contains": { - "required": ["proposed_contract_patch"], - "properties": {"proposed_contract_patch": {"type": "object"}} - } - } - } - }, - "then": { - "properties": { - "contract_patch": {"const": CampaignContractPatch::default()} - } - } - }, - { - "if": { - "properties": { - "decisions": { - "contains": { - "required": ["proposed_character_patch"], - "properties": {"proposed_character_patch": {"type": "object"}} - } - } - } - }, - "then": { - "properties": {"character_patch": {"type": "null"}} - } - } - ]), - ); - Ok(()) -} - -fn require_channel_access_by_member( - state: &SessionZeroState, - channel_id: &str, - member_id: Option<&str>, -) -> Result<()> { - let channel = state - .channels - .get(channel_id) - .ok_or_else(|| anyhow!("channel does not exist"))?; - match channel.kind { - SessionZeroChannelKind::SharedTable => Ok(()), - SessionZeroChannelKind::PrivateDm if channel.member_id.as_deref() == member_id => Ok(()), - SessionZeroChannelKind::PrivateDm => Err(anyhow!("private channel access denied")), - } -} - -fn public_character_projection(draft: &CharacterDraft) -> serde_json::Value { - serde_json::json!({ - "member_id": draft.member_id, - "actor_id": draft.actor_id, - "name": draft.name, - "public_premise": draft.public_premise, - }) -} - -fn project_focused_counter_lived_stream( - state: &SessionZeroState, - member_id: Option<&str>, - decision_id: &str, -) -> Result { - counter_replacement_focus(state, member_id, Some(decision_id))? - .ok_or_else(|| anyhow!("focused counter projection is missing its turn focus"))?; - let decision = state - .decisions - .get(decision_id) - .ok_or_else(|| anyhow!("countered decision is missing"))?; - let current_owner_state = if let Some(member_id) = member_id { - format!( - "Current private character draft:\n{}", - display_character_ledger( - state - .character_drafts - .get(member_id) - .ok_or_else(|| anyhow!("private character draft is missing"))? - ) - ) - } else { - format!( - "Current campaign contract:\nPremise: {}\nCanon horizon: {}\nStarting location: {}\nStarting time: {}\nStarting pressure: {}\nDesired goal: {}\nTone: {}\nThemes: {}\nPacing: {}\nConsequence style: {}\nNarrative focus: {}\nParty bonds: {}\nInternal tension: {}\nDM style: {}", - state.contract.premise, - state.contract.canon_horizon, - state.contract.starting_where, - state.contract.starting_when, - state.contract.starting_pressure, - state.contract.desired_goal, - display_list(&state.contract.tone), - display_list(&state.contract.themes), - state.contract.pacing, - state.contract.consequence_style, - state.contract.narrative_focus, - display_list(&state.contract.party_bonds), - state.contract.internal_tension, - state.contract.dm_style, - ) - }; - let mut previous = display_decision_payload(decision); - let previous_uses_owner_state = previous.trim().is_empty(); - if previous.trim().is_empty() { - previous = if let Some(member_id) = member_id { - format!( - "Legacy private character replacement basis:\n{}", - display_character_ledger( - state - .character_drafts - .get(member_id) - .ok_or_else(|| anyhow!("private character draft is missing"))? - ) - ) - } else { - format!( - "Legacy campaign-contract replacement basis:\nPremise: {}\nCanon horizon: {}\nStarting location: {}\nStarting time: {}\nStarting pressure: {}\nDesired goal: {}\nTone: {}\nThemes: {}\nPacing: {}\nConsequence style: {}\nNarrative focus: {}\nParty bonds: {}\nInternal tension: {}\nDM style: {}", - state.contract.premise, - state.contract.canon_horizon, - state.contract.starting_where, - state.contract.starting_when, - state.contract.starting_pressure, - state.contract.desired_goal, - display_list(&state.contract.tone), - display_list(&state.contract.themes), - state.contract.pacing, - state.contract.consequence_style, - state.contract.narrative_focus, - display_list(&state.contract.party_bonds), - state.contract.internal_tension, - state.contract.dm_style, - ) - }; - } - let current_owner_section = if previous_uses_owner_state { - String::new() - } else { - format!("\n\nAuthoritative owner state before this replacement:\n{current_owner_state}") - }; - let counter = decision - .pending_counter - .as_deref() - .ok_or_else(|| anyhow!("countered decision has no pending counterproposal"))?; - let boundaries = if state.aggregate_boundaries.is_empty() { - "No campaign content boundaries are currently recorded.".to_owned() - } else { - state - .aggregate_boundaries - .iter() - .map(|boundary| format!("{}: {:?}", boundary.display_topic, boundary.level)) - .collect::>() - .join("; ") - }; - Ok(format!( - "A player has rejected one material typed proposal in their Session Zero channel. Nothing is accepted yet. Resolve only this replacement and invite the player to review the fresh typed decision.\n\nPrevious typed proposal, rendered exactly:\n{previous}{current_owner_section}\n\nPlayer's exact counterproposal:\n{counter}\n\nCampaign content boundaries:\n{boundaries}" - )) -} - -fn permitted_dm_context( - state: &SessionZeroState, - channel_id: &str, - member_id: Option<&str>, - supersedes_countered_decision_id: Option<&str>, -) -> Result { - let channel = state - .channels - .get(channel_id) - .ok_or_else(|| anyhow!("channel does not exist"))?; - if let Some(decision_id) = supersedes_countered_decision_id { - let turn_focus = counter_replacement_focus(state, member_id, Some(decision_id))? - .expect("a supplied countered decision produces a turn focus"); - let countered_decision = state - .decisions - .get(decision_id) - .expect("the counter focus validated the decision"); - let mut value = serde_json::json!({ - "session_id": state.id, - "revision": state.revision, - "channel_kind": channel.kind, - "member_id": member_id, - "aggregate_boundaries": state.aggregate_boundaries, - "turn_focus": turn_focus, - "countered_decision": countered_decision, - }); - if !decision_has_typed_payload(countered_decision) { - if channel.kind == SessionZeroChannelKind::PrivateDm { - let member_id = member_id.ok_or_else(|| anyhow!("private member is missing"))?; - value["legacy_replacement_basis"] = serde_json::to_value( - state - .character_drafts - .get(member_id) - .ok_or_else(|| anyhow!("private character draft is missing"))?, - )?; - } else { - value["legacy_replacement_basis"] = serde_json::to_value(&state.contract)?; - } - } - return Ok(value); - } - let current_player_message = current_player_message(state, channel_id)?; - let recent_messages = channel - .message_ids - .iter() - .rev() - .skip(1) - .take(6) - .rev() - .filter_map(|id| state.messages.get(id)) - .map(|message| { - serde_json::json!({ - "speaker": message.speaker, - "author_member_id": message.author_member_id, - "text": message.text, - }) - }) - .collect::>(); - let public_party = state - .members - .values() - .filter(|member| member.active) - .map(|member| public_character_projection(&state.character_drafts[&member.id])) - .collect::>(); - let visible_decisions = visible_decisions_for_turn(state, member_id, None)?; - let mut value = serde_json::json!({ - "session_id": state.id, - "revision": state.revision, - "shared_epoch": state.shared_epoch, - "boundary_epoch": state.boundary_epoch, - "status": state.status, - "contract": state.contract, - "aggregate_boundaries": state.aggregate_boundaries, - "public_party": public_party, - "unresolved_decisions": visible_decisions, - "turn_focus": null, - "current_player_message": { - "author_member_id": current_player_message.author_member_id, - "text": current_player_message.text, - }, - "recent_messages": recent_messages, - "evidence_coverage": state.preview_evidence_coverage, - "compiler_authority": { - "compatible_branch_elaboration": "Ghostlight must synthesize the smallest canon-compatible routes, geometry, people, procedures, resources, setting mechanics, and institutional operating doctrine needed for play as explicit branch-local fact. Consequential choices remain visible as branch assumptions and may vary between campaigns unless the Vault pins them.", - "material_gaps": "A material evidence gap exists only when no compatible branch-local elaboration can preserve the approved premise without choosing between contradictory canon baselines, inventing an unanchored canon baseline explicitly required by the premise, or exceeding an approved capability.", - "canon_boundary": "Branch-local synthesis never edits the selected Vault or silently becomes setting canon." - }, - }); - if channel.kind == SessionZeroChannelKind::PrivateDm { - let member_id = member_id.ok_or_else(|| anyhow!("private member is missing"))?; - let recent_shared_messages = state - .channels - .get("shared:table") - .into_iter() - .flat_map(|shared| shared.message_ids.iter().rev().take(4).rev()) - .filter_map(|id| state.messages.get(id)) - .map(|message| { - serde_json::json!({ - "speaker": message.speaker, - "author_member_id": message.author_member_id, - "text": message.text, - }) - }) - .collect::>(); - value["recent_shared_messages"] = serde_json::to_value(recent_shared_messages)?; - value["private_character"] = serde_json::to_value( - state - .character_drafts - .get(member_id) - .ok_or_else(|| anyhow!("private character draft is missing"))?, - )?; - value["private_boundaries"] = serde_json::to_value( - state - .boundaries - .values() - .filter(|boundary| boundary.owner_member_id == member_id) - .collect::>(), - )?; - } - Ok(value) -} - -fn permitted_interpreter_context( - state: &SessionZeroState, - channel_id: &str, - member_id: Option<&str>, - supersedes_countered_decision_id: Option<&str>, -) -> Result { - let channel = state - .channels - .get(channel_id) - .ok_or_else(|| anyhow!("channel does not exist"))?; - if let Some(decision_id) = supersedes_countered_decision_id { - let turn_focus = counter_replacement_focus(state, member_id, Some(decision_id))? - .expect("a supplied countered decision produces a turn focus"); - let countered_decision = state - .decisions - .get(decision_id) - .expect("the counter focus validated the decision"); - let mut value = serde_json::json!({ - "channel_kind": channel.kind, - "member_id": member_id, - "turn_focus": turn_focus, - "countered_decision": countered_decision, - }); - if !decision_has_typed_payload(countered_decision) { - if channel.kind == SessionZeroChannelKind::PrivateDm { - let member_id = member_id.ok_or_else(|| anyhow!("private member is missing"))?; - value["legacy_replacement_basis"] = serde_json::to_value( - state - .character_drafts - .get(member_id) - .ok_or_else(|| anyhow!("private character draft is missing"))?, - )?; - } else { - value["legacy_replacement_basis"] = serde_json::to_value(&state.contract)?; - } - } - return Ok(value); - } - let current_player_message = current_player_message(state, channel_id)?; - let visible_decisions = visible_decisions_for_turn(state, member_id, None)?; - let mut value = serde_json::json!({ - "channel_kind": channel.kind, - "member_id": member_id, - "existing_visible_decisions": visible_decisions, - "turn_focus": null, - "current_player_message": { - "author_member_id": current_player_message.author_member_id, - "text": current_player_message.text, - }, - }); - if channel.kind == SessionZeroChannelKind::PrivateDm { - let member_id = member_id.ok_or_else(|| anyhow!("private member is missing"))?; - value["current_private_character"] = serde_json::to_value( - state - .character_drafts - .get(member_id) - .ok_or_else(|| anyhow!("private character draft is missing"))?, - )?; - } else { - value["current_contract"] = serde_json::to_value(&state.contract)?; - } - Ok(value) -} - -fn current_player_message<'a>( - state: &'a SessionZeroState, - channel_id: &str, -) -> Result<&'a SessionZeroMessage> { - let channel = state - .channels - .get(channel_id) - .ok_or_else(|| anyhow!("channel does not exist"))?; - let message = channel - .message_ids - .last() - .and_then(|id| state.messages.get(id)) - .ok_or_else(|| anyhow!("Session Zero DM turn has no current player message"))?; - if message.speaker != SessionZeroSpeakerKind::Player { - return Err(anyhow!( - "Session Zero DM turn is not bound to a current player message" - )); - } - Ok(message) -} - -fn visible_decisions_for_turn<'a>( - state: &'a SessionZeroState, - member_id: Option<&str>, - supersedes_countered_decision_id: Option<&str>, -) -> Result> { - if let Some(decision_id) = supersedes_countered_decision_id { - return Ok(vec![ - state - .decisions - .get(decision_id) - .ok_or_else(|| anyhow!("countered decision is missing"))?, - ]); - } - Ok(state - .decisions - .values() - .filter(|decision| { - decision.material - && !decision.resolved - && (decision.owner_member_id.is_none() - || decision.owner_member_id.as_deref() == member_id) - }) - .collect()) -} - -fn counter_replacement_focus( - state: &SessionZeroState, - member_id: Option<&str>, - supersedes_countered_decision_id: Option<&str>, -) -> Result> { - let Some(decision_id) = supersedes_countered_decision_id else { - return Ok(None); - }; - let decision = state - .decisions - .get(decision_id) - .ok_or_else(|| anyhow!("countered decision is missing"))?; - if decision.resolved { - return Err(anyhow!("countered decision is already resolved")); - } - if decision.owner_member_id.as_deref() != member_id { - return Err(anyhow!( - "countered decision is outside this channel's authority" - )); - } - let pending_counter = decision - .pending_counter - .as_deref() - .ok_or_else(|| anyhow!("countered decision has no pending counterproposal"))?; - Ok(Some(serde_json::json!({ - "kind":"counter_replacement", - "decision_id":decision.id, - "original_prompt":decision.prompt, - "pending_counter":pending_counter, - "required_owner_member_id":decision.owner_member_id, - "required_material":decision.material, - "required_output":"exactly one fresh unresolved decision with a non-empty typed payload", - }))) -} - -fn display_list(values: &[String]) -> String { - if values.is_empty() { - "—".into() - } else { - values.join("; ") - } -} - -fn display_relationships(values: &BTreeMap) -> String { - if values.is_empty() { - "—".into() - } else { - values - .iter() - .map(|(subject, relationship)| format!("{subject}: {relationship}")) - .collect::>() - .join("; ") - } -} - -fn display_extraordinary_permission(permission: &ExtraordinaryPermission) -> String { - format!( - "{}\n Reliable scope: {}\n Prerequisites: {}\n Costs: {}\n Limits: {}\n Opposition: {}\n Exposure: {}\n Effect ceiling: {}\n Branch-local: {}", - permission.name, - permission.reliable_scope, - display_list(&permission.prerequisites), - display_list(&permission.costs), - display_list(&permission.limits), - display_list(&permission.opposition), - display_list(&permission.exposure), - permission.effect_ceiling, - if permission.branch_local { "yes" } else { "no" }, - ) -} - -fn display_character_ledger(character: &CharacterDraft) -> String { - let permissions = if character.extraordinary_permissions.is_empty() { - "—".into() - } else { - character - .extraordinary_permissions - .iter() - .map(display_extraordinary_permission) - .collect::>() - .join("\n") - }; - format!( - "Name: {}\nPublic premise: {}\nPrivate history: {}\nSecrets: {}\nCapabilities: {}\nKnowledge: {}\nEquipment: {}\nRelationships: {}\nObligations: {}\nVulnerabilities: {}\nGoals: {}\nExtraordinary permissions:\n{}", - character.name, - character.public_premise, - display_list(&character.private_history), - display_list(&character.secrets), - display_list(&character.capabilities), - display_list(&character.knowledge), - display_list(&character.equipment), - display_relationships(&character.relationships), - display_list(&character.obligations), - display_list(&character.vulnerabilities), - display_list(&character.goals), - permissions, - ) -} - -fn display_patch_list(values: &[String]) -> String { - if values.is_empty() { - "(empty list)".into() - } else { - values.join("; ") - } -} - -fn display_contract_patch(patch: &CampaignContractPatch) -> String { - let mut lines = Vec::new(); - macro_rules! push_string { - ($field:ident, $label:literal) => { - if let Some(value) = &patch.$field { - lines.push(format!(concat!($label, ": {}"), value)); - } - }; - } - macro_rules! push_list { - ($field:ident, $label:literal) => { - if let Some(values) = &patch.$field { - lines.push(format!(concat!($label, ": {}"), display_patch_list(values))); - } - }; - } - push_string!(premise, "Premise"); - push_string!(canon_horizon, "Canon horizon"); - push_string!(starting_where, "Starting location"); - push_string!(starting_when, "Starting time"); - push_string!(starting_pressure, "Starting pressure"); - push_string!(desired_goal, "Desired goal"); - push_list!(tone, "Tone"); - push_list!(themes, "Themes"); - push_string!(pacing, "Pacing"); - push_string!(consequence_style, "Consequence style"); - push_string!(narrative_focus, "Narrative focus"); - push_list!(party_bonds, "Party bonds"); - push_string!(internal_tension, "Internal tension"); - push_string!(dm_style, "DM style"); - lines.join("\n") -} - -fn display_character_patch(patch: &CharacterDraftPatch) -> String { - let mut lines = Vec::new(); - if let Some(name) = &patch.name { - lines.push(format!("Name: {name}")); - } - if let Some(public_premise) = &patch.public_premise { - lines.push(format!("Public premise: {public_premise}")); - } - for (values, label) in [ - (&patch.private_history_add, "Private history to add"), - (&patch.private_history_remove, "Private history to remove"), - (&patch.secrets_add, "Secrets to add"), - (&patch.secrets_remove, "Secrets to remove"), - (&patch.capabilities_add, "Capabilities to add"), - (&patch.capabilities_remove, "Capabilities to remove"), - (&patch.knowledge_add, "Knowledge to add"), - (&patch.knowledge_remove, "Knowledge to remove"), - (&patch.equipment_add, "Equipment to add"), - (&patch.equipment_remove, "Equipment to remove"), - (&patch.obligations_add, "Obligations to add"), - (&patch.obligations_remove, "Obligations to remove"), - (&patch.vulnerabilities_add, "Vulnerabilities to add"), - (&patch.vulnerabilities_remove, "Vulnerabilities to remove"), - (&patch.goals_add, "Goals to add"), - (&patch.goals_remove, "Goals to remove"), - ] { - if !values.is_empty() { - lines.push(format!("{label}: {}", values.join("; "))); - } - } - if !patch.relationships.is_empty() { - lines.push(format!( - "Relationships to set: {}", - display_relationships(&patch.relationships) - )); - } - if !patch.relationship_removals.is_empty() { - lines.push(format!( - "Relationship keys to remove: {}", - patch.relationship_removals.join("; ") - )); - } - lines.join("\n") -} - -fn display_decision_payload(decision: &SessionZeroDecision) -> String { - let mut sections = Vec::new(); - if let Some(permission) = &decision.proposed_extraordinary_permission { - sections.push(format!( - "Extraordinary permission:\n{}", - display_extraordinary_permission(permission) - )); - } - if let Some(patch) = &decision.proposed_contract_patch - && patch != &CampaignContractPatch::default() - { - sections.push(format!( - "Campaign contract patch:\n{}", - display_contract_patch(patch) - )); - } - if let Some(patch) = &decision.proposed_character_patch - && patch != &CharacterDraftPatch::default() - { - sections.push(format!( - "Private character patch:\n{}", - display_character_patch(patch) - )); - } - sections.join("\n") -} - -#[derive(Clone, Debug, Serialize, PartialEq, Eq)] -struct PrivateRelationshipSubjectProjection { - target_id: String, - subject_kind: String, - name: String, - location_id: Option, - location_name: Option, - relationship: String, - counterpart_actor_state: Option, -} - -#[derive(Clone, Debug, Serialize, PartialEq, Eq)] -struct PrivateRelationshipActorStateProjection { - capabilities: BTreeSet, - knowledge: BTreeSet, - equipment: BTreeSet, - conditions: BTreeSet, - obligations: BTreeSet, - relationships: BTreeMap, - goals: Vec, -} - -fn private_relationship_subjects( - preview: &WorldCompilePreview, - actor_id: &str, -) -> Vec { - let campaign = &preview.campaign; - let Some(actor) = campaign.actors.get(actor_id) else { - return Vec::new(); - }; - - actor - .relationships - .iter() - .map(|(target_id, description)| { - let (subject_kind, name, location_id, counterpart_actor_state) = - if let Some(target) = campaign.actors.get(target_id) { - ( - "actor", - target.name.as_str(), - Some(target.location_id.as_str()), - Some(PrivateRelationshipActorStateProjection { - capabilities: target.capabilities.clone(), - knowledge: target.knowledge.clone(), - equipment: target.equipment.clone(), - conditions: target.conditions.clone(), - obligations: target.obligations.clone(), - relationships: target.relationships.clone(), - goals: target.goals.clone(), - }), - ) - } else if let Some(target) = campaign.institutions.get(target_id) { - ("institution", target.name.as_str(), None, None) - } else if let Some(target) = campaign.gestalts.get(target_id) { - ( - "gestalt", - target.name.as_str(), - Some(target.home_location_id.as_str()), - None, - ) - } else if let Some(member_id) = target_id.strip_prefix("member:") { - if let Some(target) = campaign.gestalt_members.get(member_id) { - let location_id = target.last_location_id.as_deref().or_else(|| { - campaign - .gestalts - .get(&target.gestalt_id) - .map(|gestalt| gestalt.home_location_id.as_str()) - }); - ("gestalt_member", target.name.as_str(), location_id, None) - } else { - ("unknown", target_id.as_str(), None, None) - } - } else { - ("unknown", target_id.as_str(), None, None) - }; - let location_name = location_id - .and_then(|id| campaign.locations.get(id)) - .map(|location| location.name.as_str()); - PrivateRelationshipSubjectProjection { - target_id: target_id.clone(), - subject_kind: subject_kind.into(), - name: name.into(), - location_id: location_id.map(str::to_owned), - location_name: location_name.map(str::to_owned), - relationship: description.clone(), - counterpart_actor_state, - } - }) - .collect() -} - -fn display_values<'a>(values: impl IntoIterator) -> String { - let joined = values.into_iter().cloned().collect::>().join(", "); - if joined.is_empty() { - "none".into() - } else { - joined - } -} - -fn display_world_preview( - preview: &WorldCompilePreview, - player_actor_ids: &BTreeSet, -) -> String { - let campaign = &preview.campaign; - let mut sections = vec![format!("Opening: {}", preview.title)]; - let topology = campaign - .locations - .values() - .map(|location| { - let routes = location - .routes - .values() - .map(|route| { - format!( - "{} ({}; {} minutes)", - route.destination_id, route.distance, route.travel_minutes - ) - }) - .collect::>() - .join(", "); - format!( - "{} [{}] · within {} · routes: {} · persistent features: {}", - location.name, - location.id, - location.container_id.as_deref().unwrap_or("root"), - if routes.is_empty() { "none" } else { &routes }, - if location.persistent_features.is_empty() { - "none".into() - } else { - location.persistent_features.join("; ") - } - ) - }) - .collect::>() - .join("\n"); - sections.push(format!("Topology\n{topology}")); - - let cast = campaign - .actors - .values() - .filter(|actor| { - !player_actor_ids.contains(&actor.id) && !actor.id.starts_with("relationship-anchor:") - }) - .map(|actor| format!("{} [{}] · {}", actor.name, actor.id, actor.location_id)) - .collect::>() - .join("\n"); - sections.push(format!( - "Starting cast\n{}", - if cast.is_empty() { "none" } else { &cast } - )); - - let institutions = campaign - .institutions - .values() - .map(|institution| { - format!( - "{} [{}] · posture: {}", - institution.name, institution.id, institution.posture - ) - }) - .collect::>() - .join("\n"); - sections.push(format!( - "Institutions\n{}", - if institutions.is_empty() { - "none" - } else { - &institutions - } - )); - - let populations = campaign - .gestalts - .values() - .map(|gestalt| { - format!( - "{} [{}] · {} · pressures: {}", - gestalt.name, - gestalt.id, - gestalt.home_location_id, - if gestalt.pressures.is_empty() { - "none".into() - } else { - gestalt.pressures.join("; ") - } - ) - }) - .collect::>() - .join("\n"); - sections.push(format!( - "Populations\n{}", - if populations.is_empty() { - "none" - } else { - &populations - } - )); - - let clocks = campaign - .clocks - .values() - .map(|clock| { - format!( - "{} [{}] · {}/{} · consequence: {}", - clock.label, clock.id, clock.progress, clock.threshold, clock.consequence - ) - }) - .collect::>() - .join("\n"); - sections.push(format!( - "World clocks\n{}", - if clocks.is_empty() { "none" } else { &clocks } - )); - sections.join("\n\n") -} - -pub fn session_zero_surface( - state: &SessionZeroState, - account_hash: &str, -) -> Result { - let member = state - .member_for_account(account_hash) - .ok_or_else(|| anyhow!("session zero membership required"))?; - let channels = state - .channels - .values() - .filter(|channel| { - channel.kind == SessionZeroChannelKind::SharedTable - || channel.member_id.as_deref() == Some(member.id.as_str()) - }) - .map(|channel| { - let messages = channel - .message_ids - .iter() - .filter_map(|id| state.messages.get(id)) - .collect::>(); - serde_json::json!({ - "id": channel.id, - "kind": channel.kind, - "revision": channel.revision, - "messages": messages, - }) - }) - .collect::>(); - let public_party = state - .members - .values() - .filter(|candidate| candidate.active) - .map(|candidate| { - let draft = &state.character_drafts[&candidate.id]; - serde_json::json!({ - "member_id": candidate.id, - "display_name": candidate.display_name, - "is_host": candidate.is_host, - "name": draft.name, - "public_premise": draft.public_premise, - "approved": state.approvals.contains_key(&candidate.id), - }) - }) - .collect::>(); - let private_boundaries = state - .boundaries - .values() - .filter(|boundary| boundary.owner_member_id == member.id) - .collect::>(); - let visible_decisions = state - .decisions - .values() - .filter(|decision| { - decision.owner_member_id.is_none() - || decision.owner_member_id.as_deref() == Some(member.id.as_str()) - }) - .collect::>(); - let character = &state.character_drafts[&member.id]; - let player_actor_ids = state - .character_drafts - .values() - .map(|draft| draft.actor_id.clone()) - .collect::>(); - let relationship_subjects = state - .preview - .as_ref() - .map(|preview| private_relationship_subjects(preview, &character.actor_id)) - .unwrap_or_default(); - let private_preview = state.preview.as_ref().map(|preview| { - serde_json::json!({ - "title": preview.title, - "gaps": preview.gaps, - "branch_assumptions": preview.branch_assumptions, - "topology": preview.campaign.locations, - "cast": preview.campaign.actors.values().filter(|actor| !player_actor_ids.contains(&actor.id) && !actor.id.starts_with("relationship-anchor:")).map(|actor| serde_json::json!({"id":actor.id,"name":actor.name,"location_id":actor.location_id})).collect::>(), - "institutions": preview.campaign.institutions.values().map(|institution| serde_json::json!({"id":institution.id,"name":institution.name,"posture":institution.posture})).collect::>(), - "populations": preview.campaign.gestalts.values().map(|gestalt| serde_json::json!({"id":gestalt.id,"name":gestalt.name,"home_location_id":gestalt.home_location_id,"pressures":gestalt.pressures})).collect::>(), - "clocks": preview.campaign.clocks, - "evidence_coverage": preview.evidence_coverage, - "relationship_subjects": relationship_subjects, - "world_preview_digest": state.world_preview_digest().ok(), - }) - }); - let roster_summary = state - .members - .values() - .filter(|candidate| candidate.active) - .map(|candidate| { - let readiness = match state.status { - SessionZeroStatus::Drafting => "drafting", - SessionZeroStatus::RosterLocked | SessionZeroStatus::Compiling => "awaiting review", - SessionZeroStatus::Review => { - if state.approvals.contains_key(&candidate.id) { - "approved" - } else { - "approval needed" - } - } - SessionZeroStatus::Published => "published", - SessionZeroStatus::Archived => "archived", - }; - format!( - "{} · {}{}", - candidate.display_name, - readiness, - if candidate.is_host { " · host" } else { "" } - ) - }) - .collect::>() - .join("\n"); - let contract_summary = format!( - "Premise: {}\nWhere: {}\nWhen: {}\nPressure: {}\nGoal: {}\nTone: {}", - state.contract.premise, - state.contract.starting_where, - state.contract.starting_when, - state.contract.starting_pressure, - state.contract.desired_goal, - state.contract.tone.join(", ") - ); - let character_summary = display_character_ledger(character); - let shared_channel_id = state - .channels - .values() - .find(|channel| channel.kind == SessionZeroChannelKind::SharedTable) - .map(|channel| channel.id.clone()) - .ok_or_else(|| anyhow!("shared Session Zero channel is missing"))?; - let private_channel_id = state - .channels - .values() - .find(|channel| channel.member_id.as_deref() == Some(member.id.as_str())) - .map(|channel| channel.id.clone()); - let transcript = channels - .iter() - .flat_map(|channel| { - let channel_label = if channel["kind"] == "shared_table" { "Table" } else { "Private DM" }; - channel["messages"].as_array().into_iter().flatten().filter_map(move |message| { - Some(serde_json::json!({ - "id":format!("session-zero.message.{}", message["id"].as_str()?), - "kind":"text.dialogue", - "props":{"value":format!("{channel_label} · {}: {}", message["speaker"].as_str().unwrap_or("system"), message["text"].as_str().unwrap_or(""))}, - "children":[] - })) - }) - }) - .collect::>(); - let mut children = vec![ - serde_json::json!({"id":"session-zero.status","kind":"card","props":{"title":format!("{} · revision {}", session_status_label(&state.status), state.revision)},"children":[]}), - serde_json::json!({"id":"session-zero.roster","kind":"card","props":{"title":format!("Roster · {} pooled cells",state.pooled_cell_allowance())},"children":[{"id":"session-zero.roster.text","kind":"text","props":{"value":roster_summary},"children":[]}]}), - serde_json::json!({"id":"session-zero.contract","kind":"card","props":{"title":"Campaign contract"},"children":[{"id":"session-zero.contract.text","kind":"text","props":{"value":contract_summary},"children":[]}]}), - serde_json::json!({"id":"session-zero.character","kind":"card","props":{"title":"Your private character"},"children":[{"id":"session-zero.character.text","kind":"text","props":{"value":character_summary},"children":[]}]}), - serde_json::json!({"id":"session-zero.conversation","kind":"card","props":{"title":"Session Zero conversation"},"children":transcript}), - serde_json::json!({ - "id":"session-zero.channel","kind":"control.select","props":{"label":"Speak at","value":shared_channel_id}, - "stateBindings":[local_draft_binding("channel_id", "choice")], - "children":[ - {"id":"channel.shared","kind":"control.option","props":{"value":shared_channel_id,"label":"Shared table"},"children":[]}, - {"id":"channel.private","kind":"control.option","props":{"value":private_channel_id.clone().unwrap_or_default(),"label":"Private DM","disabled":private_channel_id.is_none()},"children":[]} - ] - }), - serde_json::json!({ - "id":"session-zero.message.draft","kind":"control.input.textarea","props":{"label":"Tell the DM or table","rows":4,"placeholder":"Describe what you want, ask a question, or counter a proposal."}, - "stateBindings":[local_draft_binding("text", "string")],"children":[] - }), - command_control( - "session-zero.message.send", - "Send", - "session_zero.message.send", - serde_json::json!({"expected_revision":state.revision}), - &["channel_id", "text"], - ), - serde_json::json!({"id":"session-zero.boundary.topic","kind":"control.input.text","props":{"label":"Private boundary topic","placeholder":"What should the campaign avoid, veil, or ask about first?"},"stateBindings":[local_draft_binding("topic", "string")],"children":[]}), - serde_json::json!({"id":"session-zero.boundary.level","kind":"control.select","props":{"label":"Boundary level","value":"ask_first"},"stateBindings":[local_draft_binding("level", "choice")],"children":[ - {"id":"boundary.ask-first","kind":"control.option","props":{"value":"ask_first","label":"Ask first"},"children":[]}, - {"id":"boundary.veil","kind":"control.option","props":{"value":"veil","label":"Veil"},"children":[]}, - {"id":"boundary.line","kind":"control.option","props":{"value":"line","label":"Line"},"children":[]} - ]}), - command_control( - "session-zero.boundary.set", - "Add private boundary", - "session_zero.boundary.set", - serde_json::json!({"expected_revision":state.revision}), - &["topic", "level"], - ), - serde_json::json!({"id":"session-zero.decision.counter","kind":"control.input.textarea","props":{"label":"Counterproposal","rows":3,"maxLength":2000,"placeholder":"State the replacement you want the table or DM to consider (up to 2,000 characters)."},"stateBindings":[local_draft_binding("counter", "string")],"children":[]}), - ]; - if state.roster_locked - && state.preview.is_none() - && matches!( - state.status, - SessionZeroStatus::RosterLocked | SessionZeroStatus::Drafting - ) - && let Err(error) = state.compilation_brief() - { - children.insert( - 2, - serde_json::json!({ - "id":"session-zero.compilation-readiness", - "kind":"card", - "props":{"title":"Before compilation"}, - "children":[{ - "id":"session-zero.compilation-readiness.text", - "kind":"text", - "props":{"value":error.to_string()}, - "children":[] - }] - }), - ); - } - for boundary in &private_boundaries { - children.push(serde_json::json!({ - "id":format!("session-zero.boundary.{}",boundary.id), - "kind":"card", - "props":{"title":format!("Your boundary · {:?}",boundary.level)}, - "children":[ - {"id":format!("session-zero.boundary.{}.topic",boundary.id),"kind":"text","props":{"value":boundary.topic},"children":[]}, - command_control(&format!("session-zero.boundary.{}.remove",boundary.id), "Remove boundary", "session_zero.boundary.remove", serde_json::json!({"expected_revision":state.revision,"target":boundary.id}), &[]) - ] - })); - } - for decision in visible_decisions - .iter() - .filter(|decision| !decision.resolved) - { - let mut decision_children = vec![serde_json::json!({ - "id":format!("session-zero.decision.{}.proposal",decision.id), - "kind":"text", - "props":{"value":decision.pending_counter.as_ref().unwrap_or(&decision.proposed_resolution)}, - "children":[] - })]; - let payload_summary = display_decision_payload(decision); - if !payload_summary.is_empty() { - decision_children.push(serde_json::json!({ - "id":format!("session-zero.decision.{}.typed-payload",decision.id), - "kind":"text", - "props":{"value":format!("{}:\n{payload_summary}", if decision.pending_counter.is_some() { "Retired typed change" } else { "Exact typed change" })}, - "children":[] - })); - } - if decision.pending_counter.is_some() { - decision_children.push(serde_json::json!({ - "id":format!("session-zero.decision.{}.pending",decision.id), - "kind":"text", - "props":{"value":"Counterproposal recorded. The previous typed proposal has been retired; the DM is preparing a fresh decision."}, - "children":[] - })); - decision_children.push(command_control( - &format!("session-zero.decision.{}.retry-counter", decision.id), - "Revise / retry counter", - "session_zero.decision.resolve", - serde_json::json!({"expected_revision":state.revision,"decision_id":decision.id,"action":"retry_counter","counter":null}), - &[], - )); - } else { - if decision_has_typed_payload(decision) { - decision_children.push(command_control(&format!("session-zero.decision.{}.accept",decision.id), "Accept", "session_zero.decision.resolve", serde_json::json!({"expected_revision":state.revision,"decision_id":decision.id,"action":"accept","counter":null}), &[])); - } else { - decision_children.push(serde_json::json!({ - "id":format!("session-zero.decision.{}.missing-payload",decision.id), - "kind":"text", - "props":{"value":"This discussion has no typed state change attached and cannot be accepted. Counter it or ask the DM for an exact proposal."}, - "children":[] - })); - } - decision_children.extend([ - command_control(&format!("session-zero.decision.{}.decline",decision.id), "Decline", "session_zero.decision.resolve", serde_json::json!({"expected_revision":state.revision,"decision_id":decision.id,"action":"decline","counter":null}), &[]), - command_control(&format!("session-zero.decision.{}.counter",decision.id), "Counter", "session_zero.decision.resolve", serde_json::json!({"expected_revision":state.revision,"decision_id":decision.id,"action":"counter"}), &["counter"]), - command_control(&format!("session-zero.decision.{}.discuss",decision.id), "Discuss", "session_zero.message.send", serde_json::json!({"expected_revision":state.revision,"text":format!("I want to discuss this proposal before deciding: {}",decision.prompt)}), &["channel_id"]), - ]); - } - children.push(serde_json::json!({ - "id":format!("session-zero.decision.{}",decision.id), - "kind":"card", - "props":{"title":decision.prompt}, - "children":decision_children - })); - } - if member.is_host && !state.roster_locked { - children.push(serde_json::json!({"id":"session-zero.invite-count","kind":"control.input.number","props":{"label":"Invitations","value":1,"min":1,"max":7},"stateBindings":[local_draft_binding("count", "number")],"children":[]})); - children.push(command_control( - "session-zero.invites.create", - "Create invitations", - "session_zero.invites.create", - serde_json::json!({}), - &["count"], - )); - children.push(command_control( - "session-zero.roster.lock", - "Lock roster", - "session_zero.roster.lock", - serde_json::json!({"expected_revision":state.revision}), - &[], - )); - for candidate in state - .members - .values() - .filter(|candidate| candidate.active && candidate.id != member.id) - { - children.push(command_control( - &format!("session-zero.member.{}.remove", candidate.id), - &format!("Remove {}", candidate.display_name), - "session_zero.member.remove", - serde_json::json!({"expected_revision":state.revision,"target":candidate.id}), - &[], - )); - } - } - if !member.is_host && !state.roster_locked { - children.push(command_control( - "session-zero.leave", - "Leave Session Zero", - "session_zero.leave", - serde_json::json!({"expected_revision":state.revision}), - &[], - )); - } - if member.is_host { - children.push(command_control( - "session-zero.archive", - "Archive Session Zero", - "session_zero.archive", - serde_json::json!({"expected_revision":state.revision}), - &[], - )); - } - if let Some(preview) = state.preview.as_ref() { - children.push(serde_json::json!({ - "id":"session-zero.world-preview", - "kind":"card", - "props":{"title":"Compiled world preview"}, - "children":[{ - "id":"session-zero.world-preview.text", - "kind":"text", - "props":{"value":display_world_preview(preview, &player_actor_ids)}, - "children":[] - }] - })); - if !preview.evidence_coverage.is_empty() { - let evidence_summary = preview - .evidence_coverage - .iter() - .map(|coverage| { - format!( - "{} · {:?}\n{}", - coverage.source_id, coverage.lane, coverage.rationale - ) - }) - .collect::>() - .join("\n\n"); - children.push(serde_json::json!({ - "id":"session-zero.evidence-coverage", - "kind":"card", - "props":{"title":"Vault evidence use"}, - "children":[{ - "id":"session-zero.evidence-coverage.text", - "kind":"text", - "props":{"value":evidence_summary}, - "children":[] - }] - })); - } - if !preview.branch_assumptions.is_empty() { - children.push(serde_json::json!({ - "id":"session-zero.branch-assumptions", - "kind":"card", - "props":{"title":"Branch-local assumptions requiring approval"}, - "children":[{ - "id":"session-zero.branch-assumptions.text", - "kind":"text", - "props":{"value":preview.branch_assumptions.iter().map(|assumption|format!("• {assumption}")).collect::>().join("\n")}, - "children":[] - }] - })); - } - } - if let Some(preview) = state.preview.as_ref() - && !preview.gaps.is_empty() - { - children.push(serde_json::json!({ - "id":"session-zero.evidence-gaps", - "kind":"card", - "props":{"title":"Evidence gaps requiring table approval"}, - "children":[{ - "id":"session-zero.evidence-gaps.text", - "kind":"text", - "props":{"value":preview.gaps.iter().map(|gap|format!("• {gap}")).collect::>().join("\n")}, - "children":[] - }] - })); - } - if member.is_host - && matches!( - state.status, - SessionZeroStatus::RosterLocked | SessionZeroStatus::Drafting - ) - && state.preview.is_none() - && state.compilation_brief().is_ok() - { - children.push(command_control( - "session-zero.compile", - "Compile campaign preview", - "session_zero.compile", - serde_json::json!({"expected_revision":state.revision}), - &[], - )); - } - if member.is_host - && state.preview.is_some() - && matches!( - state.status, - SessionZeroStatus::Drafting - | SessionZeroStatus::RosterLocked - | SessionZeroStatus::Review - ) - { - children.push(command_control( - "session-zero.discard-preview", - "Discard this preview and continue drafting", - "session_zero.preview.discard", - serde_json::json!({"expected_revision":state.revision}), - &[], - )); - } - if member.is_host - && matches!( - state.status, - SessionZeroStatus::RosterLocked | SessionZeroStatus::Drafting - ) - && state - .preview - .as_ref() - .is_some_and(|preview| !preview.gaps.is_empty()) - { - children.push(command_control( - "session-zero.review-compilation-gaps", - "Review this exact preview with its evidence gaps", - "session_zero.compilation_gaps.review", - serde_json::json!({"expected_revision":state.revision}), - &[], - )); - } - if state.status == SessionZeroStatus::Review { - if !relationship_subjects.is_empty() { - let relationship_summary = relationship_subjects - .iter() - .map(|subject| { - let location = subject - .location_name - .as_deref() - .or(subject.location_id.as_deref()) - .map(|value| format!(" · located at {value}")) - .unwrap_or_default(); - let actor_state = subject - .counterpart_actor_state - .as_ref() - .map(|state| format!( - "\nCounterpart-owned state:\nCapabilities: {}\nKnowledge: {}\nEquipment: {}\nConditions: {}\nObligations: {}\nRelationships: {}\nGoals: {}", - display_values(&state.capabilities), - display_values(&state.knowledge), - display_values(&state.equipment), - display_values(&state.conditions), - display_values(&state.obligations), - if state.relationships.is_empty() { - "none".into() - } else { - state - .relationships - .iter() - .map(|(subject_id, description)| { - format!("{subject_id}: {description}") - }) - .collect::>() - .join(", ") - }, - display_values(&state.goals), - )) - .unwrap_or_default(); - format!( - "{} · {}{}\n{}{}", - subject.name, - subject.subject_kind, - location, - subject.relationship, - actor_state, - ) - }) - .collect::>() - .join("\n\n"); - children.push(serde_json::json!({ - "id":"session-zero.private-relationship-subjects", - "kind":"card", - "props":{"title":"Your private compiled relationships"}, - "children":[{ - "id":"session-zero.private-relationship-subjects.text", - "kind":"text", - "props":{"value":relationship_summary}, - "children":[] - }] - })); - } - children.push(command_control( - "session-zero.approve", - if state.approvals.contains_key(&member.id) { - "Approved" - } else { - "Approve exact world preview, shared contract, and private draft" - }, - "session_zero.approve", - serde_json::json!({"expected_revision":state.revision}), - &[], - )); - if member.is_host && state.approved_brief().is_ok() { - children.push(command_control( - "session-zero.publish", - "Publish campaign", - "session_zero.publish", - serde_json::json!({"expected_revision":state.revision}), - &[], - )); - } - } - children.push(command_control( - "ghostlight.logout", - "Sign out", - "app.auth.logout", - serde_json::json!({}), - &[], - )); - Ok(serde_json::json!({ - "type": "surface-state", - "schema": "gamecult.eve.surface.v1", - "providerId": "gamecult.ghostlight.dungeon", - "providerKind": "narrative.session-zero", - "title": state.name, - "version": state.revision, - "updatedAtUtc": Utc::now().to_rfc3339(), - "session_zero": { - "id": state.id, - "status": state.status, - "revision": state.revision, - "roster_locked": state.roster_locked, - "viewer_member_id": member.id, - "viewer_is_host": member.is_host, - "active_members": public_party.len(), - "pooled_cell_allowance": state.pooled_cell_allowance(), - "contract": state.contract, - "aggregate_boundaries": state.aggregate_boundaries, - "public_party": public_party, - "private_character": state.character_drafts[&member.id], - "private_boundaries": private_boundaries, - "decisions": visible_decisions, - "channels": channels, - "preview": private_preview, - "shared_digest": state.shared_digest()?, - "character_digest": state.character_digest(&member.id)?, - "world_preview_digest": state.world_preview_digest().ok(), - "approved": state.approvals.contains_key(&member.id), - "publish_ready": state.approved_brief().is_ok(), - }, - "surface": { - "id": "ghostlight.play", - "root": { - "id": "session-zero.root", - "kind": "surface", - "props": {}, - "children": children - }, - "styles": {"tokens": { - "colorBackground": "#0c1110", - "colorPanel": "#17201d", - "colorText": "#e8e1cf", - "colorMuted": "#9aa69f", - "colorAccent": "#d49b58" - }} - }, - "commands": [ - eve_command("session_zero.message.send", "ghostlight.session_zero_message_send.v1", &["channel_id","text"]), - eve_command("session_zero.boundary.set", "ghostlight.session_zero_boundary_set.v1", &["topic","level"]), - eve_command("session_zero.boundary.remove", "ghostlight.session_zero_boundary_remove.v1", &[]), - eve_command("session_zero.decision.resolve", "ghostlight.session_zero_decision_resolve.v1", &[]), - eve_command("session_zero.invites.create", "ghostlight.session_zero_invites_create.v1", &["count"]), - eve_command("session_zero.leave", "ghostlight.session_zero_revision_command.v1", &[]), - eve_command("session_zero.archive", "ghostlight.session_zero_revision_command.v1", &[]), - eve_command("session_zero.member.remove", "ghostlight.session_zero_member_remove.v1", &[]), - eve_command("session_zero.roster.lock", "ghostlight.session_zero_revision_command.v1", &[]), - eve_command("session_zero.compile", "ghostlight.session_zero_revision_command.v1", &[]), - eve_command("session_zero.compilation_gaps.review", "ghostlight.session_zero_revision_command.v1", &[]), - eve_command("session_zero.preview.discard", "ghostlight.session_zero_revision_command.v1", &[]), - eve_command("session_zero.approve", "ghostlight.session_zero_revision_command.v1", &[]), - eve_command("session_zero.publish", "ghostlight.session_zero_revision_command.v1", &[]), - eve_command("app.auth.logout", "ghostlight.app_logout.v1", &[]) - ] - })) -} - -fn local_draft_binding(name: &str, value_kind: &str) -> serde_json::Value { - serde_json::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: serde_json::Value, - bindings: &[&str], -) -> serde_json::Value { - let mut action = action.as_object().cloned().unwrap_or_default(); - action.insert("command".into(), serde_json::Value::String(command.into())); - serde_json::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]) -> serde_json::Value { - serde_json::json!({ - "schema":"gamecult.eve.command.v1", - "command":command, - "payloadSchema":payload_schema, - "captureBindings":bindings, - "transport":"https-json", - "authority":"SessionZeroKernel" - }) -} - -fn session_status_label(status: &SessionZeroStatus) -> &'static str { - match status { - SessionZeroStatus::Drafting => "Drafting", - SessionZeroStatus::RosterLocked => "Roster locked", - SessionZeroStatus::Compiling => "Compiling", - SessionZeroStatus::Review => "Review", - SessionZeroStatus::Published => "Published", - SessionZeroStatus::Archived => "Archived", - } -} - -fn execute( - store: &CampaignStore, - state_id: Uuid, - command: SessionZeroCommand, -) -> Result { - let key = state_id.to_string(); - let (row, mut state) = store - .load::("session_zero.v1", &key)? - .ok_or_else(|| anyhow!("session zero state vanished"))?; - let mut invite_tokens = Vec::new(); - match command { - SessionZeroCommand::CreateInvites { - actor_account_hash, - count, - } => { - require_host(&state, &actor_account_hash)?; - if state.roster_locked { - return Err(anyhow!("roster is locked")); - } - let available = MAX_SESSION_ZERO_MEMBERS.saturating_sub( - state - .members - .values() - .filter(|member| member.active) - .count(), - ); - let count = usize::from(count); - if count == 0 || count > available { - return Err(anyhow!("invite count exceeds available seats")); - } - for _ in 0..count { - let token = Uuid::new_v4().simple().to_string(); - let token_hash = secret_hash(&token); - let id = format!("invite:{}", Uuid::new_v4().simple()); - state.invites.insert( - id.clone(), - SessionZeroInvite { - schema: "ghostlight.session_zero_invite.v1".into(), - id, - token_hash, - expires_at: Utc::now() + Duration::days(7), - consumed_by_member_id: None, - }, - ); - invite_tokens.push(token); - } - } - SessionZeroCommand::Join { - token, - account_hash, - display_name, - cell_allowance, - } => { - if state.roster_locked { - return Err(anyhow!("roster is locked")); - } - if state.member_for_account(&account_hash).is_some() { - return Err(anyhow!("account is already a member")); - } - if state - .members - .values() - .filter(|member| member.active) - .count() - >= MAX_SESSION_ZERO_MEMBERS - { - return Err(anyhow!("session zero is full")); - } - validate_bounded("display name", &display_name, 1, 80)?; - if cell_allowance == 0 || cell_allowance > OPERATOR_CELL_CEILING { - return Err(anyhow!("Persona-cell entitlement is out of range")); - } - let token_hash = secret_hash(&token); - let invite = state - .invites - .values_mut() - .find(|invite| { - invite.token_hash == token_hash - && invite.expires_at > Utc::now() - && invite.consumed_by_member_id.is_none() - }) - .ok_or_else(|| anyhow!("invite is invalid, expired, or consumed"))?; - let member_id = format!("member:{}", Uuid::new_v4().simple()); - invite.consumed_by_member_id = Some(member_id.clone()); - state.members.insert( - member_id.clone(), - SessionZeroMember { - schema: "ghostlight.session_zero_member.v1".into(), - id: member_id.clone(), - account_hash, - display_name: display_name.clone(), - is_host: false, - active: true, - cell_allowance, - joined_at: Utc::now(), - }, - ); - let channel_id = format!("private:{member_id}"); - state.channels.insert( - channel_id.clone(), - SessionZeroChannel { - schema: "ghostlight.session_zero_channel.v1".into(), - id: channel_id, - kind: SessionZeroChannelKind::PrivateDm, - member_id: Some(member_id.clone()), - revision: 0, - message_ids: vec![], - }, - ); - state.character_drafts.insert( - member_id.clone(), - CharacterDraft { - schema: "ghostlight.character_draft.v1".into(), - member_id: member_id.clone(), - actor_id: format!("player:{}", Uuid::new_v4().simple()), - name: display_name, - ..CharacterDraft::default() - }, - ); - state.character_epochs.insert(member_id, 0); - shared_changed(&mut state); - } - SessionZeroCommand::Leave { - actor_account_hash, - expected_revision, - } => { - require_revision(&state, expected_revision)?; - if state.roster_locked { - return Err(anyhow!("roster is locked")); - } - let member_id = state - .member_for_account(&actor_account_hash) - .ok_or_else(|| anyhow!("account is not a member"))? - .id - .clone(); - if member_id == state.host_member_id { - return Err(anyhow!( - "the host must archive rather than abandon the draft" - )); - } - state - .members - .get_mut(&member_id) - .expect("member exists") - .active = false; - state.approvals.remove(&member_id); - shared_changed(&mut state); - } - SessionZeroCommand::RemoveMember { - actor_account_hash, - expected_revision, - member_id, - } => { - require_revision(&state, expected_revision)?; - require_host(&state, &actor_account_hash)?; - if state.roster_locked { - return Err(anyhow!("roster is locked")); - } - if member_id == state.host_member_id { - return Err(anyhow!("the host cannot remove themselves")); - } - let member = state - .members - .get_mut(&member_id) - .ok_or_else(|| anyhow!("member does not exist"))?; - if !member.active { - return Err(anyhow!("member has already left")); - } - member.active = false; - state.approvals.remove(&member_id); - shared_changed(&mut state); - } - SessionZeroCommand::PostPlayerMessage { - actor_account_hash, - expected_revision, - channel_id, - text, - } => { - require_revision(&state, expected_revision)?; - validate_bounded("session zero message", &text, 1, 4_000)?; - let member = state - .member_for_account(&actor_account_hash) - .ok_or_else(|| anyhow!("account is not a member"))? - .clone(); - require_channel_access(&state, &member.id, &channel_id)?; - append_message( - &mut state, - channel_id, - Some(member.id), - SessionZeroSpeakerKind::Player, - text, - )?; - } - SessionZeroCommand::ApplyDmTurn { - expected_component_epoch, - expected_channel_revision, - channel_id, - member_id, - supersedes_countered_decision_id, - delta, - model_receipts, - } => { - let channel = state - .channels - .get(&channel_id) - .ok_or_else(|| anyhow!("session zero channel is missing"))?; - if channel.revision != expected_channel_revision { - return Err(anyhow!("stale Session Zero channel projection")); - } - let live_component_epoch = match channel.kind { - SessionZeroChannelKind::SharedTable => state.shared_epoch, - SessionZeroChannelKind::PrivateDm => *state - .character_epochs - .get( - member_id - .as_deref() - .ok_or_else(|| anyhow!("private member is missing"))?, - ) - .ok_or_else(|| anyhow!("private character epoch is missing"))?, - }; - if live_component_epoch != expected_component_epoch { - return Err(anyhow!("stale Session Zero component projection")); - } - validate_dm_delta(&state, &channel_id, member_id.as_deref(), &delta)?; - if let Some(decision_id) = supersedes_countered_decision_id.as_deref() { - let countered = state - .decisions - .get(decision_id) - .ok_or_else(|| anyhow!("countered decision is missing"))?; - if countered.resolved || countered.pending_counter.is_none() { - return Err(anyhow!("decision has no pending counterproposal")); - } - if countered.owner_member_id.as_deref() != member_id.as_deref() { - return Err(anyhow!("countered decision channel owner mismatch")); - } - validate_counter_replacement(countered, member_id.as_deref(), &delta)?; - } - let contract_changed = delta.contract_patch != CampaignContractPatch::default(); - let decisions_changed = !delta.decisions.is_empty(); - apply_contract_patch(&mut state.contract, delta.contract_patch); - if let Some(patch) = delta.character_patch { - let owner = member_id.as_deref().ok_or_else(|| { - anyhow!("shared DM turn cannot mutate private character state") - })?; - let draft = state - .character_drafts - .get_mut(owner) - .ok_or_else(|| anyhow!("character draft is missing"))?; - apply_character_patch(draft, patch); - character_changed(&mut state, owner); - } - for mut decision in delta.decisions { - if decision.id.trim().is_empty() { - decision.id = format!("decision:{}", Uuid::new_v4().simple()); - } - state.decisions.insert(decision.id.clone(), decision); - } - if let Some(decision_id) = supersedes_countered_decision_id { - state - .decisions - .get_mut(&decision_id) - .expect("countered decision was just validated") - .resolved = true; - } - if contract_changed || (decisions_changed && member_id.is_none()) { - shared_changed(&mut state); - } else if decisions_changed && let Some(owner) = member_id.as_deref() { - character_changed(&mut state, owner); - } - if !delta.dm_speech.trim().is_empty() { - append_message( - &mut state, - channel_id, - None, - SessionZeroSpeakerKind::Dm, - delta.dm_speech, - )?; - } - state.model_receipts.extend(model_receipts); - } - SessionZeroCommand::SetBoundary { - actor_account_hash, - expected_revision, - boundary_id, - topic, - normalized_topic, - level, - } => { - require_revision(&state, expected_revision)?; - validate_bounded("boundary topic", &topic, 1, 300)?; - validate_bounded("normalized boundary topic", &normalized_topic, 1, 160)?; - let member_id = state - .member_for_account(&actor_account_hash) - .ok_or_else(|| anyhow!("account is not a member"))? - .id - .clone(); - let id = boundary_id.unwrap_or_else(|| format!("boundary:{}", Uuid::new_v4().simple())); - if let Some(existing) = state.boundaries.get(&id) - && existing.owner_member_id != member_id - { - return Err(anyhow!("only the boundary owner may change it")); - } - let now = Utc::now(); - let created_at = state - .boundaries - .get(&id) - .map_or(now, |value| value.created_at); - state.boundaries.insert( - id.clone(), - ContentBoundary { - schema: "ghostlight.content_boundary.v1".into(), - id, - owner_member_id: member_id.clone(), - topic, - normalized_topic, - level, - created_at, - updated_at: now, - }, - ); - let before = state.aggregate_boundaries.clone(); - state.aggregate_boundaries = aggregate_boundaries_with_inherited( - &state.boundaries, - &state.inherited_aggregate_boundaries, - ); - state.boundary_epoch = state.boundary_epoch.saturating_add(1); - state.approvals.remove(&member_id); - if before != state.aggregate_boundaries { - shared_changed(&mut state); - } else { - retire_preview(&mut state); - } - } - SessionZeroCommand::RemoveBoundary { - actor_account_hash, - expected_revision, - boundary_id, - } => { - require_revision(&state, expected_revision)?; - let member_id = state - .member_for_account(&actor_account_hash) - .ok_or_else(|| anyhow!("account is not a member"))? - .id - .clone(); - let existing = state - .boundaries - .get(&boundary_id) - .ok_or_else(|| anyhow!("boundary does not exist"))?; - if existing.owner_member_id != member_id { - return Err(anyhow!("only the boundary owner may remove it")); - } - let before = state.aggregate_boundaries.clone(); - state.boundaries.remove(&boundary_id); - state.aggregate_boundaries = aggregate_boundaries_with_inherited( - &state.boundaries, - &state.inherited_aggregate_boundaries, - ); - state.boundary_epoch = state.boundary_epoch.saturating_add(1); - state.approvals.remove(&member_id); - if before != state.aggregate_boundaries { - shared_changed(&mut state); - } else { - retire_preview(&mut state); - } - } - SessionZeroCommand::ResolveDecision { - actor_account_hash, - expected_revision, - decision_id, - resolution, - counter, - } => { - require_revision(&state, expected_revision)?; - let member_id = state - .member_for_account(&actor_account_hash) - .ok_or_else(|| anyhow!("account is not a member"))? - .id - .clone(); - let decision = state - .decisions - .get(&decision_id) - .cloned() - .ok_or_else(|| anyhow!("decision is missing"))?; - if decision.resolved { - return Err(anyhow!("decision is already resolved")); - } - if decision - .owner_member_id - .as_deref() - .is_some_and(|owner| owner != member_id) - { - return Err(anyhow!("decision belongs to another member")); - } - if resolution == SessionZeroDecisionResolution::Accept { - if decision.pending_counter.is_some() { - return Err(anyhow!("counterproposal is awaiting a fresh DM decision")); - } - if !decision_has_typed_payload(&decision) { - return Err(anyhow!( - "decision has no typed state change to accept; discuss or counter it" - )); - } - if let Some(patch) = decision.proposed_contract_patch.clone() { - if decision.owner_member_id.is_some() { - return Err(anyhow!( - "a private decision cannot amend the shared campaign contract" - )); - } - apply_contract_patch(&mut state.contract, patch); - shared_changed(&mut state); - } - if let Some(permission) = decision.proposed_extraordinary_permission.clone() { - if decision.owner_member_id.as_deref() != Some(member_id.as_str()) { - return Err(anyhow!( - "extraordinary permission must belong to the accepting player" - )); - } - let draft = state - .character_drafts - .get_mut(&member_id) - .ok_or_else(|| anyhow!("character draft is missing"))?; - if permission.actor_id != draft.actor_id { - return Err(anyhow!("extraordinary permission targets another actor")); - } - if permission.name.trim().is_empty() - || permission.reliable_scope.trim().is_empty() - || permission.effect_ceiling.trim().is_empty() - { - return Err(anyhow!("extraordinary permission is incomplete")); - } - draft - .extraordinary_permissions - .retain(|existing| existing.id != permission.id); - draft.extraordinary_permissions.push(permission); - character_changed(&mut state, &member_id); - } - if let Some(patch) = decision.proposed_character_patch.clone() { - if decision.owner_member_id.as_deref() != Some(member_id.as_str()) { - return Err(anyhow!( - "character proposal must belong to the accepting player" - )); - } - let draft = state - .character_drafts - .get_mut(&member_id) - .ok_or_else(|| anyhow!("character draft is missing"))?; - apply_character_patch(draft, patch); - character_changed(&mut state, &member_id); - } - state - .decisions - .get_mut(&decision_id) - .expect("decision was just validated") - .resolved = true; - } else if resolution == SessionZeroDecisionResolution::Counter { - let proposed_resolution = counter - .filter(|value| !value.trim().is_empty()) - .ok_or_else(|| anyhow!("counterproposal is required"))?; - validate_bounded("counterproposal", &proposed_resolution, 1, 2_000)?; - let channel_id = decision - .owner_member_id - .as_ref() - .map(|owner| format!("private:{owner}")) - .unwrap_or_else(|| "shared:table".into()); - let prompt = decision.prompt.clone(); - let private_decision = decision.owner_member_id.is_some(); - let decision = state - .decisions - .get_mut(&decision_id) - .expect("decision was just validated"); - decision.pending_counter = Some(proposed_resolution.clone()); - decision.resolved = false; - append_message( - &mut state, - channel_id, - Some(member_id.clone()), - SessionZeroSpeakerKind::Player, - format!("Counterproposal to '{}': {}", prompt, proposed_resolution), - )?; - if private_decision { - character_changed(&mut state, &member_id); - } else { - shared_changed(&mut state); - } - } else { - if counter.is_some() { - return Err(anyhow!( - "declining a decision cannot include a counterproposal" - )); - } - state - .decisions - .get_mut(&decision_id) - .expect("decision was just validated") - .resolved = true; - } - retire_preview(&mut state); - } - SessionZeroCommand::LockRoster { - actor_account_hash, - expected_revision, - } => { - require_revision(&state, expected_revision)?; - require_host(&state, &actor_account_hash)?; - if state - .members - .values() - .filter(|member| member.active) - .count() - == 0 - { - return Err(anyhow!("roster cannot be empty")); - } - state.roster_locked = true; - state.status = SessionZeroStatus::RosterLocked; - shared_changed(&mut state); - } - SessionZeroCommand::BeginCompilation { - actor_account_hash, - expected_revision, - } => { - require_revision(&state, expected_revision)?; - require_host(&state, &actor_account_hash)?; - state.compilation_brief()?; - retire_preview(&mut state); - state.status = SessionZeroStatus::Compiling; - } - SessionZeroCommand::ReviewCompilationGaps { - actor_account_hash, - expected_revision, - } => { - require_revision(&state, expected_revision)?; - require_host(&state, &actor_account_hash)?; - if !matches!( - state.status, - SessionZeroStatus::Drafting | SessionZeroStatus::RosterLocked - ) { - return Err(anyhow!("gap-bearing preview is not awaiting review")); - } - state.compilation_brief()?; - let preview = state - .preview - .as_ref() - .ok_or_else(|| anyhow!("gap-bearing preview is missing"))?; - if preview.gaps.is_empty() { - return Err(anyhow!("compiled preview has no evidence gaps to review")); - } - let shared_digest = state.shared_digest()?; - if state.preview_shared_digest.as_deref() != Some(shared_digest.as_str()) { - return Err(anyhow!( - "compiled preview no longer matches the shared draft" - )); - } - for member in state.members.values().filter(|member| member.active) { - if state.preview_character_digests.get(&member.id) - != Some(&state.character_digest(&member.id)?) - { - return Err(anyhow!( - "compiled preview no longer matches every character" - )); - } - } - state.status = SessionZeroStatus::Review; - } - SessionZeroCommand::DiscardPreview { - actor_account_hash, - expected_revision, - } => { - require_revision(&state, expected_revision)?; - require_host(&state, &actor_account_hash)?; - if state.preview.is_none() { - return Err(anyhow!("compiled preview is missing")); - } - if matches!( - state.status, - SessionZeroStatus::Compiling - | SessionZeroStatus::Published - | SessionZeroStatus::Archived - ) { - return Err(anyhow!("compiled preview cannot be discarded now")); - } - state.approvals.clear(); - retire_preview(&mut state); - } - SessionZeroCommand::InstallPreview { - expected_revision, - preview, - model_receipts, - } => { - require_revision(&state, expected_revision)?; - if !state.roster_locked { - return Err(anyhow!("roster must be locked before compilation")); - } - if state - .decisions - .values() - .any(|decision| decision.material && !decision.resolved) - { - return Err(anyhow!("material decisions remain unresolved")); - } - state.approvals.clear(); - state.preview_shared_digest = Some(state.shared_digest()?); - state.preview_character_digests.clear(); - for member in state.members.values().filter(|member| member.active) { - state - .preview_character_digests - .insert(member.id.clone(), state.character_digest(&member.id)?); - } - state.preview_evidence_coverage = preview.evidence_coverage.clone(); - state.preview_model_receipts.clone_from(&model_receipts); - state.model_receipts.extend(model_receipts); - let has_gaps = !preview.gaps.is_empty(); - let gap_text = preview.gaps.join("\n- "); - state.preview = Some(preview); - if has_gaps { - append_message( - &mut state, - "shared:table".into(), - None, - SessionZeroSpeakerKind::Dm, - format!( - "The Vault cannot yet ground these material parts of the opening:\n- {gap_text}\n\nThis exact preview is retained. The host may open it for unanimous approval as branch-local campaign material, or the table may revise the draft before compiling again." - ), - )?; - state.status = SessionZeroStatus::Drafting; - } else { - state.status = SessionZeroStatus::Review; - } - } - SessionZeroCommand::CompilationFailed { - expected_revision, - message, - } => { - require_revision(&state, expected_revision)?; - validate_bounded("compilation failure", &message, 1, 4_000)?; - state.status = SessionZeroStatus::Drafting; - append_message( - &mut state, - "shared:table".into(), - None, - SessionZeroSpeakerKind::Dm, - format!( - "The world seed did not pass compilation safely: {message}\n\nNo campaign state was published. Let's revise the draft and try again." - ), - )?; - } - SessionZeroCommand::CompilationEvidenceUnavailable { expected_revision } => { - require_revision(&state, expected_revision)?; - state.status = SessionZeroStatus::Drafting; - let decision_id = "decision:vault-retrieval-required".to_owned(); - state.decisions.insert( - decision_id.clone(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: decision_id, - owner_member_id: None, - prompt: "What must happen before this exact draft can receive a grounded world preview?".into(), - proposed_resolution: "Keep the negotiated draft unchanged and retry compilation only after Vault retrieval is available. Do not substitute nearby stories, branch inventions, or remembered setting vibes for evidence.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: true, - }, - ); - append_message( - &mut state, - "shared:table".into(), - None, - SessionZeroSpeakerKind::Dm, - "The lore Vault is currently unreachable, so I cannot distinguish missing canon from missing retrieval. No preview, branch assumption, or campaign state was published. I have kept the exact draft and queued an explicit decision to retry only after grounded evidence is available.".into(), - )?; - } - SessionZeroCommand::Approve { - actor_account_hash, - expected_revision, - } => { - require_revision(&state, expected_revision)?; - if state.status != SessionZeroStatus::Review || state.preview.is_none() { - return Err(anyhow!("there is no final preview to approve")); - } - let member = state - .member_for_account(&actor_account_hash) - .ok_or_else(|| anyhow!("account is not a member"))?; - let member_id = member.id.clone(); - let shared_digest = state.shared_digest()?; - let character_digest = state.character_digest(&member_id)?; - let world_preview_digest = state.world_preview_digest()?; - if state.preview_shared_digest.as_deref() != Some(shared_digest.as_str()) - || state.preview_character_digests.get(&member_id) != Some(&character_digest) - { - return Err(anyhow!("preview is stale")); - } - state.approvals.insert( - member_id.clone(), - SessionZeroApproval { - schema: "ghostlight.session_zero_approval.v1".into(), - member_id, - shared_digest, - character_digest, - world_preview_digest, - approved_at: Utc::now(), - }, - ); - } - SessionZeroCommand::MarkPublished { - actor_account_hash, - expected_revision, - campaign_id, - seed_digest, - } => { - require_revision(&state, expected_revision)?; - require_host(&state, &actor_account_hash)?; - let _ = state.approved_brief()?; - if let (Some(existing_campaign), Some(existing_digest)) = ( - state.published_campaign_id, - state.published_seed_digest.as_ref(), - ) { - if existing_campaign != campaign_id || existing_digest != &seed_digest { - return Err(anyhow!("session zero was published with another seed")); - } - } - state.published_campaign_id = Some(campaign_id); - state.published_seed_digest = Some(seed_digest); - state.status = SessionZeroStatus::Published; - } - SessionZeroCommand::Archive { - actor_account_hash, - expected_revision, - } => { - require_revision(&state, expected_revision)?; - require_host(&state, &actor_account_hash)?; - state.status = SessionZeroStatus::Archived; - } - } - state.revision = state.revision.saturating_add(1); - state.updated_at = Utc::now(); - store.replace(&row, "ghostlight.session_zero.v1", &state)?; - Ok(SessionZeroCommandResult { - state, - invite_tokens, - }) -} - -fn append_message( - state: &mut SessionZeroState, - channel_id: String, - author_member_id: Option, - speaker: SessionZeroSpeakerKind, - text: String, -) -> Result<()> { - let channel = state - .channels - .get_mut(&channel_id) - .ok_or_else(|| anyhow!("session zero channel is missing"))?; - let id = format!("message:{}", Uuid::new_v4().simple()); - state.messages.insert( - id.clone(), - SessionZeroMessage { - schema: "ghostlight.session_zero_message.v1".into(), - id: id.clone(), - channel_id, - author_member_id, - speaker, - text, - session_revision: state.revision, - created_at: Utc::now(), - }, - ); - channel.message_ids.push(id); - channel.revision = channel.revision.saturating_add(1); - Ok(()) -} - -fn validate_dm_delta( - state: &SessionZeroState, - channel_id: &str, - member_id: Option<&str>, - delta: &SessionZeroDelta, -) -> Result<()> { - let channel = state - .channels - .get(channel_id) - .ok_or_else(|| anyhow!("session zero channel is missing"))?; - match channel.kind { - SessionZeroChannelKind::SharedTable => { - if member_id.is_some() || delta.character_patch.is_some() { - return Err(anyhow!( - "shared DM turn cannot mutate private character state" - )); - } - if delta.decisions.iter().any(|decision| { - decision.owner_member_id.is_some() - || decision.proposed_character_patch.is_some() - || decision.proposed_extraordinary_permission.is_some() - }) { - return Err(anyhow!( - "shared DM decisions cannot mutate private character state" - )); - } - } - SessionZeroChannelKind::PrivateDm => { - if channel.member_id.as_deref() != member_id { - return Err(anyhow!("private DM turn owner mismatch")); - } - if contract_patch_changes_shared(&delta.contract_patch) { - return Err(anyhow!("private DM turn cannot mutate the shared contract")); - } - if delta.decisions.iter().any(|decision| { - decision.owner_member_id.as_deref() != member_id - || decision.proposed_contract_patch.is_some() - }) { - return Err(anyhow!( - "private DM decisions must belong to that player and cannot amend the shared contract" - )); - } - } - } - let proposes_contract_decision = delta - .decisions - .iter() - .any(|decision| decision.proposed_contract_patch.is_some()); - if contract_patch_changes_shared(&delta.contract_patch) && proposes_contract_decision { - return Err(anyhow!( - "a DM turn cannot directly edit the contract and offer a contract decision" - )); - } - let proposes_character_decision = delta - .decisions - .iter() - .any(|decision| decision.proposed_character_patch.is_some()); - if delta.character_patch.is_some() && proposes_character_decision { - return Err(anyhow!( - "a DM turn cannot directly edit a character and offer a character decision" - )); - } - validate_bounded("DM speech", &delta.dm_speech, 0, 6_000)?; - for reply in &delta.suggested_replies { - validate_bounded("suggested reply", reply, 1, 500)?; - } - let mut ids = BTreeSet::new(); - for decision in &delta.decisions { - if decision.pending_counter.is_some() { - return Err(anyhow!( - "DM proposals cannot author player counterproposal state" - )); - } - validate_bounded("decision ID", &decision.id, 1, 240)?; - validate_bounded("decision prompt", &decision.prompt, 1, 1_000)?; - validate_bounded( - "decision proposed resolution", - &decision.proposed_resolution, - 1, - 2_000, - )?; - if !decision_has_typed_payload(decision) { - return Err(anyhow!( - "DM decision must carry a non-empty typed state change" - )); - } - if !ids.insert(decision.id.clone()) || state.decisions.contains_key(&decision.id) { - return Err(anyhow!("DM turn contains a duplicate decision ID")); - } - } - Ok(()) -} - -fn decision_has_typed_payload(decision: &SessionZeroDecision) -> bool { - decision.proposed_extraordinary_permission.is_some() - || decision - .proposed_contract_patch - .as_ref() - .is_some_and(|patch| patch != &CampaignContractPatch::default()) - || decision - .proposed_character_patch - .as_ref() - .is_some_and(|patch| patch != &CharacterDraftPatch::default()) -} - -fn demote_legacy_nonmaterial_decisions(state: &mut SessionZeroState) -> bool { - let mut changed = false; - for decision in state.decisions.values_mut() { - let generated_opening = decision.id.starts_with("opening:") - && decision.owner_member_id.is_none() - && decision.proposed_contract_patch.is_some() - && decision.prompt.starts_with("Use '") - && decision - .prompt - .ends_with("' as the starting frame for further Session Zero discussion?"); - let payloadless_question = !decision_has_typed_payload(decision); - if decision.material && (generated_opening || payloadless_question) { - decision.material = false; - changed = true; - } - } - changed -} - -fn migrate_legacy_model_receipts(state: &mut SessionZeroState) -> bool { - if !state.model_receipts.is_empty() || state.preview_model_receipts.is_empty() { - return false; - } - let legacy = std::mem::take(&mut state.preview_model_receipts); - if state.preview.is_some() - && state.review_campaign_id.is_none() - && let Some(current_start) = legacy - .iter() - .rposition(|receipt| receipt.stage == "custom_retrieval_plan") - && let Some(current_end) = legacy - .iter() - .enumerate() - .skip(current_start) - .filter(|(_, receipt)| receipt.stage == "agency_compile") - .map(|(index, _)| index) - .next_back() - { - state.preview_model_receipts = legacy[current_start..=current_end].to_vec(); - } - state.model_receipts = legacy; - true -} - -fn validate_counter_replacement( - countered: &SessionZeroDecision, - member_id: Option<&str>, - delta: &SessionZeroDelta, -) -> Result<()> { - if delta.contract_patch != CampaignContractPatch::default() - || delta.character_patch.is_some() - || delta.decisions.len() != 1 - { - return Err(anyhow!( - "counter response must contain exactly one fresh decision and no direct state patch" - )); - } - let replacement = &delta.decisions[0]; - if replacement.resolved - || replacement.owner_member_id.as_deref() != member_id - || replacement.material != countered.material - { - return Err(anyhow!( - "counter response must preserve the decision owner and materiality" - )); - } - if decision_has_typed_payload(countered) { - if decision_payload_lanes(replacement) != decision_payload_lanes(countered) { - return Err(anyhow!( - "counter response must replace the same typed state lane" - )); - } - if let (Some(previous), Some(next)) = ( - countered.proposed_extraordinary_permission.as_ref(), - replacement.proposed_extraordinary_permission.as_ref(), - ) && (previous.id != next.id || previous.actor_id != next.actor_id) - { - return Err(anyhow!( - "counter response cannot change extraordinary permission identity or actor" - )); - } - } - Ok(()) -} - -fn decision_payload_lanes(decision: &SessionZeroDecision) -> [bool; 3] { - [ - decision.proposed_extraordinary_permission.is_some(), - decision.proposed_contract_patch.is_some(), - decision.proposed_character_patch.is_some(), - ] -} - -fn contract_patch_changes_shared(patch: &CampaignContractPatch) -> bool { - patch != &CampaignContractPatch::default() -} - -fn apply_contract_patch(contract: &mut CampaignContract, patch: CampaignContractPatch) { - macro_rules! apply { - ($field:ident) => { - if let Some(value) = patch.$field { - contract.$field = value; - } - }; - } - apply!(premise); - apply!(canon_horizon); - apply!(starting_where); - apply!(starting_when); - apply!(starting_pressure); - apply!(desired_goal); - apply!(tone); - apply!(themes); - apply!(pacing); - apply!(consequence_style); - apply!(narrative_focus); - apply!(party_bonds); - apply!(internal_tension); - apply!(dm_style); -} - -fn apply_character_patch(draft: &mut CharacterDraft, patch: CharacterDraftPatch) { - if let Some(value) = patch.name { - draft.name = value; - } - if let Some(value) = patch.public_premise { - draft.public_premise = value; - } - remove_exact(&mut draft.private_history, patch.private_history_remove); - extend_unique(&mut draft.private_history, patch.private_history_add); - remove_exact(&mut draft.secrets, patch.secrets_remove); - extend_unique(&mut draft.secrets, patch.secrets_add); - remove_exact(&mut draft.capabilities, patch.capabilities_remove); - extend_unique(&mut draft.capabilities, patch.capabilities_add); - remove_exact(&mut draft.knowledge, patch.knowledge_remove); - extend_unique(&mut draft.knowledge, patch.knowledge_add); - remove_exact(&mut draft.equipment, patch.equipment_remove); - extend_unique(&mut draft.equipment, patch.equipment_add); - for key in patch.relationship_removals { - draft.relationships.remove(&key); - } - draft.relationships.extend(patch.relationships); - remove_exact(&mut draft.obligations, patch.obligations_remove); - extend_unique(&mut draft.obligations, patch.obligations_add); - remove_exact(&mut draft.vulnerabilities, patch.vulnerabilities_remove); - extend_unique(&mut draft.vulnerabilities, patch.vulnerabilities_add); - remove_exact(&mut draft.goals, patch.goals_remove); - extend_unique(&mut draft.goals, patch.goals_add); -} - -fn remove_exact(target: &mut Vec, values: Vec) { - if values.is_empty() { - return; - } - let removals = values.into_iter().collect::>(); - target.retain(|value| !removals.contains(value)); -} - -fn extend_unique(target: &mut Vec, values: Vec) { - for value in values { - if !value.trim().is_empty() && !target.contains(&value) { - target.push(value); - } - } -} - -#[cfg(test)] -fn aggregate_boundaries(boundaries: &BTreeMap) -> Vec { - aggregate_boundaries_with_inherited(boundaries, &[]) -} - -fn aggregate_boundaries_with_inherited( - boundaries: &BTreeMap, - inherited: &[AggregatedBoundary], -) -> Vec { - let mut by_topic = BTreeMap::::new(); - for boundary in inherited { - by_topic.insert(boundary.normalized_topic.clone(), boundary.clone()); - } - for boundary in boundaries.values() { - let entry = by_topic - .entry(boundary.normalized_topic.clone()) - .or_insert_with(|| AggregatedBoundary { - normalized_topic: boundary.normalized_topic.clone(), - display_topic: boundary.topic.clone(), - level: boundary.level.clone(), - }); - if boundary.level.severity() > entry.level.severity() { - entry.level = boundary.level.clone(); - entry.display_topic = boundary.topic.clone(); - } - } - by_topic.into_values().collect() -} - -fn require_channel_access( - state: &SessionZeroState, - member_id: &str, - channel_id: &str, -) -> Result<()> { - let channel = state - .channels - .get(channel_id) - .ok_or_else(|| anyhow!("session zero channel is missing"))?; - if channel.kind == SessionZeroChannelKind::PrivateDm - && channel.member_id.as_deref() != Some(member_id) - { - return Err(anyhow!("private channel belongs to another member")); - } - Ok(()) -} - -fn require_host(state: &SessionZeroState, account_hash: &str) -> Result<()> { - let member = state - .member_for_account(account_hash) - .ok_or_else(|| anyhow!("account is not a member"))?; - if member.id != state.host_member_id || !member.is_host { - return Err(anyhow!("only the host may perform this command")); - } - Ok(()) -} - -fn require_revision(state: &SessionZeroState, expected: u64) -> Result<()> { - if state.revision != expected { - return Err(anyhow!("stale session zero revision")); - } - Ok(()) -} - -fn shared_changed(state: &mut SessionZeroState) { - state.shared_epoch = state.shared_epoch.saturating_add(1); - state.approvals.clear(); - retire_preview(state); -} - -fn character_changed(state: &mut SessionZeroState, member_id: &str) { - let epoch = state - .character_epochs - .entry(member_id.to_string()) - .or_default(); - *epoch = epoch.saturating_add(1); - state.approvals.remove(member_id); - retire_preview(state); -} - -fn retire_preview(state: &mut SessionZeroState) { - state.preview = None; - state.preview_model_receipts.clear(); - state.preview_shared_digest = None; - state.preview_character_digests.clear(); - if state.roster_locked { - state.status = SessionZeroStatus::RosterLocked; - } else { - state.status = SessionZeroStatus::Drafting; - } -} - -pub fn membership_from_session( - state: &SessionZeroState, - campaign_id: Uuid, -) -> Result { - let brief = state.approved_brief()?; - let mut members = BTreeMap::new(); - for member in state.members.values().filter(|member| member.active) { - let actor_id = brief - .member_actor_ids - .get(&member.id) - .ok_or_else(|| anyhow!("approved character has no actor binding"))? - .clone(); - members.insert( - member.id.clone(), - CampaignMember { - member_id: member.id.clone(), - account_hash: member.account_hash.clone(), - display_name: member.display_name.clone(), - actor_id, - is_host: member.is_host, - active: true, - cell_allowance: member.cell_allowance, - }, - ); - } - let extraordinary_permissions = brief - .characters - .iter() - .map(|character| { - ( - character.actor_id.clone(), - character.extraordinary_permissions.clone(), - ) - }) - .collect(); - Ok(CampaignMembership { - schema: "ghostlight.campaign_membership.v1".into(), - campaign_id, - governance_epoch: 0, - host_member_id: state.host_member_id.clone(), - members, - extraordinary_permissions, - }) -} - -pub fn publication_from_session( - state: &SessionZeroState, - campaign_id: Uuid, -) -> Result { - let approved_brief = state.approved_brief()?; - let membership = membership_from_session(state, campaign_id)?; - let preview = state - .preview - .as_ref() - .ok_or_else(|| anyhow!("approved world preview is missing"))?; - let approved_world_preview_digest = state.world_preview_digest()?; - let approved_evidence_gaps = preview.gaps.clone(); - let approved_branch_assumptions = preview.branch_assumptions.clone(); - let approved_seed_digest = digest(&( - campaign_id, - &approved_brief, - &membership, - &state.dm_persona, - &approved_world_preview_digest, - &approved_evidence_gaps, - &approved_branch_assumptions, - ))?; - Ok(PublishedSessionZeroSeed { - schema: "ghostlight.published_session_zero_seed.v1".into(), - session_zero_id: state.id, - approved_seed_digest, - contract: state.contract.clone(), - membership, - governance: CampaignGovernance { - schema: "ghostlight.campaign_governance.v1".into(), - campaign_id, - governance_epoch: 0, - time_advance_policy: "unanimous".into(), - pooled_cell_ceiling: state.pooled_cell_allowance(), - cooperative_shared_scene_only: true, - pvp_enabled: false, - }, - dm_persona: state.dm_persona.clone(), - approvals: state.approvals.values().cloned().collect(), - approved_brief, - approved_world_preview_digest, - approved_evidence_gaps, - approved_branch_assumptions, - boundaries: state.boundaries.values().cloned().collect(), - }) -} - -pub fn actor_from_character(draft: &CharacterDraft, location_id: String) -> ActorState { - ActorState { - id: draft.actor_id.clone(), - name: draft.name.clone(), - location_id, - capabilities: draft.capabilities.iter().cloned().collect(), - knowledge: draft.knowledge.iter().cloned().collect(), - equipment: draft.equipment.iter().cloned().collect(), - conditions: draft.vulnerabilities.iter().cloned().collect(), - obligations: draft.obligations.iter().cloned().collect(), - relationships: draft.relationships.clone(), - goals: draft.goals.clone(), - memories: draft - .private_history - .iter() - .chain(&draft.secrets) - .cloned() - .collect(), - } -} - -pub fn seed_digest(value: &T) -> Result { - digest(value) -} - -fn digest(value: &T) -> Result { - let bytes = rmp_serde::to_vec_named(value)?; - Ok(format!("sha256:{:x}", Sha256::digest(bytes))) -} - -fn secret_hash(value: &str) -> String { - format!("sha256:{:x}", Sha256::digest(value.as_bytes())) -} - -fn validate_bounded(label: &str, value: &str, min: usize, max: usize) -> Result<()> { - let count = value.chars().count(); - if count < min - || count > max - || value - .chars() - .any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t')) - { - return Err(anyhow!( - "{label} must contain {min} to {max} safe characters" - )); - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::model_connector::project_strict_responses_schema; - use async_trait::async_trait; - use tempfile::tempdir; - - struct SchemaAwareDirectorModel; - struct FocusedCounterDirectorModel; - struct FocusedPermissionModel; - struct CompositeFocusedCounterModel; - - const PERSONA_SPEECH: &str = "**Mars holds.** Your sung name remains ‘The last lamp carried between storms, learning each stranger by the weight they refuse to abandon.’ Does the revised contamination bargain fit Sable’s ability?"; - - fn model_decision_proposal(decision: &SessionZeroDecision) -> SessionZeroDecisionProposal { - SessionZeroDecisionProposal { - prompt: decision.prompt.clone(), - proposed_resolution: decision.proposed_resolution.clone(), - proposed_extraordinary_permission: decision - .proposed_extraordinary_permission - .as_ref() - .map(|permission| FocusedPermissionTerms { - name: permission.name.clone(), - reliable_scope: permission.reliable_scope.clone(), - prerequisites: permission.prerequisites.clone(), - costs: permission.costs.clone(), - limits: permission.limits.clone(), - opposition: permission.opposition.clone(), - exposure: permission.exposure.clone(), - effect_ceiling: permission.effect_ceiling.clone(), - branch_local: permission.branch_local, - }), - proposed_contract_patch: decision.proposed_contract_patch.clone(), - proposed_character_patch: decision.proposed_character_patch.clone(), - } - } - - #[async_trait] - impl ModelPort for SchemaAwareDirectorModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - match request.stage.as_str() { - "session_zero_projector" => { - let schema = request - .lived_stream - .find("OUTPUT JSON SCHEMA:") - .expect("projector must receive its exact output contract"); - let dynamic = request - .lived_stream - .find("DYNAMIC PERMITTED CONTEXT:") - .expect("projector must receive permitted state"); - assert!(schema < dynamic); - assert!(request.lived_stream.contains("Plan a Mars campaign.")); - Ok(r#"{"lived_stream":"The player wants a serious political campaign on Mars, but tone, character, and stakes remain open."}"#.into()) - } - "session_zero_dm_persona" => { - assert!( - request - .lived_stream - .contains("CURRENT PLAYER TURN, VERBATIM:\nPlan a Mars campaign.") - ); - Ok(PERSONA_SPEECH.into()) - } - "session_zero_interpreter" => { - let schema = request - .lived_stream - .find("OUTPUT JSON SCHEMA:") - .expect("interpreter must receive its exact output contract"); - let dynamic = request - .lived_stream - .find("DYNAMIC TYPED EXTRACTION CONTEXT:") - .expect("interpreter must receive bounded typed state"); - assert!(schema < dynamic); - assert!(!request.lived_stream.contains("\"dm_speech\"")); - assert!(!request.lived_stream.contains("\"recent_messages\"")); - assert!(request.lived_stream.contains("Plan a Mars campaign.")); - assert!( - request - .lived_stream - .contains("Choose exactly one ownership lane for each change") - ); - assert!( - request - .lived_stream - .contains("Never duplicate a proposed change into a direct patch") - ); - Ok(r#"{"contract_patch":{"starting_where":"Mars in Zhestokost space","tone":["serious","political"]},"decisions":[],"suggested_replies":[]}"#.into()) - } - stage => panic!("unexpected Session Zero model stage {stage}"), - } - } - - fn provider(&self) -> &'static str { - "fixture" - } - } - - #[async_trait] - impl ModelPort for FocusedCounterDirectorModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - match request.stage.as_str() { - "session_zero_projector" => { - panic!("focused counters use the exact deterministic projector") - } - "session_zero_dm_persona" => { - assert!(request.lived_stream.contains("Previous typed proposal")); - assert!( - request - .lived_stream - .contains("Player's exact counterproposal") - ); - assert!(!request.lived_stream.contains("\"schema\":")); - Ok("The exact replacement is ready for your review.".into()) - } - "session_zero_interpreter" => { - assert!(request.lived_stream.contains("private-character patch")); - assert!(!request.lived_stream.contains("SessionZeroDecision")); - assert!(!request.lived_stream.contains("owner_member_id")); - assert_eq!(request.max_output_tokens, Some(2000)); - Ok(serde_json::json!({ - "proposed_character_patch": CharacterDraftPatch { - name: Some("Sable, whose sung name remains whole".into()), - ..Default::default() - } - }) - .to_string()) - } - stage => panic!("unexpected focused Session Zero model stage {stage}"), - } - } - - fn provider(&self) -> &'static str { - "fixture" - } - } - - #[async_trait] - impl ModelPort for FocusedPermissionModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - assert_eq!(request.stage, "session_zero_interpreter"); - assert!( - request - .lived_stream - .contains("extraordinary-permission terms") - ); - assert!(!request.lived_stream.contains("permission:stable")); - assert!(!request.lived_stream.contains("actor:stable")); - Ok(serde_json::json!({ - "proposed_extraordinary_permission": FocusedPermissionTerms { - name: "Fork-memory synchronization".into(), - reliable_scope: "One willing nearby mind".into(), - prerequisites: vec!["Fresh consent".into()], - costs: vec!["Ordinary contamination fades with rest".into()], - limits: vec!["No unwilling reading".into()], - opposition: vec!["Active shielding".into()], - exposure: vec!["Traceable signature".into()], - effect_ceiling: "Bounded memory sharing".into(), - branch_local: false, - } - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "fixture" - } - } - - #[async_trait] - impl ModelPort for CompositeFocusedCounterModel { - async fn run(&self, request: &ModelStageRequest) -> Result { - assert_eq!(request.stage, "session_zero_interpreter"); - assert!( - request - .lived_stream - .contains("extraordinary-permission terms") - ); - assert!(request.lived_stream.contains("private-character patch")); - assert!(!request.lived_stream.contains("permission:stable")); - assert!(!request.lived_stream.contains("actor:stable")); - assert_eq!(request.max_output_tokens, Some(3400)); - Ok(serde_json::json!({ - "proposed_extraordinary_permission": FocusedPermissionTerms { - name: "Machine-listening".into(), - reliable_scope: "Actionable suspicion at close range".into(), - prerequisites: vec!["Physical proximity".into(), "Audible or tactile path".into()], - costs: vec!["Vocal strain".into()], - limits: vec!["No certain cause".into(), "No access bypass".into()], - opposition: vec!["Active damping".into(), "Hostile interruption".into()], - exposure: vec!["Audible at close range".into()], - effect_ceiling: "Narrowed diagnostic possibilities, never certainty".into(), - branch_local: true, - }, - "proposed_character_patch": CharacterDraftPatch { - equipment_add: vec!["Portable acoustic diagnostic pickup".into()], - obligations_add: vec!["Protect the mutual-aid route".into()], - ..Default::default() - } - }) - .to_string()) - } - - fn provider(&self) -> &'static str { - "fixture" - } - } - - fn state() -> SessionZeroState { - SessionZeroState::new( - "The Long Way Home".into(), - "aetheria".into(), - "account:host".into(), - "Host".into(), - ) - .unwrap() - } - - fn compilable_state() -> SessionZeroState { - let mut draft = state(); - draft.contract.premise = "Keep a refugee clinic supplied during a political crisis.".into(); - draft.contract.canon_horizon = "After Burden of Proof".into(); - draft.contract.starting_where = "Hellas, Mars".into(); - draft.contract.starting_when = "During a Zhestokost ration strike".into(); - draft.contract.starting_pressure = "A ration strike and refugee convoy".into(); - draft.contract.desired_goal = "Protect the clinic without becoming an informant.".into(); - draft.contract.tone = vec!["serious political drama".into()]; - draft.contract.pacing = "deliberate pressure with sharp turns".into(); - draft.contract.consequence_style = "durable, low arbitrary lethality".into(); - draft.contract.narrative_focus = "institutional leverage and human solidarity".into(); - draft.contract.dm_style = "candid, challenging, and humane".into(); - let character = draft - .character_drafts - .get_mut(&draft.host_member_id) - .unwrap(); - character.public_premise = - "A Corvid logistics mediator caught between institutions.".into(); - character.capabilities = vec!["Route planning".into()]; - character.goals = vec!["Get the convoy through".into()]; - character.obligations = vec!["A life-debt to the quartermaster".into()]; - draft - } - - #[tokio::test] - async fn host_can_archive_a_locked_unpublished_session_zero() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let mut initial = state(); - initial.roster_locked = true; - let initial_revision = initial.revision; - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store, initial.id); - - let archived = kernel - .command(SessionZeroCommand::Archive { - actor_account_hash: "account:host".into(), - expected_revision: initial_revision, - }) - .await - .unwrap(); - - assert_eq!(archived.state.status, SessionZeroStatus::Archived); - assert_eq!(archived.state.revision, initial_revision + 1); - } - - #[test] - fn host_surface_exposes_the_revision_bound_archive_command() { - let draft = state(); - let surface = session_zero_surface(&draft, "account:host").unwrap(); - let encoded = serde_json::to_string(&surface).unwrap(); - - assert!(encoded.contains("session_zero.archive")); - assert!(encoded.contains("Archive Session Zero")); - assert!(encoded.contains("expected_revision")); - } - - fn model_receipt(stage: &str, receipt_hash: &str, latency_ms: u64) -> ModelStageReceipt { - ModelStageReceipt { - schema: "ghostlight.persona_stage_receipt.v1".into(), - receipt_hash: receipt_hash.into(), - provider: "fixture".into(), - model: "fixture-model".into(), - stage: stage.into(), - snapshot_binding: "fixture-snapshot".into(), - request_hash: format!("request:{stage}"), - output_hash: format!("output:{stage}"), - source_receipt_ids: vec![], - latency_ms, - validation_result: "valid".into(), - local_validation_error: None, - input_chars: 100, - output_chars: 20, - provider_attempts: vec![], - } - } - - #[tokio::test] - async fn session_zero_keeps_inference_history_separate_from_active_preview_proof() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let mut initial = compilable_state(); - initial.roster_locked = true; - initial.status = SessionZeroStatus::Compiling; - let repeated_a = model_receipt("session_zero_dm_persona", "receipt:repeated", 10); - let repeated_b = model_receipt("session_zero_dm_persona", "receipt:repeated", 20); - initial.model_receipts = vec![repeated_a.clone(), repeated_b.clone()]; - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store, initial.id); - let current = model_receipt("custom_retrieval_plan", "receipt:current", 30); - let installed = kernel - .command(SessionZeroCommand::InstallPreview { - expected_revision: initial.revision, - preview: WorldCompilePreview { - schema: "ghostlight.world_compile_preview.v1".into(), - title: "Current preview".into(), - campaign: crate::resolution::tests::campaign(2, 1), - evidence_receipts: vec![], - evidence_coverage: vec![], - gaps: vec![], - branch_assumptions: vec![], - requires_approval: true, - }, - model_receipts: vec![current.clone()], - }) - .await - .unwrap(); - - assert_eq!( - installed.state.model_receipts, - [repeated_a, repeated_b, current.clone()] - ); - assert_eq!(installed.state.preview_model_receipts, [current]); - - let compiling = kernel - .command(SessionZeroCommand::BeginCompilation { - actor_account_hash: "account:host".into(), - expected_revision: installed.state.revision, - }) - .await - .unwrap(); - assert!(compiling.state.preview_model_receipts.is_empty()); - assert_eq!(compiling.state.model_receipts.len(), 3); - } - - #[tokio::test] - async fn unavailable_vault_becomes_one_stable_material_blocker() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let mut initial = compilable_state(); - initial.roster_locked = true; - initial.status = SessionZeroStatus::Compiling; - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store, initial.id); - - let failed = kernel - .command(SessionZeroCommand::CompilationEvidenceUnavailable { - expected_revision: initial.revision, - }) - .await - .unwrap(); - let decision = failed - .state - .decisions - .get("decision:vault-retrieval-required") - .unwrap(); - assert_eq!(failed.state.status, SessionZeroStatus::Drafting); - assert!(failed.state.preview.is_none()); - assert!(decision.material); - assert!(decision.resolved); - assert!(decision.proposed_contract_patch.is_none()); - assert!(decision.proposed_character_patch.is_none()); - assert!(decision.proposed_extraordinary_permission.is_none()); - let public_messages = failed - .state - .messages - .values() - .map(|message| message.text.as_str()) - .collect::>() - .join("\n"); - assert!( - public_messages.contains("cannot distinguish missing canon from missing retrieval") - ); - assert!(!public_messages.contains("Ollama")); - - let compiling = kernel - .command(SessionZeroCommand::BeginCompilation { - actor_account_hash: "account:host".into(), - expected_revision: failed.state.revision, - }) - .await - .unwrap(); - let failed_again = kernel - .command(SessionZeroCommand::CompilationEvidenceUnavailable { - expected_revision: compiling.state.revision, - }) - .await - .unwrap(); - assert_eq!( - failed_again - .state - .decisions - .keys() - .filter(|id| id.as_str() == "decision:vault-retrieval-required") - .count(), - 1 - ); - assert!(failed_again.state.decisions["decision:vault-retrieval-required"].resolved); - } - - #[test] - fn legacy_receipt_layout_migrates_without_changing_session_revision() { - let mut draft = compilable_state(); - draft.status = SessionZeroStatus::Review; - draft.preview = Some(WorldCompilePreview { - schema: "ghostlight.world_compile_preview.v1".into(), - title: "Current preview".into(), - campaign: crate::resolution::tests::campaign(2, 1), - evidence_receipts: vec![], - evidence_coverage: vec![], - gaps: vec![], - branch_assumptions: vec![], - requires_approval: true, - }); - let old = model_receipt("custom_retrieval_plan", "receipt:old-plan", 10); - let old_world = model_receipt("world_compile", "receipt:old-world", 20); - let current = model_receipt("custom_retrieval_plan", "receipt:current-plan", 30); - let current_world = model_receipt("world_compile", "receipt:current-world", 40); - let current_agency = model_receipt("agency_compile", "receipt:current-agency", 50); - let trailing_dm = model_receipt("session_zero_dm_persona", "receipt:later-dm", 60); - let legacy = vec![ - old, - old_world, - current.clone(), - current_world.clone(), - current_agency.clone(), - trailing_dm, - ]; - draft.preview_model_receipts.clone_from(&legacy); - let revision = draft.revision; - let status = draft.status.clone(); - - assert!(migrate_legacy_model_receipts(&mut draft)); - assert_eq!(draft.model_receipts, legacy); - assert_eq!( - draft.preview_model_receipts, - [current, current_world, current_agency] - ); - assert_eq!(draft.revision, revision); - assert_eq!(draft.status, status); - assert!(!migrate_legacy_model_receipts(&mut draft)); - } - - #[tokio::test] - async fn director_receives_stable_output_contracts_before_dynamic_context() { - let director = SessionZeroDirector::new( - Arc::new(SchemaAwareDirectorModel), - "projector", - "persona", - "interpreter", - ); - let mut draft = state(); - let host_id = draft.host_member_id.clone(); - append_message( - &mut draft, - "shared:table".into(), - Some(host_id), - SessionZeroSpeakerKind::Player, - "Plan a Mars campaign.".into(), - ) - .unwrap(); - let (delta, receipts) = director - .respond(&draft, "shared:table", None, None) - .await - .unwrap(); - assert_eq!( - delta.contract_patch.starting_where.as_deref(), - Some("Mars in Zhestokost space") - ); - assert_eq!(delta.contract_patch.tone.unwrap(), ["serious", "political"]); - assert_eq!(delta.dm_speech, PERSONA_SPEECH); - assert_eq!(receipts.len(), 3); - } - - #[tokio::test] - async fn focused_counter_uses_exact_local_projection_before_persona_and_interpreter() { - let mut draft = state(); - let host_id = draft.host_member_id.clone(); - let target_id = "decision:focused-character".to_owned(); - draft.decisions.insert( - target_id.clone(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: target_id.clone(), - owner_member_id: Some(host_id.clone()), - prompt: "Accept Sable's draft?".into(), - proposed_resolution: "Use the proposed character patch.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: None, - proposed_character_patch: Some(CharacterDraftPatch { - name: Some("Sable".into()), - ..Default::default() - }), - evidence_receipt_ids: vec![], - pending_counter: Some("Keep Sable's full sung name.".into()), - material: true, - resolved: false, - }, - ); - let director = SessionZeroDirector::new( - Arc::new(FocusedCounterDirectorModel), - "projector", - "persona", - "interpreter", - ); - let private_channel = format!("private:{host_id}"); - let (delta, receipts) = director - .respond(&draft, &private_channel, Some(&host_id), Some(&target_id)) - .await - .unwrap(); - assert_eq!(receipts.len(), 2); - assert_eq!( - delta.decisions[0].owner_member_id.as_deref(), - Some(host_id.as_str()) - ); - assert!(delta.decisions[0].material); - assert_eq!( - delta.decisions[0] - .proposed_character_patch - .as_ref() - .and_then(|patch| patch.name.as_deref()), - Some("Sable, whose sung name remains whole") - ); - } - - #[tokio::test] - async fn focused_permission_interpreter_cannot_rewrite_identity_owner_or_evidence() { - let permission = ExtraordinaryPermission { - schema: "ghostlight.extraordinary_permission.v1".into(), - id: "permission:stable".into(), - actor_id: "actor:stable".into(), - name: "Fork-memory synchronization".into(), - reliable_scope: "One willing nearby mind".into(), - prerequisites: vec!["Fresh consent".into()], - costs: vec!["Borrowed memories do not fully leave".into()], - limits: vec!["No unwilling reading".into()], - opposition: vec!["Active shielding".into()], - exposure: vec!["Traceable signature".into()], - effect_ceiling: "Bounded memory sharing".into(), - evidence_receipt_ids: vec!["receipt:stable".into()], - branch_local: false, - }; - let decision = SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:old".into(), - owner_member_id: Some("member:stable".into()), - prompt: "Accept the permission?".into(), - proposed_resolution: "Old terms".into(), - proposed_extraordinary_permission: Some(permission.clone()), - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec!["decision-receipt:stable".into()], - pending_counter: Some("Ordinary contamination fades with rest.".into()), - material: true, - resolved: false, - }; - let (interpretation, _) = run_focused_counter_interpreter( - &FocusedPermissionModel, - "fixture", - "binding", - &decision, - "Exact factual basis without persistence identifiers.", - "Please review the replacement.", - ) - .await - .unwrap(); - let replacement = &interpretation.decisions[0]; - let replaced_permission = replacement - .proposed_extraordinary_permission - .as_ref() - .unwrap(); - assert_eq!(replacement.owner_member_id, decision.owner_member_id); - assert_eq!(replacement.material, decision.material); - assert_eq!( - replacement.evidence_receipt_ids, - decision.evidence_receipt_ids - ); - assert_eq!(replaced_permission.id, permission.id); - assert_eq!(replaced_permission.actor_id, permission.actor_id); - assert_eq!( - replaced_permission.evidence_receipt_ids, - permission.evidence_receipt_ids - ); - assert_eq!( - replaced_permission.costs, - ["Ordinary contamination fades with rest"] - ); - } - - #[tokio::test] - async fn focused_composite_counter_preserves_every_lane_and_permission_identity() { - let permission = ExtraordinaryPermission { - schema: "ghostlight.extraordinary_permission.v1".into(), - id: "permission:stable".into(), - actor_id: "actor:stable".into(), - name: "Machine-listening".into(), - reliable_scope: "Nearby machine rhythm".into(), - prerequisites: vec!["Close range".into()], - costs: vec!["Fatigue".into()], - limits: vec!["No certainty".into()], - opposition: vec![], - exposure: vec!["Audible use".into()], - effect_ceiling: "A diagnostic lead".into(), - evidence_receipt_ids: vec!["receipt:stable".into()], - branch_local: true, - }; - let decision = SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:composite".into(), - owner_member_id: Some("member:stable".into()), - prompt: "Review the character and permission?".into(), - proposed_resolution: "Old composite terms".into(), - proposed_extraordinary_permission: Some(permission.clone()), - proposed_contract_patch: None, - proposed_character_patch: Some(CharacterDraftPatch { - equipment_add: vec!["Vague audit tools".into()], - ..Default::default() - }), - evidence_receipt_ids: vec!["decision-receipt:stable".into()], - pending_counter: Some("Restore the exact equipment and opposition.".into()), - material: true, - resolved: false, - }; - let (interpretation, _) = run_focused_counter_interpreter( - &CompositeFocusedCounterModel, - "fixture", - "binding", - &decision, - "Exact factual basis without persistence identifiers.", - "Please review the replacement.", - ) - .await - .unwrap(); - let replacement = &interpretation.decisions[0]; - assert_eq!( - decision_payload_lanes(replacement), - decision_payload_lanes(&decision) - ); - assert_eq!(replacement.owner_member_id, decision.owner_member_id); - assert_eq!(replacement.material, decision.material); - assert_eq!( - replacement.evidence_receipt_ids, - decision.evidence_receipt_ids - ); - let replaced_permission = replacement - .proposed_extraordinary_permission - .as_ref() - .unwrap(); - assert_eq!(replaced_permission.id, permission.id); - assert_eq!(replaced_permission.actor_id, permission.actor_id); - assert_eq!( - replaced_permission.evidence_receipt_ids, - permission.evidence_receipt_ids - ); - assert_eq!( - replaced_permission.opposition, - ["Active damping", "Hostile interruption"] - ); - let patch = replacement.proposed_character_patch.as_ref().unwrap(); - assert_eq!(patch.equipment_add, ["Portable acoustic diagnostic pickup"]); - assert_eq!(patch.obligations_add, ["Protect the mutual-aid route"]); - } - - #[test] - fn legacy_extraordinary_permission_defaults_missing_opposition() { - let permission: ExtraordinaryPermission = serde_json::from_value(serde_json::json!({ - "schema":"ghostlight.extraordinary_permission.v1", - "id":"permission:legacy", - "actor_id":"actor:legacy", - "name":"Legacy gift", - "reliable_scope":"One bounded effect", - "prerequisites":[], - "costs":[], - "limits":[], - "exposure":[], - "effect_ceiling":"One bounded effect", - "evidence_receipt_ids":[], - "branch_local":true - })) - .unwrap(); - assert!(permission.opposition.is_empty()); - } - - #[test] - fn focused_counter_schema_excludes_the_full_decision_union() { - let decision = SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:focused".into(), - owner_member_id: Some("member:focused".into()), - prompt: "Review the character?".into(), - proposed_resolution: "Replace the character patch.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: None, - proposed_character_patch: Some(CharacterDraftPatch { - name: Some("Sable".into()), - ..Default::default() - }), - evidence_receipt_ids: vec![], - pending_counter: Some("Keep the sung name whole.".into()), - material: true, - resolved: false, - }; - let (_, focused, _) = focused_counter_schema(&decision).unwrap(); - let focused = serde_json::to_string(&focused).unwrap(); - let mut full = serde_json::to_value(schema_for!(SessionZeroModelInterpretation)).unwrap(); - require_typed_decision_payloads(&mut full).unwrap(); - let full = serde_json::to_string(&full).unwrap(); - assert!(!focused.contains("SessionZeroDecision")); - assert!(!focused.contains("ExtraordinaryPermission")); - assert!(!focused.contains("CampaignContractPatch")); - assert!( - focused.len() * 2 < full.len(), - "focused schema={} bytes full union={} bytes", - focused.len(), - full.len() - ); - } - - #[test] - fn interpreter_schema_exposes_only_the_current_channel_authority() { - let shared = session_zero_interpreter_schema(&SessionZeroChannelKind::SharedTable).unwrap(); - let shared_root = shared["properties"].as_object().unwrap(); - assert!(shared_root.contains_key("contract_patch")); - assert!(!shared_root.contains_key("character_patch")); - let shared_decision = shared - .pointer("/properties/decisions/items/properties") - .and_then(serde_json::Value::as_object) - .unwrap(); - assert!(shared_decision.contains_key("proposed_contract_patch")); - assert!(!shared_decision.contains_key("proposed_character_patch")); - assert!(!shared_decision.contains_key("proposed_extraordinary_permission")); - assert_eq!(shared_decision["proposed_contract_patch"]["type"], "object"); - assert!( - shared - .pointer("/properties/decisions/items/anyOf") - .is_none() - ); - assert!(shared.get("$defs").is_none()); - - let private = session_zero_interpreter_schema(&SessionZeroChannelKind::PrivateDm).unwrap(); - let private_root = private["properties"].as_object().unwrap(); - assert!(!private_root.contains_key("contract_patch")); - assert!(private_root.contains_key("character_patch")); - let private_decision = private - .pointer("/properties/decisions/items/properties") - .and_then(serde_json::Value::as_object) - .unwrap(); - assert!(!private_decision.contains_key("proposed_contract_patch")); - assert!(private_decision.contains_key("proposed_character_patch")); - assert!(private_decision.contains_key("proposed_extraordinary_permission")); - assert!(private.get("$defs").is_none()); - - for mut provider_schema in [shared, private] { - crate::model_connector::project_strict_responses_schema(&mut provider_schema).unwrap(); - jsonschema::validator_for(&provider_schema).unwrap(); - } - } - - #[test] - fn private_interpretation_defaults_the_absent_shared_lane() { - let interpreted: SessionZeroModelInterpretation = - serde_json::from_value(serde_json::json!({ - "character_patch": null, - "decisions": [], - "suggested_replies": [] - })) - .unwrap(); - assert_eq!(interpreted.contract_patch, CampaignContractPatch::default()); - } - - #[test] - fn interpreter_schema_rejects_decisions_without_typed_payloads() { - let mut schema = serde_json::to_value(schema_for!(SessionZeroModelInterpretation)).unwrap(); - require_typed_decision_payloads(&mut schema).unwrap(); - let validator = jsonschema::validator_for(&schema).unwrap(); - let decision = SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:empty-promise".into(), - owner_member_id: None, - prompt: "Materialize the character?".into(), - proposed_resolution: "Materialize the character exactly as discussed.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }; - let invalid = SessionZeroModelInterpretation { - decisions: vec![model_decision_proposal(&decision)], - ..Default::default() - }; - assert!(!validator.is_valid(&serde_json::to_value(invalid).unwrap())); - - let mut actionable = decision; - actionable.proposed_character_patch = Some(CharacterDraftPatch { - name: Some("Sable".into()), - ..Default::default() - }); - let valid = SessionZeroModelInterpretation { - decisions: vec![model_decision_proposal(&actionable)], - ..Default::default() - }; - assert!(validator.is_valid(&serde_json::to_value(valid).unwrap())); - } - - #[test] - fn ghostlight_owns_interpreted_decision_and_permission_identity() { - let state = state(); - let member_id = state.host_member_id.clone(); - let schema = serde_json::to_value(schema_for!(SessionZeroModelInterpretation)).unwrap(); - let decision_properties = schema["$defs"]["SessionZeroDecisionProposal"]["properties"] - .as_object() - .unwrap(); - for forbidden in [ - "id", - "owner_member_id", - "pending_counter", - "material", - "resolved", - ] { - assert!(!decision_properties.contains_key(forbidden)); - } - let permission_properties = schema["$defs"]["FocusedPermissionTerms"]["properties"] - .as_object() - .unwrap(); - for forbidden in ["id", "actor_id", "evidence_receipt_ids"] { - assert!(!permission_properties.contains_key(forbidden)); - } - let proposed = SessionZeroModelInterpretation { - decisions: vec![SessionZeroDecisionProposal { - prompt: "Accept bounded pressure sensing?".into(), - proposed_resolution: "Touch reveals recent local stress only.".into(), - proposed_extraordinary_permission: Some(FocusedPermissionTerms { - name: "Pressure Echo".into(), - reliable_scope: "One touched pressure-bearing machine".into(), - prerequisites: vec!["Direct touch".into()], - costs: vec!["Vertigo".into()], - limits: vec!["No causes or remote history".into()], - opposition: vec!["Active damping".into()], - exposure: vec!["A breathing-rhythm trace".into()], - effect_ceiling: "Recent local stress map".into(), - branch_local: true, - }), - proposed_contract_patch: None, - proposed_character_patch: None, - }], - ..Default::default() - }; - - let admitted = - admit_model_interpretation(&state, Some(&member_id), proposed.clone()).unwrap(); - let decision = &admitted.decisions[0]; - assert!(decision.id.starts_with("decision:")); - assert_eq!( - decision.owner_member_id.as_deref(), - Some(member_id.as_str()) - ); - assert!(decision.material); - assert!(!decision.resolved); - assert!(decision.evidence_receipt_ids.is_empty()); - let permission = decision.proposed_extraordinary_permission.as_ref().unwrap(); - assert!(permission.id.starts_with("permission:")); - assert_eq!( - permission.actor_id, - state.character_drafts[&member_id].actor_id - ); - assert!(permission.evidence_receipt_ids.is_empty()); - - assert!(admit_model_interpretation(&state, None, proposed).is_err()); - } - - #[test] - fn ui_suggestions_never_enter_dm_or_interpreter_cognition() { - let mut draft = state(); - let host_id = draft.host_member_id.clone(); - append_message( - &mut draft, - "shared:table".into(), - Some(host_id), - SessionZeroSpeakerKind::Player, - "Use the negotiated post-Burden frame, not the generated openings.".into(), - ) - .unwrap(); - draft.decisions.insert( - "opening:unselected".into(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "opening:unselected".into(), - owner_member_id: None, - prompt: "Use an unselected opening?".into(), - proposed_resolution: "Age-of-Automation suggestion must remain UI-only.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: Some(CampaignContractPatch { - starting_when: Some("Age of Automation (2160-2163)".into()), - ..Default::default() - }), - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: false, - resolved: false, - }, - ); - draft.decisions.insert( - "decision:material".into(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:material".into(), - owner_member_id: None, - prompt: "Adopt the negotiated post-Burden horizon?".into(), - proposed_resolution: "Begin after Burden of Proof.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: Some(CampaignContractPatch { - canon_horizon: Some("After Burden of Proof".into()), - ..Default::default() - }), - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }, - ); - - let dm = permitted_dm_context(&draft, "shared:table", None, None).unwrap(); - let interpreter = - permitted_interpreter_context(&draft, "shared:table", None, None).unwrap(); - for context in [dm, interpreter] { - let rendered = serde_json::to_string(&context).unwrap(); - assert!(!rendered.contains("Age of Automation")); - assert!(!rendered.contains("opening:unselected")); - assert!(rendered.contains("decision:material")); - assert!(rendered.contains("After Burden of Proof")); - } - } - - #[test] - fn dm_turn_cannot_split_one_lane_between_direct_and_decision_ownership() { - let draft = state(); - let duplicate_contract = SessionZeroDelta { - contract_patch: CampaignContractPatch { - canon_horizon: Some("After Burden of Proof".into()), - ..Default::default() - }, - decisions: vec![SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:duplicate-contract".into(), - owner_member_id: None, - prompt: "Adopt the horizon?".into(), - proposed_resolution: "Begin after Burden of Proof.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: Some(CampaignContractPatch { - canon_horizon: Some("After Burden of Proof".into()), - ..Default::default() - }), - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }], - ..Default::default() - }; - - let mut schema = serde_json::to_value(schema_for!(SessionZeroModelInterpretation)).unwrap(); - require_typed_decision_payloads(&mut schema).unwrap(); - require_single_lane_ownership(&mut schema).unwrap(); - let validator = jsonschema::validator_for(&schema).unwrap(); - let split_interpretation = SessionZeroModelInterpretation { - contract_patch: duplicate_contract.contract_patch.clone(), - decisions: duplicate_contract - .decisions - .iter() - .map(model_decision_proposal) - .collect(), - ..Default::default() - }; - assert!(!validator.is_valid(&serde_json::to_value(&split_interpretation).unwrap())); - assert!( - validator.is_valid( - &serde_json::to_value(SessionZeroModelInterpretation { - contract_patch: duplicate_contract.contract_patch.clone(), - ..Default::default() - }) - .unwrap() - ) - ); - assert!( - validator.is_valid( - &serde_json::to_value(SessionZeroModelInterpretation { - decisions: duplicate_contract - .decisions - .iter() - .map(model_decision_proposal) - .collect(), - ..Default::default() - }) - .unwrap() - ) - ); - - let error = validate_dm_delta(&draft, "shared:table", None, &duplicate_contract) - .unwrap_err() - .to_string(); - assert!(error.contains("directly edit the contract")); - - let host_id = draft.host_member_id.clone(); - let actor_id = draft.character_drafts[&host_id].actor_id.clone(); - let character_and_permission = SessionZeroDelta { - character_patch: Some(CharacterDraftPatch { - public_premise: Some("A refugee logistics organizer.".into()), - ..Default::default() - }), - decisions: vec![SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:permission".into(), - owner_member_id: Some(host_id.clone()), - prompt: "Accept bounded pressure-stress sensing?".into(), - proposed_resolution: "Touch reveals only recent local stress.".into(), - proposed_extraordinary_permission: Some(ExtraordinaryPermission { - schema: "ghostlight.extraordinary_permission.v1".into(), - id: "permission:stress-sense".into(), - actor_id, - name: "Pressure-stress sensing".into(), - reliable_scope: "One touched pressure-bearing machine".into(), - prerequisites: vec!["Direct touch".into()], - costs: vec!["Vertigo".into()], - limits: vec!["No causes or remote history".into()], - opposition: vec!["Active damping".into()], - exposure: vec!["Traceable breathing rhythm".into()], - effect_ceiling: "Recent local thermal and pressure stress map".into(), - evidence_receipt_ids: vec![], - branch_local: true, - }), - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }], - ..Default::default() - }; - assert!( - validator.is_valid( - &serde_json::to_value(SessionZeroModelInterpretation { - character_patch: character_and_permission.character_patch.clone(), - decisions: character_and_permission - .decisions - .iter() - .map(model_decision_proposal) - .collect(), - ..Default::default() - }) - .unwrap() - ) - ); - validate_dm_delta( - &draft, - &format!("private:{host_id}"), - Some(&host_id), - &character_and_permission, - ) - .unwrap(); - } - - #[test] - fn character_patch_can_correct_accepted_identity_without_duplicate_subjects() { - let mut character = CharacterDraft { - relationships: BTreeMap::from([( - "Reed".into(), - "Ash promised not to let Reed disappear into a manifest.".into(), - )]), - capabilities: vec![ - "manifest reconciliation".into(), - "mistaken capability".into(), - ], - ..Default::default() - }; - let full_name = - "Reed — full sung name: Rain gathering every lost footstep beneath one patient wing"; - let patch = CharacterDraftPatch { - relationship_removals: vec!["Reed".into()], - relationships: BTreeMap::from([( - full_name.into(), - "Ash promised not to let Reed disappear into a destination manifest.".into(), - )]), - capabilities_remove: vec!["mistaken capability".into()], - ..Default::default() - }; - let visible = display_character_patch(&patch); - assert!(visible.contains("Relationship keys to remove: Reed")); - assert!(visible.contains("Capabilities to remove: mistaken capability")); - - apply_character_patch(&mut character, patch); - - assert_eq!(character.relationships.len(), 1); - assert!(!character.relationships.contains_key("Reed")); - assert!(character.relationships.contains_key(full_name)); - assert_eq!(character.capabilities, ["manifest reconciliation"]); - } - - #[test] - fn character_patch_loads_pre_removal_messagepack_rows() { - let legacy = serde_json::json!({ - "name": "Ash", - "public_premise": null, - "private_history_add": ["kept the convoy ledger"], - "secrets_add": [], - "capabilities_add": ["manifest reconciliation"], - "knowledge_add": [], - "equipment_add": [], - "relationships": {"Reed": "Ash owes Reed their life."}, - "obligations_add": [], - "vulnerabilities_add": [], - "goals_add": [] - }); - let bytes = rmp_serde::to_vec_named(&legacy).unwrap(); - - let patch: CharacterDraftPatch = rmp_serde::from_slice(&bytes).unwrap(); - - assert_eq!(patch.name.as_deref(), Some("Ash")); - assert_eq!(patch.capabilities_add, ["manifest reconciliation"]); - assert_eq!( - patch.relationships.get("Reed").map(String::as_str), - Some("Ash owes Reed their life.") - ); - assert!(patch.private_history_remove.is_empty()); - assert!(patch.secrets_remove.is_empty()); - assert!(patch.capabilities_remove.is_empty()); - assert!(patch.knowledge_remove.is_empty()); - assert!(patch.equipment_remove.is_empty()); - assert!(patch.relationship_removals.is_empty()); - assert!(patch.obligations_remove.is_empty()); - assert!(patch.vulnerabilities_remove.is_empty()); - assert!(patch.goals_remove.is_empty()); - } - - #[test] - fn character_relationship_patch_uses_strict_entry_array_and_reads_legacy_maps() { - let patch = CharacterDraftPatch { - relationships: BTreeMap::from([( - "Sera Dain".into(), - "Eda's former co-scribe and once-close friend.".into(), - )]), - ..Default::default() - }; - - let encoded = serde_json::to_value(&patch).unwrap(); - assert_eq!( - encoded["relationships"], - serde_json::json!([{ - "subject": "Sera Dain", - "relationship": "Eda's former co-scribe and once-close friend." - }]) - ); - let decoded: CharacterDraftPatch = serde_json::from_value(encoded).unwrap(); - assert_eq!(decoded.relationships, patch.relationships); - - let mut schema = inline_provider_schema_for::().unwrap(); - project_strict_responses_schema(&mut schema).unwrap(); - assert_eq!(schema["properties"]["relationships"]["type"], "array"); - assert_eq!( - schema["properties"]["relationships"]["items"]["additionalProperties"], - false - ); - assert_eq!( - schema["properties"]["relationships"]["items"]["required"], - serde_json::json!(["relationship", "subject"]) - ); - } - - #[test] - fn character_relationship_patch_composes_duplicate_subject_clauses_for_review() { - let duplicate = serde_json::json!({ - "name": null, - "public_premise": null, - "private_history_add": [], - "private_history_remove": [], - "secrets_add": [], - "secrets_remove": [], - "capabilities_add": [], - "capabilities_remove": [], - "knowledge_add": [], - "knowledge_remove": [], - "equipment_add": [], - "equipment_remove": [], - "relationships": [ - {"subject":"Sera Dain","relationship":"friend"}, - {"subject":"Sera Dain","relationship":"clerk"} - ], - "relationship_removals": [], - "obligations_add": [], - "obligations_remove": [], - "vulnerabilities_add": [], - "vulnerabilities_remove": [], - "goals_add": [], - "goals_remove": [] - }); - - let patch = serde_json::from_value::(duplicate).unwrap(); - assert_eq!( - patch.relationships.get("Sera Dain").map(String::as_str), - Some("friend; clerk") - ); - } - - #[test] - fn private_dm_context_carries_bounded_public_session_continuity() { - let mut draft = state(); - let host_id = draft.host_member_id.clone(); - append_message( - &mut draft, - "shared:table".into(), - Some(host_id.clone()), - SessionZeroSpeakerKind::Player, - "The campaign begins in Hellas inside Zhestokost space.".into(), - ) - .unwrap(); - let private_channel = format!("private:{host_id}"); - append_message( - &mut draft, - private_channel.clone(), - Some(host_id.clone()), - SessionZeroSpeakerKind::Player, - "I carry a forged transit credential.".into(), - ) - .unwrap(); - - let context = permitted_dm_context(&draft, &private_channel, Some(&host_id), None).unwrap(); - assert!( - context["compiler_authority"]["compatible_branch_elaboration"] - .as_str() - .unwrap() - .contains("setting mechanics") - ); - assert!( - context["compiler_authority"]["material_gaps"] - .as_str() - .unwrap() - .contains("contradictory canon baselines") - ); - let shared = serde_json::to_string(&context["recent_shared_messages"]).unwrap(); - assert!(shared.contains("Hellas inside Zhestokost space")); - assert!(!shared.contains("forged transit credential")); - assert!( - serde_json::to_string(&context["current_player_message"]) - .unwrap() - .contains("forged transit credential") - ); - assert!( - !serde_json::to_string(&context["recent_messages"]) - .unwrap() - .contains("forged transit credential") - ); - let interpreter = - permitted_interpreter_context(&draft, &private_channel, Some(&host_id), None).unwrap(); - assert!( - serde_json::to_string(&interpreter["current_player_message"]) - .unwrap() - .contains("forged transit credential") - ); - assert!(interpreter.get("current_contract").is_none()); - } - - #[test] - fn ordinary_dm_context_keeps_one_exact_current_turn_and_six_prior_channel_turns() { - let mut draft = state(); - let host_id = draft.host_member_id.clone(); - let private_channel = format!("private:{host_id}"); - for index in 0..10 { - append_message( - &mut draft, - private_channel.clone(), - Some(host_id.clone()), - SessionZeroSpeakerKind::Player, - format!("private-turn-{index}"), - ) - .unwrap(); - } - - let context = permitted_dm_context(&draft, &private_channel, Some(&host_id), None).unwrap(); - assert_eq!(context["current_player_message"]["text"], "private-turn-9"); - let history = context["recent_messages"].as_array().unwrap(); - assert_eq!(history.len(), 6); - assert_eq!(history[0]["text"], "private-turn-3"); - assert_eq!(history[5]["text"], "private-turn-8"); - } - - #[test] - fn counter_replacement_focus_projects_only_the_exact_pending_decision() { - let mut draft = state(); - let host_id = draft.host_member_id.clone(); - let target_id = "decision:target".to_string(); - let decision = - |id: String, prompt: &str, pending_counter: Option| SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id, - owner_member_id: Some(host_id.clone()), - prompt: prompt.into(), - proposed_resolution: "A retired proposal".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter, - material: true, - resolved: false, - }; - let mut target = decision( - target_id.clone(), - "Replace the memory cost?", - Some("Ordinary contamination fades with rest.".into()), - ); - target.proposed_extraordinary_permission = Some(ExtraordinaryPermission { - schema: "ghostlight.extraordinary_permission.v1".into(), - id: "permission:fork-memory".into(), - actor_id: draft.character_drafts[&host_id].actor_id.clone(), - name: "Fork-memory synchronization".into(), - reliable_scope: "One willing nearby mind".into(), - prerequisites: vec!["Fresh consent".into()], - costs: vec!["Borrowed memories do not fully leave".into()], - limits: vec!["No unwilling reading".into()], - opposition: vec!["Active shielding".into()], - exposure: vec!["Traceable synchronization signature".into()], - effect_ceiling: "Bounded memory and procedural-skill sharing".into(), - evidence_receipt_ids: vec![], - branch_local: false, - }); - draft.decisions.insert(target_id.clone(), target); - draft.decisions.insert( - "decision:unrelated".into(), - decision( - "decision:unrelated".into(), - "UNRELATED-DECISION-MARKER", - None, - ), - ); - let character = draft.character_drafts.get_mut(&host_id).unwrap(); - character - .knowledge - .push("Oren serves the superseded pass office".into()); - character.relationships.insert( - "Oren".into(), - "Oren now serves the mountain settlement customs office".into(), - ); - let private_channel = format!("private:{host_id}"); - - let projected = - permitted_dm_context(&draft, &private_channel, Some(&host_id), Some(&target_id)) - .unwrap(); - let extraction = permitted_interpreter_context( - &draft, - &private_channel, - Some(&host_id), - Some(&target_id), - ) - .unwrap(); - for context in [&projected, &extraction] { - let encoded = serde_json::to_string(context).unwrap(); - assert!(encoded.contains("Ordinary contamination fades with rest")); - assert!(encoded.contains("counter_replacement")); - assert!(encoded.contains("exactly one fresh unresolved decision")); - assert!(!encoded.contains("UNRELATED-DECISION-MARKER")); - assert!( - encoded.len() < 6_000, - "focused context was {} bytes", - encoded.len() - ); - assert!(context.get("recent_messages").is_none()); - assert!(context.get("recent_shared_messages").is_none()); - assert!(context.get("private_character").is_none()); - assert!(context.get("current_private_character").is_none()); - assert_eq!(context["countered_decision"]["id"], target_id); - } - let lived = - project_focused_counter_lived_stream(&draft, Some(&host_id), &target_id).unwrap(); - assert!(lived.contains("Previous typed proposal, rendered exactly")); - assert!(lived.contains("Borrowed memories do not fully leave")); - assert!(lived.contains("Player's exact counterproposal")); - assert!(lived.contains("Ordinary contamination fades with rest")); - assert!(lived.contains("Authoritative owner state before this replacement")); - assert!(lived.contains("Oren serves the superseded pass office")); - assert!(lived.contains("Oren now serves the mountain settlement customs office")); - assert!(!lived.contains("UNRELATED-DECISION-MARKER")); - assert!(!lived.contains("ghostlight.session_zero_decision")); - assert!(!lived.contains(&target_id)); - - let mut legacy = draft.clone(); - let accepted_permission = legacy.decisions[&target_id] - .proposed_extraordinary_permission - .clone() - .unwrap(); - legacy - .character_drafts - .get_mut(&host_id) - .unwrap() - .extraordinary_permissions - .push(accepted_permission); - legacy - .decisions - .get_mut(&target_id) - .unwrap() - .proposed_extraordinary_permission = None; - let legacy_context = - permitted_dm_context(&legacy, &private_channel, Some(&host_id), Some(&target_id)) - .unwrap(); - let legacy_encoded = serde_json::to_string(&legacy_context).unwrap(); - assert!(legacy_encoded.contains("legacy_replacement_basis")); - assert!(legacy_encoded.contains("permission:fork-memory")); - assert!(!legacy_encoded.contains("UNRELATED-DECISION-MARKER")); - assert!( - legacy_encoded.len() < 8_000, - "legacy focused context was {} bytes", - legacy_encoded.len() - ); - let legacy_lived = - project_focused_counter_lived_stream(&legacy, Some(&host_id), &target_id).unwrap(); - assert!(legacy_lived.contains("Legacy private character replacement basis")); - assert!(legacy_lived.contains("Fork-memory synchronization")); - assert!(!legacy_lived.contains("UNRELATED-DECISION-MARKER")); - } - - #[tokio::test] - async fn private_channels_and_boundaries_preserve_ownership() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let initial = state(); - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store.clone(), initial.id); - let invite = kernel - .command(SessionZeroCommand::CreateInvites { - actor_account_hash: "account:host".into(), - count: 1, - }) - .await - .unwrap(); - let joined = kernel - .command(SessionZeroCommand::Join { - token: invite.invite_tokens[0].clone(), - account_hash: "account:guest".into(), - display_name: "Guest".into(), - cell_allowance: FIXTURE_CELL_ALLOWANCE, - }) - .await - .unwrap(); - let guest = joined.state.member_for_account("account:guest").unwrap(); - let private = format!("private:{}", guest.id); - let error = kernel - .command(SessionZeroCommand::PostPlayerMessage { - actor_account_hash: "account:host".into(), - expected_revision: joined.state.revision, - channel_id: private, - text: "I should not see this room.".into(), - }) - .await - .unwrap_err(); - assert!(error.to_string().contains("belongs to another member")); - - let bounded = kernel - .command(SessionZeroCommand::SetBoundary { - actor_account_hash: "account:guest".into(), - expected_revision: joined.state.revision, - boundary_id: None, - topic: "Graphic eye injury".into(), - normalized_topic: "eye injury".into(), - level: BoundaryLevel::Line, - }) - .await - .unwrap(); - assert_eq!(bounded.state.aggregate_boundaries.len(), 1); - let encoded = serde_json::to_string(&bounded.state.aggregate_boundaries).unwrap(); - assert!(!encoded.contains(&guest.id)); - assert!(!encoded.contains("account:guest")); - } - - #[test] - fn strictest_boundary_wins_without_attribution() { - let now = Utc::now(); - let boundaries = BTreeMap::from([ - ( - "a".into(), - ContentBoundary { - schema: "ghostlight.content_boundary.v1".into(), - id: "a".into(), - owner_member_id: "one".into(), - topic: "Spiders".into(), - normalized_topic: "spiders".into(), - level: BoundaryLevel::AskFirst, - created_at: now, - updated_at: now, - }, - ), - ( - "b".into(), - ContentBoundary { - schema: "ghostlight.content_boundary.v1".into(), - id: "b".into(), - owner_member_id: "two".into(), - topic: "Spiders".into(), - normalized_topic: "spiders".into(), - level: BoundaryLevel::Veil, - created_at: now, - updated_at: now, - }, - ), - ]); - let aggregate = aggregate_boundaries(&boundaries); - assert_eq!(aggregate[0].level, BoundaryLevel::Veil); - assert!(!serde_json::to_string(&aggregate).unwrap().contains("two")); - } - - #[test] - fn pooled_allowance_is_bounded_by_operator_ceiling() { - let mut state = state(); - for index in 0..7 { - let id = format!("member:{index}"); - state.members.insert( - id.clone(), - SessionZeroMember { - schema: "ghostlight.session_zero_member.v1".into(), - id, - account_hash: format!("account:{index}"), - display_name: format!("P{index}"), - is_host: false, - active: true, - cell_allowance: if index == 0 { 40 } else { 32 }, - joined_at: Utc::now(), - }, - ); - } - assert_eq!(state.pooled_cell_allowance(), OPERATOR_CELL_CEILING); - } - - #[test] - fn blank_conversation_only_draft_cannot_enter_world_compilation() { - let mut draft = state(); - draft.roster_locked = true; - let error = draft.compilation_brief().unwrap_err().to_string(); - assert!(error.contains("Session Zero draft is incomplete")); - assert!(error.contains("starting location")); - assert!(error.contains("public character premise")); - assert!(error.contains("capabilities")); - } - - #[test] - fn optional_opening_or_role_suggestions_do_not_block_custom_compilation() { - let mut draft = state(); - draft.roster_locked = true; - draft.contract.premise = "Keep a refugee clinic supplied during a political crisis.".into(); - draft.contract.canon_horizon = "After Burden of Proof".into(); - draft.contract.starting_where = "Hellas, Mars".into(); - draft.contract.starting_when = "Zhestokost administration".into(); - draft.contract.starting_pressure = "A ration strike and refugee convoy".into(); - draft.contract.desired_goal = "Protect the clinic without becoming an informant.".into(); - draft.contract.tone = vec!["serious political drama".into()]; - draft.contract.pacing = "deliberate pressure with sharp turns".into(); - draft.contract.consequence_style = "durable, low arbitrary lethality".into(); - draft.contract.narrative_focus = "institutional leverage and human solidarity".into(); - draft.contract.dm_style = "candid, challenging, and humane".into(); - let character = draft - .character_drafts - .get_mut(&draft.host_member_id) - .unwrap(); - character.public_premise = - "A Corvid logistics mediator caught between institutions.".into(); - character.capabilities = vec!["Route planning".into()]; - character.goals = vec!["Get the convoy through".into()]; - character.obligations = vec!["A life-debt to the quartermaster".into()]; - draft.decisions.insert( - "opening:optional".into(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "opening:optional".into(), - owner_member_id: None, - prompt: "Use this generated opening?".into(), - proposed_resolution: "A generated frame the player may ignore.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: Some(CampaignContractPatch { - starting_where: Some("Somewhere else".into()), - ..Default::default() - }), - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: false, - resolved: false, - }, - ); - assert!(draft.compilation_brief().is_ok()); - draft - .decisions - .get_mut("opening:optional") - .unwrap() - .material = true; - assert!( - draft - .compilation_brief() - .unwrap_err() - .to_string() - .contains("material decisions") - ); - } - - #[test] - fn legacy_generated_openings_are_demoted_without_advancing_session_state() { - let mut draft = state(); - let revision = draft.revision; - let shared_epoch = draft.shared_epoch; - draft.decisions.insert( - "opening:legacy".into(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "opening:legacy".into(), - owner_member_id: None, - prompt: "Use 'A Legacy Opening' as the starting frame for further Session Zero discussion?".into(), - proposed_resolution: "An optional generated opening.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: Some(CampaignContractPatch { - starting_where: Some("Somewhere the player did not choose".into()), - ..Default::default() - }), - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }, - ); - - assert!(demote_legacy_nonmaterial_decisions(&mut draft)); - assert!(!draft.decisions["opening:legacy"].material); - assert_eq!(draft.revision, revision); - assert_eq!(draft.shared_epoch, shared_epoch); - assert!(!demote_legacy_nonmaterial_decisions(&mut draft)); - } - - #[tokio::test] - async fn registry_load_persists_the_payloadless_question_demotion() { - let root = tempdir().unwrap(); - let mut draft = state(); - let id = draft.id; - let revision = draft.revision; - draft.decisions.insert( - "decision:persisted-legacy-question".into(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:persisted-legacy-question".into(), - owner_member_id: None, - prompt: "Which campaign aspiration should lead?".into(), - proposed_resolution: "Choose one of two discussion prompts.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }, - ); - let directory = root.path().join(id.to_string()); - fs::create_dir(&directory).unwrap(); - let store = CampaignStore::open(directory.join("session-zero.cc")).unwrap(); - SessionZeroKernel::initialize(&store, &draft).unwrap(); - drop(store); - - let registry = SessionZeroRegistry::new(root.path()).unwrap(); - registry.load_existing().await.unwrap(); - let loaded = registry.snapshot(id).await.unwrap(); - assert!(!loaded.decisions["decision:persisted-legacy-question"].material); - assert_eq!(loaded.revision, revision); - } - - #[tokio::test] - async fn published_session_zero_cannot_own_campaign_entry_navigation() { - let root = tempdir().unwrap(); - let mut published = state(); - published.status = SessionZeroStatus::Published; - let published_id = published.id; - let published_directory = root.path().join(published_id.to_string()); - fs::create_dir(&published_directory).unwrap(); - let published_store = - CampaignStore::open(published_directory.join("session-zero.cc")).unwrap(); - SessionZeroKernel::initialize(&published_store, &published).unwrap(); - drop(published_store); - - let registry = SessionZeroRegistry::new(root.path()).unwrap(); - registry.load_existing().await.unwrap(); - - assert_eq!( - registry.session_for_account("account:host").await.unwrap(), - None, - "published negotiation history must not replace the campaign entry surface" - ); - } - - #[tokio::test] - async fn registry_load_persists_legacy_receipt_ownership_migration() { - let root = tempdir().unwrap(); - let mut draft = compilable_state(); - let id = draft.id; - let revision = draft.revision; - draft.status = SessionZeroStatus::Review; - draft.preview = Some(WorldCompilePreview { - schema: "ghostlight.world_compile_preview.v1".into(), - title: "Current preview".into(), - campaign: crate::resolution::tests::campaign(2, 1), - evidence_receipts: vec![], - evidence_coverage: vec![], - gaps: vec![], - branch_assumptions: vec![], - requires_approval: true, - }); - let old = model_receipt("world_compile", "receipt:old-world", 10); - let current_plan = model_receipt("custom_retrieval_plan", "receipt:current-plan", 20); - let current_world = model_receipt("world_compile", "receipt:current-world", 30); - let current_agency = model_receipt("agency_compile", "receipt:current-agency", 40); - draft.preview_model_receipts = vec![ - old.clone(), - current_plan.clone(), - current_world.clone(), - current_agency.clone(), - ]; - let directory = root.path().join(id.to_string()); - fs::create_dir(&directory).unwrap(); - let store = CampaignStore::open(directory.join("session-zero.cc")).unwrap(); - SessionZeroKernel::initialize(&store, &draft).unwrap(); - drop(store); - - let registry = SessionZeroRegistry::new(root.path()).unwrap(); - registry.load_existing().await.unwrap(); - let loaded = registry.snapshot(id).await.unwrap(); - assert_eq!(loaded.revision, revision); - assert_eq!( - loaded.model_receipts, - [ - old, - current_plan.clone(), - current_world.clone(), - current_agency.clone() - ] - ); - assert_eq!( - loaded.preview_model_receipts, - [current_plan, current_world, current_agency] - ); - - let runtime = registry.runtime(id).await.unwrap(); - let (_, persisted) = runtime - .store - .load::("session_zero.v1", &id.to_string()) - .unwrap() - .unwrap(); - assert_eq!(persisted.model_receipts, loaded.model_receipts); - assert_eq!( - persisted.preview_model_receipts, - loaded.preview_model_receipts - ); - } - - #[tokio::test] - async fn actor_filtered_surface_never_projects_other_private_state_or_account_hashes() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let mut initial = state(); - let host_id = initial.host_member_id.clone(); - initial.character_drafts.get_mut(&host_id).unwrap().secrets = - vec!["HOST-ONLY-CIPHER-ORCHID".into()]; - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store, initial.id); - let invite = kernel - .command(SessionZeroCommand::CreateInvites { - actor_account_hash: "account:host".into(), - count: 1, - }) - .await - .unwrap(); - let joined = kernel - .command(SessionZeroCommand::Join { - token: invite.invite_tokens[0].clone(), - account_hash: "account:guest".into(), - display_name: "Guest".into(), - cell_allowance: FIXTURE_CELL_ALLOWANCE, - }) - .await - .unwrap(); - let encoded = - serde_json::to_string(&session_zero_surface(&joined.state, "account:guest").unwrap()) - .unwrap(); - assert!(!encoded.contains("HOST-ONLY-CIPHER-ORCHID")); - assert!(!encoded.contains("account:host")); - assert!(!encoded.contains("account:guest")); - assert!(!encoded.contains("token_hash")); - let member_schema = serde_json::to_string(&schema_for!(SessionZeroMember)).unwrap(); - assert!(!member_schema.contains("account_hash")); - } - - #[test] - fn private_preview_projects_exact_relationship_subjects_for_player_approval() { - let mut campaign = crate::resolution::tests::campaign(1, 1); - let mut quartermaster = campaign.actors["player"].clone(); - quartermaster.id = "relationship-anchor:quartermaster".into(); - quartermaster.name = "convoy quartermaster".into(); - quartermaster - .capabilities - .insert("convoy manifest custody".into()); - quartermaster - .knowledge - .insert("the convoy departure window".into()); - quartermaster.relationships.insert( - "faction-0000".into(), - "serves as the faction's convoy quartermaster".into(), - ); - campaign - .actors - .insert(quartermaster.id.clone(), quartermaster); - campaign - .actors - .get_mut("player") - .unwrap() - .relationships - .insert( - "relationship-anchor:quartermaster".into(), - "owes them a life-debt".into(), - ); - campaign - .institutions - .get_mut("faction-0000") - .unwrap() - .resources = vec!["OPERATOR-ONLY-RESERVE".into()]; - campaign.institutions.get_mut("faction-0000").unwrap().goals = - vec!["PRIVATE-INSTITUTION-GOAL".into()]; - let preview = WorldCompilePreview { - schema: "ghostlight.world_compile_preview.v1".into(), - title: "Private relationship witness".into(), - campaign, - evidence_receipts: vec![], - evidence_coverage: vec![], - gaps: vec![], - branch_assumptions: vec![], - requires_approval: true, - }; - - let subjects = private_relationship_subjects(&preview, "player"); - assert_eq!(subjects.len(), 1); - assert_eq!(subjects[0].subject_kind, "actor"); - assert_eq!(subjects[0].name, "convoy quartermaster"); - assert_eq!(subjects[0].location_id.as_deref(), Some("center")); - assert_eq!(subjects[0].location_name.as_deref(), Some("Center")); - assert_eq!(subjects[0].relationship, "owes them a life-debt"); - let counterpart = subjects[0].counterpart_actor_state.as_ref().unwrap(); - assert!(counterpart.capabilities.contains("convoy manifest custody")); - assert!( - counterpart - .knowledge - .contains("the convoy departure window") - ); - assert_eq!( - counterpart.relationships.get("faction-0000"), - Some(&"serves as the faction's convoy quartermaster".into()) - ); - assert!(private_relationship_subjects(&preview, "not-the-player").is_empty()); - - let mut draft = state(); - let actor_id = draft.character_drafts[&draft.host_member_id] - .actor_id - .clone(); - let mut projected_preview = preview; - let mut player = projected_preview.campaign.actors.remove("player").unwrap(); - player.id = actor_id.clone(); - projected_preview.campaign.player_actor_id = actor_id.clone(); - projected_preview.campaign.actors.insert(actor_id, player); - draft.preview = Some(projected_preview); - draft.status = SessionZeroStatus::Review; - let surface = serde_json::to_string( - &session_zero_surface(&draft, "account:host").expect("owner surface"), - ) - .unwrap(); - assert!(surface.contains("Your private compiled relationships")); - assert!(surface.contains("Compiled world preview")); - assert!(surface.contains("Topology")); - assert!(surface.contains("Institutions")); - assert!(surface.contains("convoy quartermaster")); - assert!(surface.contains("owes them a life-debt")); - assert!(surface.contains("Counterpart-owned state")); - assert!(surface.contains("convoy manifest custody")); - assert!(surface.contains("the convoy departure window")); - assert!(surface.contains("serves as the faction's convoy quartermaster")); - assert!(!surface.contains("OPERATOR-ONLY-RESERVE")); - assert!(!surface.contains("PRIVATE-INSTITUTION-GOAL")); - } - - #[test] - fn session_zero_surface_exposes_accept_decline_counter_discuss_and_owned_boundary_controls_as_bindings() - { - let mut draft = state(); - let host = draft.host_member_id.clone(); - draft.boundaries.insert( - "boundary:host".into(), - ContentBoundary { - schema: "ghostlight.content_boundary.v1".into(), - id: "boundary:host".into(), - owner_member_id: host, - topic: "medical horror".into(), - normalized_topic: "medical horror".into(), - level: BoundaryLevel::Veil, - created_at: Utc::now(), - updated_at: Utc::now(), - }, - ); - draft.decisions.insert( - "decision:tone".into(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:tone".into(), - owner_member_id: None, - prompt: "How severe should consequences be?".into(), - proposed_resolution: "Consequences are durable but rarely lethal.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: Some(CampaignContractPatch { - consequence_style: Some("Consequences are durable but rarely lethal.".into()), - ..Default::default() - }), - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }, - ); - - let encoded = - serde_json::to_string(&session_zero_surface(&draft, "account:host").unwrap()).unwrap(); - assert!(encoded.contains("Accept")); - assert!(encoded.contains("Decline")); - assert!(encoded.contains("Counter")); - assert!(encoded.contains("Discuss")); - assert!(encoded.contains("session_zero.boundary.remove")); - assert!(encoded.contains("\"bindingName\":\"counter\"")); - assert!(encoded.contains("\"maxLength\":2000")); - assert!(!encoded.contains("payload.fields")); - assert!(!encoded.contains("\"kind\":\"form\"")); - } - - #[test] - fn locked_incomplete_session_projects_the_authoritative_compilation_blocker() { - let mut draft = state(); - draft.roster_locked = true; - draft.status = SessionZeroStatus::RosterLocked; - - let encoded = - serde_json::to_string(&session_zero_surface(&draft, "account:host").unwrap()).unwrap(); - - assert!(encoded.contains("Before compilation")); - assert!(encoded.contains("Session Zero draft is incomplete: campaign premise")); - assert!(encoded.contains("Host · awaiting review · host")); - assert!(!encoded.contains("Host · not ready")); - } - - #[test] - fn compilable_locked_draft_can_retry_after_compiler_failure() { - let mut draft = compilable_state(); - draft.roster_locked = true; - draft.status = SessionZeroStatus::Drafting; - let encoded = - serde_json::to_string(&session_zero_surface(&draft, "account:host").unwrap()).unwrap(); - assert!(encoded.contains("Compile campaign preview")); - - draft.status = SessionZeroStatus::Compiling; - let encoded = - serde_json::to_string(&session_zero_surface(&draft, "account:host").unwrap()).unwrap(); - assert!(!encoded.contains("Compile campaign preview")); - } - - #[tokio::test] - async fn gap_preview_is_retained_and_every_approval_binds_its_exact_world_digest() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let mut initial = compilable_state(); - initial.roster_locked = true; - initial.status = SessionZeroStatus::Compiling; - initial.model_receipts = vec![ - model_receipt("global_agency_doctrine_synthesis", "receipt:repeated", 10), - model_receipt("global_agency_doctrine_synthesis", "receipt:repeated", 20), - ]; - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store, initial.id); - let gap = "The requested clinic district is branch-local.".to_owned(); - let current_receipt = model_receipt("custom_retrieval_plan", "receipt:current-preview", 30); - let preview = WorldCompilePreview { - schema: "ghostlight.world_compile_preview.v1".into(), - title: "Hellas clinic pressure".into(), - campaign: crate::resolution::tests::campaign(2, 1), - evidence_receipts: vec![], - evidence_coverage: vec![], - gaps: vec![gap.clone()], - branch_assumptions: vec!["The convoy arrived this morning.".into()], - requires_approval: true, - }; - let installed = kernel - .command(SessionZeroCommand::InstallPreview { - expected_revision: initial.revision, - preview, - model_receipts: vec![current_receipt.clone()], - }) - .await - .unwrap(); - assert_eq!(installed.state.status, SessionZeroStatus::Drafting); - assert_eq!( - installed.state.preview.as_ref().unwrap().gaps, - [gap.clone()] - ); - let surface = - serde_json::to_string(&session_zero_surface(&installed.state, "account:host").unwrap()) - .unwrap(); - assert!(surface.contains("Evidence gaps requiring table approval")); - assert!(surface.contains("Review this exact preview with its evidence gaps")); - assert!(surface.contains("Discard this preview and continue drafting")); - assert!(!surface.contains("Compile campaign preview")); - - let reviewing = kernel - .command(SessionZeroCommand::ReviewCompilationGaps { - actor_account_hash: "account:host".into(), - expected_revision: installed.state.revision, - }) - .await - .unwrap(); - assert_eq!(reviewing.state.status, SessionZeroStatus::Review); - let approved = kernel - .command(SessionZeroCommand::Approve { - actor_account_hash: "account:host".into(), - expected_revision: reviewing.state.revision, - }) - .await - .unwrap(); - let exact_digest = approved.state.world_preview_digest().unwrap(); - assert_eq!( - approved - .state - .approvals - .values() - .next() - .unwrap() - .world_preview_digest, - exact_digest - ); - let publication = publication_from_session( - &approved.state, - approved.state.preview.as_ref().unwrap().campaign.id, - ) - .unwrap(); - assert_eq!(publication.approved_world_preview_digest, exact_digest); - assert_eq!(publication.approved_evidence_gaps, [gap]); - assert_eq!(approved.state.model_receipts.len(), 3); - assert_eq!( - approved.state.preview_model_receipts, - [current_receipt.clone()] - ); - let published_store = - CampaignStore::open(dir.path().join("published-campaign.cc")).unwrap(); - let published_campaign = approved.state.preview.as_ref().unwrap(); - published_store - .create_session_zero_campaign( - &published_campaign.campaign, - &published_campaign.evidence_receipts, - &approved.state.preview_model_receipts, - &publication, - ) - .unwrap(); - assert_eq!( - published_store.keys("persona_stage_receipt.v1").unwrap(), - [current_receipt.storage_key()] - ); - - let mut substituted = approved.state; - substituted.preview.as_mut().unwrap().title = "A different world".into(); - assert!(substituted.approved_brief().is_err()); - assert!( - publication_from_session( - &substituted, - substituted.preview.as_ref().unwrap().campaign.id - ) - .is_err() - ); - } - - #[tokio::test] - async fn host_can_discard_a_noncanonical_preview_without_changing_the_draft() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let mut initial = compilable_state(); - initial.roster_locked = true; - initial.status = SessionZeroStatus::Drafting; - initial.preview = Some(WorldCompilePreview { - schema: "ghostlight.world_compile_preview.v1".into(), - title: "Retired candidate".into(), - campaign: crate::resolution::tests::campaign(2, 1), - evidence_receipts: vec![], - evidence_coverage: vec![], - gaps: vec!["A material gap".into()], - branch_assumptions: vec![], - requires_approval: true, - }); - let original_contract = initial.contract.clone(); - let original_character = initial.character_drafts[&initial.host_member_id].clone(); - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store, initial.id); - - let discarded = kernel - .command(SessionZeroCommand::DiscardPreview { - actor_account_hash: "account:host".into(), - expected_revision: initial.revision, - }) - .await - .unwrap(); - - assert!(discarded.state.preview.is_none()); - assert_eq!(discarded.state.status, SessionZeroStatus::RosterLocked); - assert_eq!(discarded.state.contract, original_contract); - assert_eq!( - discarded.state.character_drafts[&discarded.state.host_member_id], - original_character - ); - let surface = - serde_json::to_string(&session_zero_surface(&discarded.state, "account:host").unwrap()) - .unwrap(); - assert!(surface.contains("Compile campaign preview")); - assert!(!surface.contains("Discard this preview")); - } - - #[test] - fn player_surface_projects_the_complete_private_ledger_and_exact_typed_change() { - let mut draft = state(); - let host = draft.host_member_id.clone(); - let actor_id = draft.character_drafts[&host].actor_id.clone(); - let character = draft.character_drafts.get_mut(&host).unwrap(); - character.name = "Sable".into(); - character.public_premise = "Corvid logistics mediator".into(); - character.private_history = vec!["FULL-SUNG-NAME-ANCHOR".into()]; - character.secrets = vec!["FORGED-TRANSIT-CREDENTIAL".into()]; - character.capabilities = vec!["RATION-LEDGER-RECONCILIATION".into()]; - character.knowledge = vec!["HELLAS-SUPPLY-ROUTES".into()]; - character.equipment = vec!["MINOR-RATION-AUDIT-SEAL".into()]; - character - .relationships - .insert("convoy-quartermaster".into(), "LIFE-DEBT".into()); - character.obligations = vec!["CLINIC-EXPECTS-EXCEPTIONS".into()]; - character.vulnerabilities = vec!["TRACEABLE-SYNC-SIGNATURE".into()]; - character.goals = vec!["KEEP-CONVOY-SUPPLIED".into()]; - character.extraordinary_permissions = vec![ExtraordinaryPermission { - schema: "ghostlight.extraordinary_permission.v1".into(), - id: "permission:fork-memory".into(), - actor_id, - name: "FORK-MEMORY-SYNCHRONIZATION".into(), - reliable_scope: "ONE-WILLING-MIND-AT-CLOSE-RANGE".into(), - prerequisites: vec!["FRESH-CONSENT".into()], - costs: vec!["MIGRAINE".into()], - limits: vec!["NO-COMPULSION".into()], - opposition: vec!["ACTIVE-SHIELDING".into()], - exposure: vec!["TECHNICAL-SIGNATURE".into()], - effect_ceiling: "BOUNDED-MEMORY-OR-SKILL".into(), - evidence_receipt_ids: vec![], - branch_local: true, - }]; - draft.decisions.insert( - "decision:sable".into(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:sable".into(), - owner_member_id: Some(host), - prompt: "Materialize Sable?".into(), - proposed_resolution: "Record the negotiated character.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: Some(CampaignContractPatch { - starting_where: Some("MARS-HELLAS-ZHESTOKOST".into()), - tone: Some(vec!["COLD-INSTITUTIONAL-PRESSURE".into()]), - ..Default::default() - }), - proposed_character_patch: Some(CharacterDraftPatch { - goals_add: vec!["BUILD-A-DURABLE-REFUGEE-ROUTE".into()], - equipment_add: vec!["COUNTERSIGNED-LEDGER".into()], - ..Default::default() - }), - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }, - ); - - let encoded = - serde_json::to_string(&session_zero_surface(&draft, "account:host").unwrap()).unwrap(); - for expected in [ - "FULL-SUNG-NAME-ANCHOR", - "FORGED-TRANSIT-CREDENTIAL", - "RATION-LEDGER-RECONCILIATION", - "HELLAS-SUPPLY-ROUTES", - "MINOR-RATION-AUDIT-SEAL", - "LIFE-DEBT", - "CLINIC-EXPECTS-EXCEPTIONS", - "TRACEABLE-SYNC-SIGNATURE", - "KEEP-CONVOY-SUPPLIED", - "FORK-MEMORY-SYNCHRONIZATION", - "ONE-WILLING-MIND-AT-CLOSE-RANGE", - "MARS-HELLAS-ZHESTOKOST", - "COLD-INSTITUTIONAL-PRESSURE", - "BUILD-A-DURABLE-REFUGEE-ROUTE", - "COUNTERSIGNED-LEDGER", - "Exact typed change", - ] { - assert!( - encoded.contains(expected), - "missing player projection: {expected}" - ); - } - } - - #[tokio::test] - async fn independent_private_dm_outputs_commit_across_unrelated_global_revisions() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let initial = state(); - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store, initial.id); - let invite = kernel - .command(SessionZeroCommand::CreateInvites { - actor_account_hash: "account:host".into(), - count: 1, - }) - .await - .unwrap(); - let joined = kernel - .command(SessionZeroCommand::Join { - token: invite.invite_tokens[0].clone(), - account_hash: "account:guest".into(), - display_name: "Guest".into(), - cell_allowance: FIXTURE_CELL_ALLOWANCE, - }) - .await - .unwrap(); - let host_id = joined.state.host_member_id.clone(); - let guest_id = joined - .state - .member_for_account("account:guest") - .unwrap() - .id - .clone(); - let host_channel = format!("private:{host_id}"); - let guest_channel = format!("private:{guest_id}"); - let host_message = kernel - .command(SessionZeroCommand::PostPlayerMessage { - actor_account_hash: "account:host".into(), - expected_revision: joined.state.revision, - channel_id: host_channel.clone(), - text: "I want a debt to the harbor guild.".into(), - }) - .await - .unwrap(); - let both_messages = kernel - .command(SessionZeroCommand::PostPlayerMessage { - actor_account_hash: "account:guest".into(), - expected_revision: host_message.state.revision, - channel_id: guest_channel.clone(), - text: "I want to find my missing sibling.".into(), - }) - .await - .unwrap(); - let private_delta = |goal: &str| SessionZeroDelta { - character_patch: Some(CharacterDraftPatch { - goals_add: vec![goal.into()], - ..Default::default() - }), - dm_speech: format!("Let's make {goal} concrete."), - ..Default::default() - }; - let host_applied = kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: 0, - expected_channel_revision: 1, - channel_id: host_channel, - member_id: Some(host_id.clone()), - supersedes_countered_decision_id: None, - delta: private_delta("repay the harbor guild"), - model_receipts: vec![], - }) - .await - .unwrap(); - assert!(host_applied.state.revision > both_messages.state.revision); - let guest_applied = kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: 0, - expected_channel_revision: 1, - channel_id: guest_channel, - member_id: Some(guest_id.clone()), - supersedes_countered_decision_id: None, - delta: private_delta("find my missing sibling"), - model_receipts: vec![], - }) - .await - .unwrap(); - assert!( - guest_applied.state.character_drafts[&host_id] - .goals - .contains(&"repay the harbor guild".into()) - ); - assert!( - guest_applied.state.character_drafts[&guest_id] - .goals - .contains(&"find my missing sibling".into()) - ); - } - - #[tokio::test] - async fn local_dm_failure_notice_changes_only_the_conversation() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let initial = state(); - let state_id = initial.id; - let channel_id = "shared:table".to_string(); - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store, state_id); - let posted = kernel - .command(SessionZeroCommand::PostPlayerMessage { - actor_account_hash: "account:host".into(), - expected_revision: initial.revision, - channel_id: channel_id.clone(), - text: "Please try this turn.".into(), - }) - .await - .unwrap(); - let before = posted.state.clone(); - let receipt = model_receipt("session_zero_dm_persona", "receipt:dm-notice", 10); - - let noticed = kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: before.shared_epoch, - expected_channel_revision: before.channels[&channel_id].revision, - channel_id: channel_id.clone(), - member_id: None, - supersedes_countered_decision_id: None, - delta: SessionZeroDelta { - dm_speech: "I couldn't finish that response. No draft state changed.".into(), - ..Default::default() - }, - model_receipts: vec![receipt.clone()], - }) - .await - .unwrap(); - - assert_eq!(noticed.state.contract, before.contract); - assert_eq!(noticed.state.character_drafts, before.character_drafts); - assert_eq!(noticed.state.decisions, before.decisions); - assert_eq!(noticed.state.boundaries, before.boundaries); - assert_eq!(noticed.state.shared_epoch, before.shared_epoch); - assert_eq!(noticed.state.character_epochs, before.character_epochs); - assert_eq!(noticed.state.model_receipts, [receipt]); - assert_eq!( - noticed.state.preview_model_receipts, - before.preview_model_receipts - ); - assert_eq!(noticed.state.revision, before.revision + 1); - assert_eq!( - noticed.state.channels[&channel_id].revision, - before.channels[&channel_id].revision + 1 - ); - let last_message_id = noticed.state.channels[&channel_id] - .message_ids - .last() - .unwrap(); - assert_eq!( - noticed.state.messages[last_message_id].speaker, - SessionZeroSpeakerKind::Dm - ); - } - - #[tokio::test] - async fn payloadless_legacy_decision_cannot_be_accepted_or_claim_a_commit() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let mut initial = state(); - let decision_id = "decision:empty-promise".to_string(); - initial.decisions.insert( - decision_id.clone(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: decision_id.clone(), - owner_member_id: None, - prompt: "Materialize the character?".into(), - proposed_resolution: "Materialize the character exactly as discussed.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }, - ); - let before = initial.clone(); - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store.clone(), initial.id); - - let surface = - serde_json::to_string(&session_zero_surface(&initial, "account:host").unwrap()) - .unwrap(); - assert!(!surface.contains(&format!("session-zero.decision.{decision_id}.accept"))); - assert!(surface.contains("has no typed state change attached")); - - let error = kernel - .command(SessionZeroCommand::ResolveDecision { - actor_account_hash: "account:host".into(), - expected_revision: initial.revision, - decision_id, - resolution: SessionZeroDecisionResolution::Accept, - counter: None, - }) - .await - .unwrap_err(); - assert!(error.to_string().contains("no typed state change")); - assert_eq!( - store - .load::("session_zero.v1", &initial.id.to_string()) - .unwrap() - .unwrap() - .1, - before - ); - } - - #[tokio::test] - async fn material_character_bargain_is_inert_until_its_owner_accepts() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let initial = state(); - let member_id = initial.host_member_id.clone(); - let actor_id = initial.character_drafts[&member_id].actor_id.clone(); - let state_id = initial.id; - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store, state_id); - let decision_id = "decision:dangerous-gift".to_string(); - let proposed = ExtraordinaryPermission { - schema: "ghostlight.extraordinary_permission.v1".into(), - id: "permission:storm-step".into(), - actor_id, - name: "Storm step".into(), - reliable_scope: "Cross one visible gap in a flash of lightning".into(), - prerequisites: vec!["A charged storm is overhead".into()], - costs: vec!["Become visibly marked by the storm".into()], - limits: vec!["Cannot carry another person".into()], - opposition: vec!["Grounded containment".into()], - exposure: vec!["Grounding wards can detect the transit".into()], - effect_ceiling: "Movement only; never bypasses a sealed ward".into(), - evidence_receipt_ids: vec![], - branch_local: true, - }; - let proposed_turn = kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: 0, - expected_channel_revision: 0, - channel_id: format!("private:{member_id}"), - member_id: Some(member_id.clone()), - supersedes_countered_decision_id: None, - delta: SessionZeroDelta { - decisions: vec![SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: decision_id.clone(), - owner_member_id: Some(member_id.clone()), - prompt: "Accept Storm step with these limits?".into(), - proposed_resolution: "Grant the bounded permission.".into(), - proposed_extraordinary_permission: Some(proposed.clone()), - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }], - dm_speech: "This power needs a cost and a ceiling.".into(), - ..Default::default() - }, - model_receipts: vec![], - }) - .await - .unwrap(); - assert!( - proposed_turn.state.character_drafts[&member_id] - .extraordinary_permissions - .is_empty() - ); - - let accepted = kernel - .command(SessionZeroCommand::ResolveDecision { - actor_account_hash: "account:host".into(), - expected_revision: proposed_turn.state.revision, - decision_id, - resolution: SessionZeroDecisionResolution::Accept, - counter: None, - }) - .await - .unwrap(); - assert_eq!( - accepted.state.character_drafts[&member_id].extraordinary_permissions, - vec![proposed] - ); - } - - #[tokio::test] - async fn declining_a_material_decision_resolves_it_without_applying_its_patch() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let mut initial = state(); - let original_contract = initial.contract.clone(); - let decision_id = "decision:declined-opening".to_string(); - initial.decisions.insert( - decision_id.clone(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: decision_id.clone(), - owner_member_id: None, - prompt: "Use the generated opening?".into(), - proposed_resolution: "Move the campaign to an unrelated generated opening.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: Some(CampaignContractPatch { - starting_where: Some("Wrong place".into()), - ..Default::default() - }), - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }, - ); - let state_id = initial.id; - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store, state_id); - - let surface = - serde_json::to_string(&session_zero_surface(&initial, "account:host").unwrap()) - .unwrap(); - assert!(surface.contains(&format!("session-zero.decision.{decision_id}.decline"))); - - let declined = kernel - .command(SessionZeroCommand::ResolveDecision { - actor_account_hash: "account:host".into(), - expected_revision: initial.revision, - decision_id: decision_id.clone(), - resolution: SessionZeroDecisionResolution::Decline, - counter: None, - }) - .await - .unwrap(); - - assert_eq!(declined.state.contract, original_contract); - assert!(declined.state.decisions[&decision_id].resolved); - assert!( - declined.state.decisions[&decision_id] - .pending_counter - .is_none() - ); - } - - #[tokio::test] - async fn counterproposal_preserves_inert_payload_until_fresh_typed_decision_arrives() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let mut initial = state(); - let member_id = initial.host_member_id.clone(); - let actor_id = initial.character_drafts[&member_id].actor_id.clone(); - let original_decision_id = "decision:fork-memory".to_string(); - let permission = |id: &str, costs: Vec| ExtraordinaryPermission { - schema: "ghostlight.extraordinary_permission.v1".into(), - id: id.into(), - actor_id: actor_id.clone(), - name: "Fork-memory synchronization".into(), - reliable_scope: "Synchronize briefly with one willing nearby mind".into(), - prerequisites: vec!["The other mind gives informed consent".into()], - costs, - limits: vec!["Cannot read an unwilling mind".into()], - opposition: vec!["Active shielding".into()], - exposure: vec!["Leaves a traceable synchronization signature".into()], - effect_ceiling: "Shared impressions, never identity overwrite".into(), - evidence_receipt_ids: vec![], - branch_local: true, - }; - initial.decisions.insert( - original_decision_id.clone(), - SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: original_decision_id.clone(), - owner_member_id: Some(member_id.clone()), - prompt: "Accept the proposed fork-memory limits?".into(), - proposed_resolution: "Memory contamination always fades after rest.".into(), - proposed_extraordinary_permission: Some(permission( - "permission:fork-memory:original", - vec!["Temporary memory contamination".into()], - )), - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }, - ); - let state_id = initial.id; - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store.clone(), state_id); - - let counter_text = "Contamination usually fades, but intense synchronization can leave permanent associative scars."; - let countered = kernel - .command(SessionZeroCommand::ResolveDecision { - actor_account_hash: "account:host".into(), - expected_revision: 0, - decision_id: original_decision_id.clone(), - resolution: SessionZeroDecisionResolution::Counter, - counter: Some(counter_text.into()), - }) - .await - .unwrap(); - let pending = &countered.state.decisions[&original_decision_id]; - assert_eq!(pending.pending_counter.as_deref(), Some(counter_text)); - assert_eq!( - pending - .proposed_extraordinary_permission - .as_ref() - .unwrap() - .id, - "permission:fork-memory:original" - ); - assert!(pending.proposed_contract_patch.is_none()); - assert!(pending.proposed_character_patch.is_none()); - assert!(!pending.resolved); - let private_channel = format!("private:{member_id}"); - let last_message_id = countered.state.channels[&private_channel] - .message_ids - .last() - .unwrap(); - assert!( - countered.state.messages[last_message_id] - .text - .contains(counter_text) - ); - let pending_surface = - serde_json::to_string(&session_zero_surface(&countered.state, "account:host").unwrap()) - .unwrap(); - assert!(pending_surface.contains("Counterproposal recorded")); - assert!(pending_surface.contains("Retired typed change")); - assert!(!pending_surface.contains(&format!( - "session-zero.decision.{original_decision_id}.accept" - ))); - - let before_rejected_accept = countered.state.clone(); - let rejected_accept = kernel - .command(SessionZeroCommand::ResolveDecision { - actor_account_hash: "account:host".into(), - expected_revision: countered.state.revision, - decision_id: original_decision_id.clone(), - resolution: SessionZeroDecisionResolution::Accept, - counter: None, - }) - .await - .unwrap_err(); - assert!( - rejected_accept - .to_string() - .contains("awaiting a fresh DM decision") - ); - assert_eq!( - store - .load::("session_zero.v1", &state_id.to_string()) - .unwrap() - .unwrap() - .1, - before_rejected_accept - ); - - let rejected_replacement = kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: countered.state.character_epochs[&member_id], - expected_channel_revision: countered.state.channels[&private_channel].revision, - channel_id: private_channel.clone(), - member_id: Some(member_id.clone()), - supersedes_countered_decision_id: Some(original_decision_id.clone()), - delta: SessionZeroDelta { - dm_speech: "I need to think about that.".into(), - ..Default::default() - }, - model_receipts: vec![], - }) - .await - .unwrap_err(); - assert!( - rejected_replacement - .to_string() - .contains("exactly one fresh decision") - ); - assert_eq!( - store - .load::("session_zero.v1", &state_id.to_string()) - .unwrap() - .unwrap() - .1, - before_rejected_accept - ); - - let wrong_lane = kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: countered.state.character_epochs[&member_id], - expected_channel_revision: countered.state.channels[&private_channel].revision, - channel_id: private_channel.clone(), - member_id: Some(member_id.clone()), - supersedes_countered_decision_id: Some(original_decision_id.clone()), - delta: SessionZeroDelta { - decisions: vec![SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:wrong-lane".into(), - owner_member_id: Some(member_id.clone()), - prompt: "Replace the ability with a goal?".into(), - proposed_resolution: "This is not the countered state lane.".into(), - proposed_extraordinary_permission: None, - proposed_contract_patch: None, - proposed_character_patch: Some(CharacterDraftPatch { - goals_add: vec!["Wrong replacement lane".into()], - ..Default::default() - }), - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }], - ..Default::default() - }, - model_receipts: vec![], - }) - .await - .unwrap_err(); - assert!(wrong_lane.to_string().contains("same typed state lane")); - - let wrong_identity = kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: countered.state.character_epochs[&member_id], - expected_channel_revision: countered.state.channels[&private_channel].revision, - channel_id: private_channel.clone(), - member_id: Some(member_id.clone()), - supersedes_countered_decision_id: Some(original_decision_id.clone()), - delta: SessionZeroDelta { - decisions: vec![SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: "decision:wrong-permission-identity".into(), - owner_member_id: Some(member_id.clone()), - prompt: "Accept a different permission?".into(), - proposed_resolution: counter_text.into(), - proposed_extraordinary_permission: Some(permission( - "permission:fork-memory:impostor", - vec!["Intense synchronization can leave scars".into()], - )), - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }], - ..Default::default() - }, - model_receipts: vec![], - }) - .await - .unwrap_err(); - assert!(wrong_identity.to_string().contains("permission identity")); - assert_eq!( - store - .load::("session_zero.v1", &state_id.to_string()) - .unwrap() - .unwrap() - .1, - before_rejected_accept - ); - - let replacement_decision_id = "decision:fork-memory:revised".to_string(); - let revised_permission = permission( - "permission:fork-memory:original", - vec![ - "Migraines and memory contamination".into(), - "Intense synchronization can leave permanent associative scars".into(), - ], - ); - let replaced = kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: countered.state.character_epochs[&member_id], - expected_channel_revision: countered.state.channels[&private_channel].revision, - channel_id: private_channel, - member_id: Some(member_id.clone()), - supersedes_countered_decision_id: Some(original_decision_id.clone()), - delta: SessionZeroDelta { - decisions: vec![SessionZeroDecision { - schema: "ghostlight.session_zero_decision.v1".into(), - id: replacement_decision_id.clone(), - owner_member_id: Some(member_id.clone()), - prompt: "Accept the revised fork-memory bargain?".into(), - proposed_resolution: counter_text.into(), - proposed_extraordinary_permission: Some(revised_permission.clone()), - proposed_contract_patch: None, - proposed_character_patch: None, - evidence_receipt_ids: vec![], - pending_counter: None, - material: true, - resolved: false, - }], - dm_speech: "That cost preserves the ability and its stakes.".into(), - ..Default::default() - }, - model_receipts: vec![], - }) - .await - .unwrap(); - assert!(replaced.state.decisions[&original_decision_id].resolved); - assert!(!replaced.state.decisions[&replacement_decision_id].resolved); - assert!( - replaced.state.character_drafts[&member_id] - .extraordinary_permissions - .is_empty() - ); - - let accepted = kernel - .command(SessionZeroCommand::ResolveDecision { - actor_account_hash: "account:host".into(), - expected_revision: replaced.state.revision, - decision_id: replacement_decision_id, - resolution: SessionZeroDecisionResolution::Accept, - counter: None, - }) - .await - .unwrap(); - assert_eq!( - accepted.state.character_drafts[&member_id].extraordinary_permissions, - vec![revised_permission] - ); - } - - #[tokio::test] - async fn malformed_shared_dm_delta_cannot_cross_private_authority() { - let dir = tempdir().unwrap(); - let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); - let initial = state(); - let state_id = initial.id; - let before = initial.clone(); - SessionZeroKernel::initialize(&store, &initial).unwrap(); - let kernel = SessionZeroKernel::start(store.clone(), state_id); - let result = kernel - .command(SessionZeroCommand::ApplyDmTurn { - expected_component_epoch: 0, - expected_channel_revision: 0, - channel_id: "shared:table".into(), - member_id: None, - supersedes_countered_decision_id: None, - delta: SessionZeroDelta { - character_patch: Some(CharacterDraftPatch { - secrets_add: vec!["leaked private history".into()], - ..Default::default() - }), - dm_speech: "This must not commit.".into(), - ..Default::default() - }, - model_receipts: vec![], - }) - .await; - assert!(result.is_err()); - let persisted = store - .load::("session_zero.v1", &state_id.to_string()) - .unwrap() - .unwrap() - .1; - assert_eq!(persisted, before); - } -} diff --git a/crates/ghostlight-dungeon/src/surface.rs b/crates/ghostlight-dungeon/src/surface.rs deleted file mode 100644 index c4cccf5..0000000 --- a/crates/ghostlight-dungeon/src/surface.rs +++ /dev/null @@ -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::>(); - 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::>(); - 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::>() - .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::>(); - let reported_event_ids = accessible_news - .iter() - .flat_map(|item| item.event_ids.iter().cloned()) - .collect::>(); - 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::>(); - 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::>() - })); - 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::>(), - "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::>() - }, - "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 { - 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::>() - .join(", "), - cell.merge_loss.total, - cell.detail_focus_subject_id.as_deref().unwrap_or("none"), - cell.rationale - ) - }) - .collect::>() - .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::>() - .join("\n"); - let provider_attempt_count = stages - .iter() - .map(|stage| stage.provider_attempts.len()) - .sum::(); - 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::>().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 { - if values.is_empty() { - "none".into() - } else { - values.iter().cloned().collect::>().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::>(); - 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\"")); - } -} diff --git a/crates/ghostlight-dungeon/src/transition.rs b/crates/ghostlight-dungeon/src/transition.rs deleted file mode 100644 index 2334f92..0000000 --- a/crates/ghostlight-dungeon/src/transition.rs +++ /dev/null @@ -1,5406 +0,0 @@ -use crate::domain::{ - CivicSystemManifest, FactScope, MAX_POSTURE_CHARS, OutcomeBand, StrategicOutcomeBand, -}; -use anyhow::{Result, anyhow}; -use chrono::{DateTime, Utc}; -use schemars::{JsonSchema, schema_for}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; -use uuid::Uuid; - -#[derive( - Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, Hash, -)] -#[serde(rename_all = "snake_case")] -pub enum SubjectKind { - Campaign, - Actor, - Population, - Institution, - Place, - Resource, - Pressure, - Proposition, - Channel, -} - -#[derive( - Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, Hash, -)] -pub struct SubjectRef { - pub kind: SubjectKind, - pub id: String, -} - -#[derive( - Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, Hash, -)] -#[serde(rename_all = "snake_case")] -pub enum WorldComponentKind { - Identity, - Occupancy, - Custody, - ResourceState, - Capability, - Condition, - Knowledge, - Memory, - Relationship, - Commitment, - Pressure, - Posture, - PopulationMembership, - PopulationLineage, - PlaceProfile, - PropositionContent, - Topology, - CivicSystem, - Lifecycle, - WorldTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct WorldComponentRef { - pub subject: SubjectRef, - pub component: WorldComponentKind, - pub entry_id: Option, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct ActionMeans { - pub schema: String, - pub actor: SubjectRef, - #[schemars(length(min = 1, max = 4000))] - pub description: String, - #[serde(default)] - pub targets: Vec, - #[serde(default)] - pub instruments: Vec, - #[serde(default)] - pub places: Vec, - #[serde(default)] - pub route_ids: BTreeSet, - #[serde(default)] - pub channels: Vec, - #[serde(default)] - #[schemars(length(max = 4000))] - pub speech: Option, - #[serde(default)] - pub state_references: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct MutationIntent { - pub schema: String, - pub component: WorldComponentKind, - #[serde(default)] - pub targets: Vec, - #[schemars(length(min = 1, max = 1000))] - pub desired_change: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum MutationProcedure { - ForegroundAttempt, - DirectCommand, - NpcAttempt, - ReactionAppraisal, - StrategicOutcome, - Governance, - CompilerAdmission, - Lifecycle, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(tag = "type", content = "value", rename_all = "snake_case")] -pub enum MutationOutcomeBinding { - Foreground(OutcomeBand), - Strategic(StrategicOutcomeBand), - StrategicWave(Vec), - Deterministic, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct StrategicOutcomeSourceBinding { - pub action_digest: String, - pub band: StrategicOutcomeBand, -} - -#[derive( - Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, Hash, -)] -#[serde(rename_all = "snake_case")] -pub enum WorldMutationOperation { - Relocate, - TransferCustody, - ResourceCreate, - ResourceTransform, - ResourceConsume, - ResourceDamage, - ResourceRepair, - ResourceSplit, - ResourceCombine, - CapabilityGrant, - CapabilityAlter, - CapabilitySuspend, - CapabilityRetire, - ConditionApply, - ConditionAlter, - ConditionClear, - CommitmentCreate, - CommitmentAlter, - CommitmentFulfill, - CommitmentDefault, - CommitmentRetire, - RelationshipCreate, - RelationshipAlter, - RelationshipRetire, - PressureCreate, - PressureAdvance, - PressureReduce, - PressureResolve, - PressureRetire, - KnowledgeAcquire, - KnowledgeCommunicate, - KnowledgeConceal, - KnowledgeCorrect, - KnowledgeInvalidate, - MemoryRecord, - MemoryRevise, - MemoryRetire, - PostureChange, - PopulationJoin, - PopulationLeave, - PopulationTransfer, - PopulationSplit, - PopulationMerge, - IdentityAdopt, - IdentityDisclose, - IdentityRestrict, - IdentityRetire, - TopologyAdd, - TopologyAlter, - TopologyOpen, - TopologyClose, - TopologyRetire, - CivicSystemSet, - AdmitEntity, - RetireEntity, - AdvanceWorldTime, -} - -#[derive( - Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, Hash, -)] -#[serde(rename_all = "snake_case")] -pub enum MutationSubjectRole { - Subject, - Actor, - Owner, - Counterparty, - OriginPlace, - DestinationPlace, - Resource, - RelatedResource, - SourceCustodian, - DestinationCustodian, - Pressure, - Knower, - Speaker, - Recipient, - Proposition, - Channel, - SourcePopulation, - DestinationPopulation, - ParentPopulation, - ChildPopulation, - RelationshipSource, - RelationshipTarget, - TopologyOrigin, - TopologyDestination, - Entity, - InitialPlace, -} - -#[derive( - Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, Hash, -)] -#[serde(rename_all = "snake_case")] -pub enum MutationStringRole { - RouteId, - ResourceKind, - ResourceLabel, - RecipeId, - Description, - Summary, - RetirementReason, - CapabilityId, - ConditionId, - CommitmentId, - RelationshipId, - MemoryId, - EventId, - PressureLabel, - Posture, - IdentityHandleId, - IdentityHandleValue, - TopologyEdgeId, - Distance, - AdmissionReceiptId, -} - -#[derive( - Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord, Hash, -)] -#[serde(rename_all = "snake_case")] -pub enum MutationIntegerRole { - Quantity, - Integrity, - Severity, - RelationshipStrengthDelta, - PressureAmount, - TravelMinutes, - WorldMinutes, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct IntegerBounds { - pub minimum: i64, - pub maximum: i64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct StringConstraint { - #[serde(default)] - pub allowed_values: BTreeSet, - #[schemars(range(min = 1))] - pub minimum_length: u16, - #[schemars(range(min = 1))] - pub maximum_length: u16, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct MutationSubjectBinding { - pub role: MutationSubjectRole, - pub allowed_subjects: BTreeSet, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct MutationPermit { - pub id: String, - pub operation: WorldMutationOperation, - pub subject_bindings: Vec, - #[serde(default)] - pub string_constraints: BTreeMap, - #[serde(default)] - pub integer_bounds: BTreeMap, - #[serde(default)] - pub exact_mutation: Option, - #[schemars(range(min = 1))] - pub maximum_uses: u16, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct MutationAuthorityEnvelope { - pub schema: String, - pub id: String, - pub campaign_id: Uuid, - pub world_revision: u64, - pub resolution_epoch: Option, - pub procedure: MutationProcedure, - pub source_subject: Option, - pub outcome: MutationOutcomeBinding, - #[schemars(length(min = 1, max = 1000))] - pub effect_ceiling: String, - pub permits: Vec, - #[serde(default)] - pub authority_receipt_ids: BTreeSet, - pub expires_at: DateTime, - pub digest: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ResourceMutationOperation { - Create, - Transform, - Consume, - Damage, - Repair, - Split, - Combine, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum CapabilityMutationOperation { - Grant, - Alter, - Suspend, - Retire, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ConditionMutationOperation { - Apply, - Alter, - Clear, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum CommitmentKind { - Goal, - Obligation, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum CommitmentMutationOperation { - Create, - Alter, - Fulfill, - Default, - Retire, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum RelationshipMutationOperation { - Create, - Alter, - Retire, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum PressureMutationOperation { - Create, - Advance, - Reduce, - Resolve, - Retire, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum KnowledgeMutationOperation { - Acquire, - Communicate, - Conceal, - Correct, - Invalidate, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum MemoryMutationOperation { - Record, - Revise, - Retire, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum PopulationMembershipOperation { - Join, - Leave, - Transfer, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum PopulationLineageOperation { - Split, - Merge, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum IdentityMutationOperation { - Adopt, - Disclose, - Restrict, - Retire, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum TopologyMutationOperation { - Add, - Alter, - Open, - Close, - Retire, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum AdmittedEntityProfile { - Place { - #[schemars(length(min = 1, max = 240))] - name: String, - container: Option, - #[serde(default)] - persistent_features: BTreeSet, - }, - Proposition { - #[schemars(length(min = 1, max = 4000))] - statement: String, - scope: FactScope, - #[serde(default)] - evidence_receipt_ids: BTreeSet, - #[serde(default)] - discoverable_at_places: BTreeSet, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(tag = "type", rename_all = "snake_case")] -pub enum WorldMutation { - Relocate { - subject: SubjectRef, - from_place: SubjectRef, - to_place: SubjectRef, - route_id: String, - }, - TransferCustody { - resource: SubjectRef, - from_custodian: SubjectRef, - to_custodian: SubjectRef, - }, - MutateResource { - resource: SubjectRef, - operation: ResourceMutationOperation, - custodian: Option, - #[serde(default)] - related_resources: Vec, - resource_kind: Option, - resource_label: Option, - recipe_id: Option, - quantity: Option, - integrity: Option, - }, - ChangeCapability { - subject: SubjectRef, - operation: CapabilityMutationOperation, - capability_id: String, - #[schemars(length(max = 1000))] - description: Option, - }, - ChangeCondition { - subject: SubjectRef, - operation: ConditionMutationOperation, - condition_id: String, - #[schemars(length(max = 1000))] - description: Option, - severity: Option, - }, - ChangeCommitment { - subject: SubjectRef, - operation: CommitmentMutationOperation, - kind: CommitmentKind, - commitment_id: String, - counterparty: Option, - #[schemars(length(max = 1000))] - description: Option, - }, - ChangeRelationship { - source: SubjectRef, - target: SubjectRef, - operation: RelationshipMutationOperation, - relationship_id: String, - #[schemars(length(max = 1000))] - description: Option, - strength_delta: Option, - }, - ChangePressure { - pressure: SubjectRef, - owner: SubjectRef, - operation: PressureMutationOperation, - amount: Option, - #[schemars(length(max = 240))] - label: Option, - }, - ChangeKnowledge { - operation: KnowledgeMutationOperation, - proposition: SubjectRef, - knower: Option, - speaker: Option, - #[serde(default)] - recipients: Vec, - channel: Option, - }, - ChangeMemory { - subject: SubjectRef, - operation: MemoryMutationOperation, - memory_id: String, - event_id: Option, - #[schemars(length(max = 1000))] - summary: Option, - }, - ChangePosture { - subject: SubjectRef, - posture: String, - }, - ChangePopulationMembership { - actor: SubjectRef, - operation: PopulationMembershipOperation, - source_population: Option, - destination_population: Option, - }, - ChangePopulationLineage { - operation: PopulationLineageOperation, - #[serde(default)] - parent_populations: Vec, - #[serde(default)] - child_populations: Vec, - remainder_population: Option, - }, - ChangeIdentity { - subject: SubjectRef, - operation: IdentityMutationOperation, - handle_id: String, - handle_value: Option, - #[serde(default)] - audience: Vec, - }, - ChangeTopology { - operation: TopologyMutationOperation, - edge_id: String, - from_place: SubjectRef, - to_place: SubjectRef, - #[serde(default)] - distance: Option, - travel_minutes: Option, - }, - SetCivicSystem { - jurisdiction: SubjectRef, - system: CivicSystemManifest, - }, - AdmitEntity { - subject: SubjectRef, - initial_components: BTreeSet, - #[serde(default)] - initial_place: Option, - #[serde(default)] - initial_profile: Option, - admission_receipt_id: String, - }, - RetireEntity { - subject: SubjectRef, - #[schemars(length(min = 1, max = 1000))] - reason: String, - }, - AdvanceWorldTime { - campaign: SubjectRef, - minutes: i64, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct PermittedWorldMutation { - pub permit_id: String, - pub mutation: WorldMutation, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct WorldMutationBatch { - pub schema: String, - pub id: String, - pub campaign_id: Uuid, - pub expected_world_revision: u64, - pub expected_resolution_epoch: Option, - pub authority_envelope_digest: String, - pub source_receipt_id: String, - pub means_digest: Option, - pub intended_effect_digest: Option, - #[serde(default)] - pub mutations: Vec, - pub digest: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct ComponentVersionChange { - pub component: WorldComponentRef, - pub previous_version: Option, - pub version: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct WorldMutationReceipt { - pub schema: String, - pub id: String, - pub campaign_id: Uuid, - pub batch_digest: String, - pub authority_envelope_digest: String, - pub previous_world_revision: u64, - pub world_revision: u64, - pub mutation_digests: Vec, - pub component_versions: Vec, - #[serde(default)] - pub derived_event_ids: Vec, - pub committed_at: DateTime, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct IdentityHandleState { - pub schema: String, - pub id: String, - pub subject: SubjectRef, - pub value: String, - pub active: bool, - #[serde(default)] - pub known_by: BTreeSet, - #[serde(default)] - pub restricted_to: BTreeSet, - pub source_revision: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum LifecycleStatus { - Admitted, - Active, - Consumed, - Retired, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct TypedSubject { - pub schema: String, - pub subject: SubjectRef, - pub lifecycle: LifecycleStatus, - #[serde(default)] - pub admitted_components: BTreeSet, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct ResourceComponentState { - pub schema: String, - pub resource: SubjectRef, - pub resource_kind: String, - pub label: String, - pub quantity: i64, - pub integrity: i64, - #[serde(default)] - pub qualities: BTreeSet, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)] -pub struct SubjectEntryKey { - pub subject: SubjectRef, - pub entry_id: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct CapabilityComponentState { - pub description: String, - pub suspended: bool, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct ConditionComponentState { - pub description: String, - pub severity: Option, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct CommitmentComponentState { - pub kind: CommitmentKind, - pub description: String, - pub counterparty: Option, - pub status: String, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct RelationshipComponentState { - pub source: SubjectRef, - pub target: SubjectRef, - pub description: String, - pub strength: Option, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct PressureComponentState { - pub pressure: SubjectRef, - pub owner: SubjectRef, - pub label: String, - pub progress: i64, - pub threshold: i64, - pub resolved: bool, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)] -pub struct KnowledgeKey { - pub knower: SubjectRef, - pub proposition: SubjectRef, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct KnowledgeComponentState { - pub status: String, - pub source: Option, - pub channel: Option, - #[serde(default)] - pub concealed_from: BTreeSet, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct MemoryComponentState { - pub event_id: Option, - pub summary: String, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)] -pub struct MembershipKey { - pub actor: SubjectRef, - pub population: SubjectRef, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct PopulationMembershipState { - pub active: bool, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct PopulationLineageState { - pub id: String, - pub operation: PopulationLineageOperation, - pub parent_populations: Vec, - pub child_populations: Vec, - pub remainder_population: Option, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct PlaceComponentState { - pub place: SubjectRef, - pub name: String, - pub container: Option, - #[serde(default)] - pub persistent_features: BTreeSet, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct PropositionComponentState { - pub proposition: SubjectRef, - pub statement: String, - pub scope: FactScope, - #[serde(default)] - pub evidence_receipt_ids: BTreeSet, - #[serde(default)] - pub discoverable_at_places: BTreeSet, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct TopologyComponentState { - pub id: String, - pub from_place: SubjectRef, - pub to_place: SubjectRef, - #[serde(default = "default_route_distance")] - pub distance: String, - pub travel_minutes: i64, - pub open: bool, - pub version: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct ComponentWorldState { - pub schema: String, - pub campaign_id: Uuid, - pub revision: u64, - pub resolution_epoch: u64, - pub world_time: DateTime, - pub subjects: BTreeMap, - pub occupancy: BTreeMap, - pub custody: BTreeMap, - pub resources: BTreeMap, - pub capabilities: BTreeMap, - pub conditions: BTreeMap, - pub commitments: BTreeMap, - pub relationships: BTreeMap, - pub pressures: BTreeMap, - pub knowledge: BTreeMap, - pub memories: BTreeMap, - pub postures: BTreeMap, - pub memberships: BTreeMap, - pub population_lineages: BTreeMap, - pub identities: BTreeMap, - #[serde(default)] - pub place_profiles: BTreeMap, - #[serde(default)] - pub propositions: BTreeMap, - pub topology: BTreeMap, - #[serde(default)] - pub civic_systems: BTreeMap, -} - -fn default_route_distance() -> String { - "unspecified".into() -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MutationApplication { - pub state: ComponentWorldState, - pub receipt: WorldMutationReceipt, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum AgencyAdmissionExpectation { - Admissible, - Impossible, - BargainRequired, - MissingPrimitive, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)] -#[serde(rename_all = "snake_case")] -pub enum AgencyResolutionLane { - Foreground, - Npc, - Reaction, - StrategicActor, - StrategicPopulation, - StrategicInstitution, - ArenaConstituent, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -pub struct AgencyAttemptCase { - pub schema: String, - pub id: String, - pub domain: String, - pub scenario: String, - pub world_fixture_ids: Vec, - pub means: ActionMeans, - pub intended_effects: Vec, - pub expected_admission: AgencyAdmissionExpectation, - #[serde(default)] - pub expected_mutation_operations: BTreeSet, - #[serde(default)] - pub forbidden_mutation_operations: BTreeSet, - #[serde(default)] - pub expected_bargains: Vec, - #[serde(default)] - pub equivalent_lanes: BTreeSet, - #[serde(default)] - pub invariant_witnesses: Vec, - pub review_status: String, - pub missing_primitive: Option, -} - -pub fn envelope_digest(envelope: &MutationAuthorityEnvelope) -> Result { - let mut value = envelope.clone(); - value.digest.clear(); - Ok(sha256(&rmp_serde::to_vec_named(&value)?)) -} - -pub fn mutation_batch_digest(batch: &WorldMutationBatch) -> Result { - let mut value = batch.clone(); - value.digest.clear(); - Ok(sha256(&rmp_serde::to_vec_named(&value)?)) -} - -pub fn mutation_digest(mutation: &PermittedWorldMutation) -> Result { - Ok(sha256(&rmp_serde::to_vec_named(mutation)?)) -} - -fn sha256(bytes: &[u8]) -> String { - format!("sha256:{:x}", Sha256::digest(bytes)) -} - -pub fn apply_component_world_batch( - state: &ComponentWorldState, - envelope: &MutationAuthorityEnvelope, - batch: &WorldMutationBatch, - now: DateTime, -) -> Result { - validate_batch_structure(envelope, batch, now)?; - if state.campaign_id != batch.campaign_id - || state.revision != batch.expected_world_revision - || batch - .expected_resolution_epoch - .is_some_and(|epoch| state.resolution_epoch != epoch) - { - return Err(anyhow!( - "component world state does not match the mutation snapshot" - )); - } - - let mut next = state.clone(); - for proposed in &batch.mutations { - apply_component_mutation(&mut next, &proposed.mutation)?; - } - validate_component_world(&next)?; - - let previous_revision = state.revision; - next.revision = next.revision.saturating_add(1); - let mutation_digests = batch - .mutations - .iter() - .map(mutation_digest) - .collect::>>()?; - let component_versions = batch - .mutations - .iter() - .flat_map(|proposed| mutation_component_refs(&proposed.mutation)) - .collect::>() - .into_iter() - .map(|(subject, component, entry_id)| ComponentVersionChange { - component: WorldComponentRef { - subject, - component, - entry_id, - version: next.revision, - }, - previous_version: Some(previous_revision), - version: Some(next.revision), - }) - .collect(); - Ok(MutationApplication { - state: next, - receipt: WorldMutationReceipt { - schema: "ghostlight.world_mutation_receipt.v1".into(), - id: format!("mutation:{}", batch.id), - campaign_id: batch.campaign_id, - batch_digest: batch.digest.clone(), - authority_envelope_digest: envelope.digest.clone(), - previous_world_revision: previous_revision, - world_revision: previous_revision.saturating_add(1), - mutation_digests, - component_versions, - derived_event_ids: Vec::new(), - committed_at: now, - }, - }) -} - -fn active_subject<'a>( - state: &'a ComponentWorldState, - subject: &SubjectRef, -) -> Result<&'a TypedSubject> { - state - .subjects - .get(subject) - .filter(|record| { - matches!( - record.lifecycle, - LifecycleStatus::Admitted | LifecycleStatus::Active - ) - }) - .ok_or_else(|| anyhow!("mutation subject is absent or retired: {}", subject.id)) -} - -fn require_kind(subject: &SubjectRef, kind: SubjectKind) -> Result<()> { - if subject.kind != kind { - return Err(anyhow!( - "subject {} has kind {:?}, expected {:?}", - subject.id, - subject.kind, - kind - )); - } - Ok(()) -} - -fn next_component_version(state: &ComponentWorldState) -> u64 { - state.revision.saturating_add(1) -} - -fn apply_component_mutation( - state: &mut ComponentWorldState, - mutation: &WorldMutation, -) -> Result<()> { - use WorldMutation::*; - match mutation { - Relocate { - subject, - from_place, - to_place, - route_id, - } => { - active_subject(state, subject)?; - active_subject(state, from_place)?; - active_subject(state, to_place)?; - require_kind(from_place, SubjectKind::Place)?; - require_kind(to_place, SubjectKind::Place)?; - let route = state - .topology - .get(route_id) - .ok_or_else(|| anyhow!("relocation route does not exist"))?; - if !route.open || route.from_place != *from_place || route.to_place != *to_place { - return Err(anyhow!( - "relocation route does not admit the exact origin and destination" - )); - } - if state.occupancy.get(subject) != Some(from_place) { - return Err(anyhow!( - "relocation origin does not match canonical occupancy" - )); - } - state.occupancy.insert(subject.clone(), to_place.clone()); - } - TransferCustody { - resource, - from_custodian, - to_custodian, - } => { - active_subject(state, resource)?; - active_subject(state, from_custodian)?; - active_subject(state, to_custodian)?; - require_kind(resource, SubjectKind::Resource)?; - if state.custody.get(resource) != Some(from_custodian) { - return Err(anyhow!("custody source does not own the exact resource")); - } - state.custody.insert(resource.clone(), to_custodian.clone()); - } - MutateResource { - resource, - operation, - custodian, - related_resources, - resource_kind, - resource_label, - recipe_id, - quantity, - integrity, - } => apply_resource_mutation( - state, - resource, - operation, - custodian.as_ref(), - related_resources, - resource_kind.as_deref(), - resource_label.as_deref(), - recipe_id.as_deref(), - *quantity, - *integrity, - )?, - ChangeCapability { - subject, - operation, - capability_id, - description, - } => { - active_subject(state, subject)?; - let key = SubjectEntryKey { - subject: subject.clone(), - entry_id: capability_id.clone(), - }; - let version = next_component_version(state); - match operation { - CapabilityMutationOperation::Grant => { - if state.capabilities.contains_key(&key) { - return Err(anyhow!("capability already exists")); - } - state.capabilities.insert( - key, - CapabilityComponentState { - description: description - .clone() - .unwrap_or_else(|| capability_id.clone()), - suspended: false, - version, - }, - ); - } - CapabilityMutationOperation::Alter => { - let value = state - .capabilities - .get_mut(&key) - .ok_or_else(|| anyhow!("capability does not exist"))?; - value.description = description - .clone() - .ok_or_else(|| anyhow!("capability alteration lacks a description"))?; - value.version = version; - } - CapabilityMutationOperation::Suspend => { - let value = state - .capabilities - .get_mut(&key) - .ok_or_else(|| anyhow!("capability does not exist"))?; - value.suspended = true; - value.version = version; - } - CapabilityMutationOperation::Retire => { - if state.capabilities.remove(&key).is_none() { - return Err(anyhow!("capability does not exist")); - } - } - } - } - ChangeCondition { - subject, - operation, - condition_id, - description, - severity, - } => { - active_subject(state, subject)?; - let key = SubjectEntryKey { - subject: subject.clone(), - entry_id: condition_id.clone(), - }; - let version = next_component_version(state); - match operation { - ConditionMutationOperation::Apply => { - if state.conditions.contains_key(&key) { - return Err(anyhow!("condition already exists")); - } - state.conditions.insert( - key, - ConditionComponentState { - description: description - .clone() - .unwrap_or_else(|| condition_id.clone()), - severity: *severity, - version, - }, - ); - } - ConditionMutationOperation::Alter => { - let value = state - .conditions - .get_mut(&key) - .ok_or_else(|| anyhow!("condition does not exist"))?; - if let Some(description) = description { - value.description = description.clone(); - } - if severity.is_some() { - value.severity = *severity; - } - value.version = version; - } - ConditionMutationOperation::Clear => { - if state.conditions.remove(&key).is_none() { - return Err(anyhow!("condition does not exist")); - } - } - } - } - ChangeCommitment { - subject, - operation, - kind, - commitment_id, - counterparty, - description, - } => apply_commitment_mutation( - state, - subject, - operation, - kind, - commitment_id, - counterparty.as_ref(), - description.as_deref(), - )?, - ChangeRelationship { - source, - target, - operation, - relationship_id, - description, - strength_delta, - } => apply_relationship_mutation( - state, - source, - target, - operation, - relationship_id, - description.as_deref(), - *strength_delta, - )?, - ChangePressure { - pressure, - owner, - operation, - amount, - label, - } => apply_pressure_mutation(state, pressure, owner, operation, *amount, label.as_deref())?, - ChangeKnowledge { - operation, - proposition, - knower, - speaker, - recipients, - channel, - } => apply_knowledge_mutation( - state, - operation, - proposition, - knower.as_ref(), - speaker.as_ref(), - recipients, - channel.as_ref(), - )?, - ChangeMemory { - subject, - operation, - memory_id, - event_id, - summary, - } => apply_memory_mutation( - state, - subject, - operation, - memory_id, - event_id.as_deref(), - summary.as_deref(), - )?, - ChangePosture { subject, posture } => { - active_subject(state, subject)?; - state.postures.insert(subject.clone(), posture.clone()); - } - ChangePopulationMembership { - actor, - operation, - source_population, - destination_population, - } => apply_membership_mutation( - state, - actor, - operation, - source_population.as_ref(), - destination_population.as_ref(), - )?, - ChangePopulationLineage { - operation, - parent_populations, - child_populations, - remainder_population, - } => apply_lineage_mutation( - state, - operation, - parent_populations, - child_populations, - remainder_population.as_ref(), - )?, - ChangeIdentity { - subject, - operation, - handle_id, - handle_value, - audience, - } => apply_identity_mutation( - state, - subject, - operation, - handle_id, - handle_value.as_deref(), - audience, - )?, - ChangeTopology { - operation, - edge_id, - from_place, - to_place, - distance, - travel_minutes, - } => apply_topology_mutation( - state, - operation, - edge_id, - from_place, - to_place, - distance.as_deref(), - *travel_minutes, - )?, - SetCivicSystem { - jurisdiction, - system, - } => apply_civic_system(state, jurisdiction, system)?, - AdmitEntity { - subject, - initial_components, - initial_place, - initial_profile, - .. - } => { - if subject.kind == SubjectKind::Resource { - return Err(anyhow!("resources are admitted by resource creation")); - } - if state.subjects.contains_key(subject) { - return Err(anyhow!("entity already exists")); - } - state.subjects.insert( - subject.clone(), - TypedSubject { - schema: "ghostlight.typed_subject.v1".into(), - subject: subject.clone(), - lifecycle: LifecycleStatus::Admitted, - admitted_components: initial_components.clone(), - version: next_component_version(state), - }, - ); - if let Some(place) = initial_place { - active_subject(state, place)?; - require_kind(place, SubjectKind::Place)?; - state.occupancy.insert(subject.clone(), place.clone()); - } - let version = next_component_version(state); - match initial_profile { - Some(AdmittedEntityProfile::Place { - name, - container, - persistent_features, - }) => { - state.place_profiles.insert( - subject.clone(), - PlaceComponentState { - place: subject.clone(), - name: name.clone(), - container: container.clone(), - persistent_features: persistent_features.clone(), - version, - }, - ); - } - Some(AdmittedEntityProfile::Proposition { - statement, - scope, - evidence_receipt_ids, - discoverable_at_places, - }) => { - state.propositions.insert( - subject.clone(), - PropositionComponentState { - proposition: subject.clone(), - statement: statement.clone(), - scope: scope.clone(), - evidence_receipt_ids: evidence_receipt_ids.clone(), - discoverable_at_places: discoverable_at_places.clone(), - version, - }, - ); - } - None => {} - } - } - RetireEntity { subject, .. } => retire_entity(state, subject)?, - AdvanceWorldTime { campaign, minutes } => { - require_kind(campaign, SubjectKind::Campaign)?; - active_subject(state, campaign)?; - state.world_time += chrono::Duration::minutes(*minutes); - } - } - Ok(()) -} - -fn apply_civic_system( - state: &mut ComponentWorldState, - jurisdiction: &SubjectRef, - system: &CivicSystemManifest, -) -> Result<()> { - active_subject(state, jurisdiction)?; - require_kind(jurisdiction, SubjectKind::Place)?; - if system.schema != "ghostlight.civic_system_manifest.v1" - || system.jurisdiction_location_id != jurisdiction.id - || system.semantic_verification_receipt_id.trim().is_empty() - { - return Err(anyhow!( - "civic system is not bound to its exact jurisdiction and verifier" - )); - } - let expected_version = state - .civic_systems - .get(jurisdiction) - .map(|current| current.version.saturating_add(1)) - .unwrap_or(0); - if system.version != expected_version { - return Err(anyhow!( - "civic system version is stale: expected {expected_version}, got {}", - system.version - )); - } - for id in &system.governing_institution_ids { - let subject = SubjectRef { - kind: SubjectKind::Institution, - id: id.clone(), - }; - active_subject(state, &subject)?; - } - for id in &system.resident_population_ids { - let resident = SubjectRef { - kind: SubjectKind::Population, - id: id.clone(), - }; - active_subject(state, &resident)?; - for fact_id in system - .public_authority_fact_ids - .iter() - .chain(system.public_selection_fact_ids.iter()) - .chain(system.public_resource_fact_ids.iter()) - .chain(system.public_redress_fact_ids.iter()) - { - let proposition = SubjectRef { - kind: SubjectKind::Proposition, - id: fact_id.clone(), - }; - active_subject(state, &proposition)?; - if !state.knowledge.contains_key(&KnowledgeKey { - knower: resident.clone(), - proposition, - }) { - return Err(anyhow!( - "resident population lacks a civic proposition bound by the manifest" - )); - } - } - } - for id in &system.political_relation_ids { - if !state.relationships.contains_key(id) { - return Err(anyhow!( - "civic system references a missing political relation" - )); - } - } - state - .civic_systems - .insert(jurisdiction.clone(), system.clone()); - Ok(()) -} - -#[allow(clippy::too_many_arguments)] -fn apply_resource_mutation( - state: &mut ComponentWorldState, - resource: &SubjectRef, - operation: &ResourceMutationOperation, - custodian: Option<&SubjectRef>, - related_resources: &[SubjectRef], - resource_kind: Option<&str>, - resource_label: Option<&str>, - recipe_id: Option<&str>, - quantity: Option, - integrity: Option, -) -> Result<()> { - require_kind(resource, SubjectKind::Resource)?; - let version = next_component_version(state); - if !matches!(operation, ResourceMutationOperation::Create) { - let custodian = - custodian.ok_or_else(|| anyhow!("resource mutation lacks exact custody authority"))?; - active_subject(state, custodian)?; - if matches!(operation, ResourceMutationOperation::Combine) { - if related_resources - .iter() - .any(|input| state.custody.get(input) != Some(custodian)) - { - return Err(anyhow!("resource combination exceeds exact custody")); - } - } else if state.custody.get(resource) != Some(custodian) { - return Err(anyhow!("resource mutation exceeds exact custody")); - } - } - match operation { - ResourceMutationOperation::Create => { - if state.subjects.contains_key(resource) || state.resources.contains_key(resource) { - return Err(anyhow!("resource already exists")); - } - let custodian = custodian.ok_or_else(|| anyhow!("resource creation lacks custody"))?; - active_subject(state, custodian)?; - let quantity = quantity.ok_or_else(|| anyhow!("resource creation lacks quantity"))?; - if quantity <= 0 { - return Err(anyhow!("resource quantity must be positive")); - } - let resource_kind = resource_kind - .filter(|value| !value.trim().is_empty()) - .ok_or_else(|| anyhow!("resource creation lacks a kind"))?; - let resource_label = resource_label - .filter(|value| !value.trim().is_empty()) - .ok_or_else(|| anyhow!("resource creation lacks a label"))?; - state.subjects.insert( - resource.clone(), - TypedSubject { - schema: "ghostlight.typed_subject.v1".into(), - subject: resource.clone(), - lifecycle: LifecycleStatus::Active, - admitted_components: BTreeSet::from([ - WorldComponentKind::ResourceState, - WorldComponentKind::Custody, - WorldComponentKind::Lifecycle, - ]), - version, - }, - ); - state.resources.insert( - resource.clone(), - ResourceComponentState { - schema: "ghostlight.resource_component.v1".into(), - resource: resource.clone(), - resource_kind: resource_kind.into(), - label: resource_label.into(), - quantity, - integrity: integrity.unwrap_or(100), - qualities: BTreeSet::new(), - version, - }, - ); - state.custody.insert(resource.clone(), custodian.clone()); - } - ResourceMutationOperation::Transform => { - let _recipe = - recipe_id.ok_or_else(|| anyhow!("resource transformation lacks recipe"))?; - let owner = custodian.expect("non-create custody checked").clone(); - for input in related_resources { - active_subject(state, input)?; - require_kind(input, SubjectKind::Resource)?; - if state.custody.get(input) != Some(&owner) { - return Err(anyhow!("resource transformation crosses custody")); - } - } - for input in related_resources { - consume_entire_resource(state, input)?; - } - let value = state - .resources - .get_mut(resource) - .ok_or_else(|| anyhow!("resource does not exist"))?; - if let Some(kind) = resource_kind { - value.resource_kind = kind.into(); - } - if let Some(label) = resource_label { - value.label = label.into(); - } - if quantity.is_some_and(|quantity| quantity != value.quantity) { - return Err(anyhow!( - "resource transformation cannot alter quantity; compose consumption or creation" - )); - } - if let Some(integrity) = integrity { - value.integrity = integrity; - } - value.version = version; - } - ResourceMutationOperation::Consume => { - active_subject(state, resource)?; - let amount = quantity.ok_or_else(|| anyhow!("resource consumption lacks quantity"))?; - if amount <= 0 { - return Err(anyhow!("resource consumption must be positive")); - } - let value = state - .resources - .get_mut(resource) - .ok_or_else(|| anyhow!("resource does not exist"))?; - if value.quantity < amount { - return Err(anyhow!("resource consumption exceeds available quantity")); - } - value.quantity -= amount; - value.version = version; - if value.quantity == 0 { - state.custody.remove(resource); - state.resources.remove(resource); - state - .subjects - .get_mut(resource) - .expect("active resource has a subject") - .lifecycle = LifecycleStatus::Consumed; - } - } - ResourceMutationOperation::Damage | ResourceMutationOperation::Repair => { - active_subject(state, resource)?; - let amount = integrity.ok_or_else(|| anyhow!("integrity mutation lacks amount"))?; - if amount <= 0 { - return Err(anyhow!("integrity mutation must be positive")); - } - let value = state - .resources - .get_mut(resource) - .ok_or_else(|| anyhow!("resource does not exist"))?; - value.integrity = if matches!(operation, ResourceMutationOperation::Damage) { - value.integrity.saturating_sub(amount) - } else { - value.integrity.saturating_add(amount).min(100) - }; - value.version = version; - } - ResourceMutationOperation::Split => { - active_subject(state, resource)?; - let amount = quantity.ok_or_else(|| anyhow!("resource split lacks quantity"))?; - let [child] = related_resources else { - return Err(anyhow!( - "resource split requires exactly one reserved child" - )); - }; - require_kind(child, SubjectKind::Resource)?; - if state.subjects.contains_key(child) { - return Err(anyhow!("resource split child already exists")); - } - let owner = custodian.expect("non-create custody checked").clone(); - let source = state - .resources - .get_mut(resource) - .ok_or_else(|| anyhow!("resource does not exist"))?; - if amount <= 0 || amount >= source.quantity { - return Err(anyhow!( - "resource split must preserve positive source and child lots" - )); - } - source.quantity -= amount; - source.version = version; - let child_state = ResourceComponentState { - schema: source.schema.clone(), - resource: child.clone(), - resource_kind: source.resource_kind.clone(), - label: resource_label.unwrap_or(&source.label).into(), - quantity: amount, - integrity: source.integrity, - qualities: source.qualities.clone(), - version, - }; - state.subjects.insert( - child.clone(), - TypedSubject { - schema: "ghostlight.typed_subject.v1".into(), - subject: child.clone(), - lifecycle: LifecycleStatus::Active, - admitted_components: BTreeSet::from([ - WorldComponentKind::ResourceState, - WorldComponentKind::Custody, - WorldComponentKind::Lifecycle, - ]), - version, - }, - ); - state.resources.insert(child.clone(), child_state); - state.custody.insert(child.clone(), owner); - } - ResourceMutationOperation::Combine => { - if state.subjects.contains_key(resource) { - return Err(anyhow!("combined resource target already exists")); - } - if related_resources.len() < 2 { - return Err(anyhow!("resource combination requires at least two inputs")); - } - let _recipe = recipe_id.ok_or_else(|| anyhow!("resource combination lacks recipe"))?; - let first = related_resources - .first() - .expect("length checked before first"); - let owner = custodian.expect("non-create custody checked").clone(); - let first_state = state - .resources - .get(first) - .cloned() - .ok_or_else(|| anyhow!("combined input does not exist"))?; - let mut total = 0i64; - for input in related_resources { - active_subject(state, input)?; - if state.custody.get(input) != Some(&owner) { - return Err(anyhow!("resource combination crosses custody")); - } - total = total.saturating_add( - state - .resources - .get(input) - .ok_or_else(|| anyhow!("combined input does not exist"))? - .quantity, - ); - } - for input in related_resources { - consume_entire_resource(state, input)?; - } - state.subjects.insert( - resource.clone(), - TypedSubject { - schema: "ghostlight.typed_subject.v1".into(), - subject: resource.clone(), - lifecycle: LifecycleStatus::Active, - admitted_components: BTreeSet::from([ - WorldComponentKind::ResourceState, - WorldComponentKind::Custody, - WorldComponentKind::Lifecycle, - ]), - version, - }, - ); - if quantity.is_some_and(|quantity| quantity != total) { - return Err(anyhow!( - "resource combination must conserve the exact input quantity" - )); - } - state.resources.insert( - resource.clone(), - ResourceComponentState { - schema: first_state.schema, - resource: resource.clone(), - resource_kind: resource_kind.unwrap_or(&first_state.resource_kind).into(), - label: resource_label.unwrap_or(&first_state.label).into(), - quantity: total, - integrity: integrity.unwrap_or(first_state.integrity), - qualities: first_state.qualities, - version, - }, - ); - state.custody.insert(resource.clone(), owner); - } - } - Ok(()) -} - -fn consume_entire_resource(state: &mut ComponentWorldState, resource: &SubjectRef) -> Result<()> { - state - .resources - .remove(resource) - .ok_or_else(|| anyhow!("resource input does not exist"))?; - state.custody.remove(resource); - state - .subjects - .get_mut(resource) - .ok_or_else(|| anyhow!("resource subject does not exist"))? - .lifecycle = LifecycleStatus::Consumed; - Ok(()) -} - -fn apply_commitment_mutation( - state: &mut ComponentWorldState, - subject: &SubjectRef, - operation: &CommitmentMutationOperation, - kind: &CommitmentKind, - commitment_id: &str, - counterparty: Option<&SubjectRef>, - description: Option<&str>, -) -> Result<()> { - active_subject(state, subject)?; - if let Some(counterparty) = counterparty { - active_subject(state, counterparty)?; - } - let key = SubjectEntryKey { - subject: subject.clone(), - entry_id: commitment_id.into(), - }; - let version = next_component_version(state); - match operation { - CommitmentMutationOperation::Create => { - if state.commitments.contains_key(&key) { - return Err(anyhow!("commitment already exists")); - } - state.commitments.insert( - key, - CommitmentComponentState { - kind: kind.clone(), - description: description.unwrap_or(commitment_id).into(), - counterparty: counterparty.cloned(), - status: "active".into(), - version, - }, - ); - } - CommitmentMutationOperation::Alter => { - let value = state - .commitments - .get_mut(&key) - .ok_or_else(|| anyhow!("commitment does not exist"))?; - if let Some(description) = description { - value.description = description.into(); - } - value.counterparty = counterparty.cloned().or(value.counterparty.clone()); - value.version = version; - } - CommitmentMutationOperation::Fulfill => { - let value = state - .commitments - .get_mut(&key) - .ok_or_else(|| anyhow!("commitment does not exist"))?; - value.status = "fulfilled".into(); - value.version = version; - } - CommitmentMutationOperation::Default => { - let value = state - .commitments - .get_mut(&key) - .ok_or_else(|| anyhow!("commitment does not exist"))?; - value.status = "defaulted".into(); - value.version = version; - } - CommitmentMutationOperation::Retire => { - if state.commitments.remove(&key).is_none() { - return Err(anyhow!("commitment does not exist")); - } - } - } - Ok(()) -} - -fn apply_relationship_mutation( - state: &mut ComponentWorldState, - source: &SubjectRef, - target: &SubjectRef, - operation: &RelationshipMutationOperation, - relationship_id: &str, - description: Option<&str>, - strength_delta: Option, -) -> Result<()> { - active_subject(state, source)?; - active_subject(state, target)?; - let version = next_component_version(state); - match operation { - RelationshipMutationOperation::Create => { - if state.relationships.contains_key(relationship_id) { - return Err(anyhow!("relationship already exists")); - } - if strength_delta.is_some_and(|value| !(0..=100).contains(&value)) { - return Err(anyhow!("relationship strength exceeds bounds")); - } - state.relationships.insert( - relationship_id.into(), - RelationshipComponentState { - source: source.clone(), - target: target.clone(), - description: description - .filter(|value| !value.trim().is_empty()) - .ok_or_else(|| anyhow!("relationship creation lacks a description"))? - .into(), - strength: strength_delta, - version, - }, - ); - } - RelationshipMutationOperation::Alter => { - let value = state - .relationships - .get_mut(relationship_id) - .ok_or_else(|| anyhow!("relationship does not exist"))?; - if value.source != *source || value.target != *target { - return Err(anyhow!("relationship endpoints do not match")); - } - if let Some(description) = description.filter(|value| !value.trim().is_empty()) { - value.description = description.into(); - } - if let Some(delta) = strength_delta { - let current = value - .strength - .ok_or_else(|| anyhow!("relationship has no numeric strength"))?; - let next = current - .checked_add(delta) - .filter(|next| (0..=100).contains(next)) - .ok_or_else(|| anyhow!("relationship strength exceeds bounds"))?; - value.strength = Some(next); - } - if description.is_none() && strength_delta.is_none() { - return Err(anyhow!("relationship alteration is empty")); - } - value.version = version; - } - RelationshipMutationOperation::Retire => { - let value = state - .relationships - .get(relationship_id) - .ok_or_else(|| anyhow!("relationship does not exist"))?; - if value.source != *source || value.target != *target { - return Err(anyhow!("relationship endpoints do not match")); - } - state.relationships.remove(relationship_id); - } - } - Ok(()) -} - -fn apply_pressure_mutation( - state: &mut ComponentWorldState, - pressure: &SubjectRef, - owner: &SubjectRef, - operation: &PressureMutationOperation, - amount: Option, - label: Option<&str>, -) -> Result<()> { - require_kind(pressure, SubjectKind::Pressure)?; - active_subject(state, owner)?; - let version = next_component_version(state); - match operation { - PressureMutationOperation::Create => { - if state.subjects.contains_key(pressure) || state.pressures.contains_key(pressure) { - return Err(anyhow!("pressure already exists")); - } - let threshold = amount.unwrap_or(4); - if threshold <= 0 { - return Err(anyhow!("pressure threshold must be positive")); - } - state.subjects.insert( - pressure.clone(), - TypedSubject { - schema: "ghostlight.typed_subject.v1".into(), - subject: pressure.clone(), - lifecycle: LifecycleStatus::Active, - admitted_components: BTreeSet::from([ - WorldComponentKind::Pressure, - WorldComponentKind::Lifecycle, - ]), - version, - }, - ); - state.pressures.insert( - pressure.clone(), - PressureComponentState { - pressure: pressure.clone(), - owner: owner.clone(), - label: label - .filter(|label| !label.trim().is_empty()) - .ok_or_else(|| anyhow!("pressure creation lacks a label"))? - .into(), - progress: 0, - threshold, - resolved: false, - version, - }, - ); - } - PressureMutationOperation::Advance | PressureMutationOperation::Reduce => { - let amount = amount.ok_or_else(|| anyhow!("pressure change lacks an amount"))?; - if amount <= 0 { - return Err(anyhow!("pressure change must be positive")); - } - let value = state - .pressures - .get_mut(pressure) - .ok_or_else(|| anyhow!("pressure does not exist"))?; - if value.owner != *owner || value.resolved { - return Err(anyhow!("pressure owner or lifecycle does not match")); - } - value.progress = if matches!(operation, PressureMutationOperation::Advance) { - value.progress.saturating_add(amount).min(value.threshold) - } else { - value.progress.saturating_sub(amount) - }; - value.version = version; - } - PressureMutationOperation::Resolve => { - let value = state - .pressures - .get_mut(pressure) - .ok_or_else(|| anyhow!("pressure does not exist"))?; - if value.owner != *owner || value.resolved { - return Err(anyhow!("pressure owner or lifecycle does not match")); - } - value.resolved = true; - value.version = version; - } - PressureMutationOperation::Retire => { - let value = state - .pressures - .get(pressure) - .ok_or_else(|| anyhow!("pressure does not exist"))?; - if value.owner != *owner { - return Err(anyhow!("pressure owner does not match")); - } - state.pressures.remove(pressure); - state - .subjects - .get_mut(pressure) - .expect("pressure component has subject") - .lifecycle = LifecycleStatus::Retired; - } - } - Ok(()) -} - -fn apply_knowledge_mutation( - state: &mut ComponentWorldState, - operation: &KnowledgeMutationOperation, - proposition: &SubjectRef, - knower: Option<&SubjectRef>, - speaker: Option<&SubjectRef>, - recipients: &[SubjectRef], - channel: Option<&SubjectRef>, -) -> Result<()> { - active_subject(state, proposition)?; - require_kind(proposition, SubjectKind::Proposition)?; - if let Some(channel) = channel { - active_subject(state, channel)?; - require_kind(channel, SubjectKind::Channel)?; - } - let version = next_component_version(state); - match operation { - KnowledgeMutationOperation::Acquire => { - let knower = knower.ok_or_else(|| anyhow!("knowledge acquisition lacks a knower"))?; - active_subject(state, knower)?; - let key = KnowledgeKey { - knower: knower.clone(), - proposition: proposition.clone(), - }; - if state - .knowledge - .get(&key) - .is_some_and(|knowledge| knowledge.status == "known") - { - return Err(anyhow!("knower already has the proposition")); - } - state.knowledge.insert( - key, - KnowledgeComponentState { - status: "known".into(), - source: None, - channel: channel.cloned(), - concealed_from: BTreeSet::new(), - version, - }, - ); - } - KnowledgeMutationOperation::Communicate => { - let speaker = speaker.ok_or_else(|| anyhow!("communication lacks a speaker"))?; - active_subject(state, speaker)?; - let speaker_key = KnowledgeKey { - knower: speaker.clone(), - proposition: proposition.clone(), - }; - if !state - .knowledge - .get(&speaker_key) - .is_some_and(|knowledge| knowledge.status == "known") - { - return Err(anyhow!("speaker does not know the proposition")); - } - if recipients.is_empty() { - return Err(anyhow!("communication lacks exact recipients")); - } - for recipient in recipients { - active_subject(state, recipient)?; - let key = KnowledgeKey { - knower: recipient.clone(), - proposition: proposition.clone(), - }; - state.knowledge.insert( - key, - KnowledgeComponentState { - status: "known".into(), - source: Some(speaker.clone()), - channel: channel.cloned(), - concealed_from: BTreeSet::new(), - version, - }, - ); - } - } - KnowledgeMutationOperation::Conceal => { - let knower = knower.ok_or_else(|| anyhow!("concealment lacks a knower"))?; - let value = state - .knowledge - .get_mut(&KnowledgeKey { - knower: knower.clone(), - proposition: proposition.clone(), - }) - .ok_or_else(|| anyhow!("knower does not hold the proposition"))?; - value.concealed_from.extend(recipients.iter().cloned()); - value.version = version; - } - KnowledgeMutationOperation::Correct | KnowledgeMutationOperation::Invalidate => { - let knower = knower.ok_or_else(|| anyhow!("knowledge change lacks a knower"))?; - let value = state - .knowledge - .get_mut(&KnowledgeKey { - knower: knower.clone(), - proposition: proposition.clone(), - }) - .ok_or_else(|| anyhow!("knower does not hold the proposition"))?; - value.status = if matches!(operation, KnowledgeMutationOperation::Correct) { - "corrected" - } else { - "invalidated" - } - .into(); - value.version = version; - } - } - Ok(()) -} - -fn apply_memory_mutation( - state: &mut ComponentWorldState, - subject: &SubjectRef, - operation: &MemoryMutationOperation, - memory_id: &str, - event_id: Option<&str>, - summary: Option<&str>, -) -> Result<()> { - active_subject(state, subject)?; - let key = SubjectEntryKey { - subject: subject.clone(), - entry_id: memory_id.into(), - }; - let version = next_component_version(state); - match operation { - MemoryMutationOperation::Record => { - if state.memories.contains_key(&key) { - return Err(anyhow!("memory already exists")); - } - state.memories.insert( - key, - MemoryComponentState { - event_id: event_id.map(str::to_owned), - summary: summary - .filter(|summary| !summary.trim().is_empty()) - .ok_or_else(|| anyhow!("memory record lacks a summary"))? - .into(), - version, - }, - ); - } - MemoryMutationOperation::Revise => { - let value = state - .memories - .get_mut(&key) - .ok_or_else(|| anyhow!("memory does not exist"))?; - value.summary = summary - .filter(|summary| !summary.trim().is_empty()) - .ok_or_else(|| anyhow!("memory revision lacks a summary"))? - .into(); - value.event_id = event_id.map(str::to_owned).or(value.event_id.clone()); - value.version = version; - } - MemoryMutationOperation::Retire => { - if state.memories.remove(&key).is_none() { - return Err(anyhow!("memory does not exist")); - } - } - } - Ok(()) -} - -fn apply_membership_mutation( - state: &mut ComponentWorldState, - actor: &SubjectRef, - operation: &PopulationMembershipOperation, - source_population: Option<&SubjectRef>, - destination_population: Option<&SubjectRef>, -) -> Result<()> { - active_subject(state, actor)?; - require_kind(actor, SubjectKind::Actor)?; - if let Some(population) = source_population { - active_subject(state, population)?; - require_kind(population, SubjectKind::Population)?; - } - if let Some(population) = destination_population { - active_subject(state, population)?; - require_kind(population, SubjectKind::Population)?; - } - let version = next_component_version(state); - let source_key = source_population.map(|population| MembershipKey { - actor: actor.clone(), - population: population.clone(), - }); - let destination_key = destination_population.map(|population| MembershipKey { - actor: actor.clone(), - population: population.clone(), - }); - match operation { - PopulationMembershipOperation::Join => { - let key = - destination_key.ok_or_else(|| anyhow!("population join lacks destination"))?; - if state - .memberships - .get(&key) - .is_some_and(|membership| membership.active) - { - return Err(anyhow!("actor already belongs to destination population")); - } - state.memberships.insert( - key, - PopulationMembershipState { - active: true, - version, - }, - ); - } - PopulationMembershipOperation::Leave => { - let key = source_key.ok_or_else(|| anyhow!("population leave lacks source"))?; - let value = state - .memberships - .get_mut(&key) - .filter(|membership| membership.active) - .ok_or_else(|| anyhow!("actor does not belong to source population"))?; - value.active = false; - value.version = version; - } - PopulationMembershipOperation::Transfer => { - let source = source_key.ok_or_else(|| anyhow!("population transfer lacks source"))?; - let destination = - destination_key.ok_or_else(|| anyhow!("population transfer lacks destination"))?; - if source == destination { - return Err(anyhow!( - "population transfer source and destination are identical" - )); - } - if state - .memberships - .get(&destination) - .is_some_and(|membership| membership.active) - { - return Err(anyhow!("actor already belongs to destination population")); - } - let source_value = state - .memberships - .get_mut(&source) - .filter(|membership| membership.active) - .ok_or_else(|| anyhow!("actor does not belong to source population"))?; - source_value.active = false; - source_value.version = version; - state.memberships.insert( - destination, - PopulationMembershipState { - active: true, - version, - }, - ); - } - } - Ok(()) -} - -fn apply_lineage_mutation( - state: &mut ComponentWorldState, - operation: &PopulationLineageOperation, - parents: &[SubjectRef], - children: &[SubjectRef], - remainder: Option<&SubjectRef>, -) -> Result<()> { - for population in parents.iter().chain(children).chain(remainder) { - active_subject(state, population)?; - require_kind(population, SubjectKind::Population)?; - } - let parent_set = parents.iter().cloned().collect::>(); - let child_set = children.iter().cloned().collect::>(); - if parent_set.len() != parents.len() - || child_set.len() != children.len() - || !parent_set.is_disjoint(&child_set) - { - return Err(anyhow!("population lineage repeats or overlaps subjects")); - } - match operation { - PopulationLineageOperation::Split => { - if parents.len() != 1 || children.is_empty() { - return Err(anyhow!("population split shape is invalid")); - } - let remainder = remainder.ok_or_else(|| anyhow!("population split lacks remainder"))?; - if !child_set.contains(remainder) { - return Err(anyhow!("population split remainder is not a child")); - } - inherit_population_baseline(state, &parents[0], children)?; - } - PopulationLineageOperation::Merge => { - if parents.len() < 2 || children.len() != 1 || remainder.is_some() { - return Err(anyhow!("population merge shape is invalid")); - } - } - } - let encoded = rmp_serde::to_vec_named(&(operation, parents, children, remainder))?; - let id = format!("lineage:{}", &sha256(&encoded)[7..23]); - if state.population_lineages.contains_key(&id) { - return Err(anyhow!("population lineage already exists")); - } - state.population_lineages.insert( - id.clone(), - PopulationLineageState { - id, - operation: operation.clone(), - parent_populations: parents.to_vec(), - child_populations: children.to_vec(), - remainder_population: remainder.cloned(), - version: next_component_version(state), - }, - ); - Ok(()) -} - -fn inherit_population_baseline( - state: &mut ComponentWorldState, - parent: &SubjectRef, - children: &[SubjectRef], -) -> Result<()> { - let version = next_component_version(state); - let capabilities = state - .capabilities - .iter() - .filter(|(key, _)| key.subject == *parent) - .map(|(key, value)| (key.entry_id.clone(), value.clone())) - .collect::>(); - let commitments = state - .commitments - .iter() - .filter(|(key, _)| key.subject == *parent) - .map(|(key, value)| (key.entry_id.clone(), value.clone())) - .collect::>(); - let knowledge = state - .knowledge - .iter() - .filter(|(key, _)| key.knower == *parent) - .map(|(key, value)| (key.proposition.clone(), value.clone())) - .collect::>(); - let pressures = state - .pressures - .iter() - .filter(|(_, value)| value.owner == *parent) - .map(|(subject, value)| (subject.clone(), value.clone())) - .collect::>(); - let relationships = state - .relationships - .iter() - .filter(|(_, value)| value.source == *parent || value.target == *parent) - .map(|(id, value)| (id.clone(), value.clone())) - .collect::>(); - - for child in children { - for (entry_id, mut value) in capabilities.clone() { - value.version = version; - state.capabilities.insert( - SubjectEntryKey { - subject: child.clone(), - entry_id, - }, - value, - ); - } - for (entry_id, mut value) in commitments.clone() { - value.version = version; - state.commitments.insert( - SubjectEntryKey { - subject: child.clone(), - entry_id, - }, - value, - ); - } - for (proposition, mut value) in knowledge.clone() { - value.version = version; - state.knowledge.insert( - KnowledgeKey { - knower: child.clone(), - proposition, - }, - value, - ); - } - for (_source_pressure, mut value) in pressures.clone() { - let pressure = SubjectRef { - kind: SubjectKind::Pressure, - id: format!("gestalt-pressure:{}:{}", child.id, short_hash(&value.label)), - }; - if state.subjects.contains_key(&pressure) || state.pressures.contains_key(&pressure) { - return Err(anyhow!("population split pressure identity collides")); - } - state.subjects.insert( - pressure.clone(), - TypedSubject { - schema: "ghostlight.typed_subject.v1".into(), - subject: pressure.clone(), - lifecycle: LifecycleStatus::Admitted, - admitted_components: BTreeSet::from([WorldComponentKind::Pressure]), - version, - }, - ); - value.pressure = pressure.clone(); - value.owner = child.clone(); - value.version = version; - state.pressures.insert(pressure, value); - } - for (source_id, mut value) in relationships.clone() { - let id = format!("{source_id}:fission:{}", child.id); - if state.relationships.contains_key(&id) { - return Err(anyhow!("population split relationship identity collides")); - } - if value.source == *parent { - value.source = child.clone(); - } - if value.target == *parent { - value.target = child.clone(); - } - value.version = version; - state.relationships.insert(id, value); - } - } - Ok(()) -} - -fn short_hash(value: &str) -> String { - format!("{:x}", Sha256::digest(value.as_bytes())) - .chars() - .take(16) - .collect() -} - -fn apply_identity_mutation( - state: &mut ComponentWorldState, - subject: &SubjectRef, - operation: &IdentityMutationOperation, - handle_id: &str, - handle_value: Option<&str>, - audience: &[SubjectRef], -) -> Result<()> { - active_subject(state, subject)?; - for observer in audience { - active_subject(state, observer)?; - } - let version = next_component_version(state); - match operation { - IdentityMutationOperation::Adopt => { - if state.identities.contains_key(handle_id) { - return Err(anyhow!("identity handle already exists")); - } - state.identities.insert( - handle_id.into(), - IdentityHandleState { - schema: "ghostlight.identity_handle.v1".into(), - id: handle_id.into(), - subject: subject.clone(), - value: handle_value - .filter(|value| !value.trim().is_empty()) - .ok_or_else(|| anyhow!("identity adoption lacks a handle value"))? - .into(), - active: true, - known_by: BTreeSet::from([subject.clone()]), - restricted_to: BTreeSet::new(), - source_revision: version, - }, - ); - } - IdentityMutationOperation::Disclose => { - let value = state - .identities - .get_mut(handle_id) - .filter(|handle| handle.active && handle.subject == *subject) - .ok_or_else(|| anyhow!("active identity handle does not exist for subject"))?; - if handle_value.is_some_and(|candidate| candidate != value.value) { - return Err(anyhow!( - "identity disclosure value does not match the handle" - )); - } - value.known_by.extend(audience.iter().cloned()); - value.source_revision = version; - } - IdentityMutationOperation::Restrict => { - let value = state - .identities - .get_mut(handle_id) - .filter(|handle| handle.active && handle.subject == *subject) - .ok_or_else(|| anyhow!("active identity handle does not exist for subject"))?; - value.restricted_to = audience.iter().cloned().collect(); - value.source_revision = version; - } - IdentityMutationOperation::Retire => { - let value = state - .identities - .get_mut(handle_id) - .filter(|handle| handle.active && handle.subject == *subject) - .ok_or_else(|| anyhow!("active identity handle does not exist for subject"))?; - value.active = false; - value.source_revision = version; - } - } - Ok(()) -} - -fn apply_topology_mutation( - state: &mut ComponentWorldState, - operation: &TopologyMutationOperation, - edge_id: &str, - from_place: &SubjectRef, - to_place: &SubjectRef, - distance: Option<&str>, - travel_minutes: Option, -) -> Result<()> { - active_subject(state, from_place)?; - active_subject(state, to_place)?; - require_kind(from_place, SubjectKind::Place)?; - require_kind(to_place, SubjectKind::Place)?; - if from_place == to_place { - return Err(anyhow!("topology edge cannot connect a place to itself")); - } - let version = next_component_version(state); - match operation { - TopologyMutationOperation::Add => { - if state.topology.contains_key(edge_id) { - return Err(anyhow!("topology edge already exists")); - } - let travel_minutes = travel_minutes - .filter(|minutes| *minutes > 0) - .ok_or_else(|| anyhow!("topology edge requires positive travel time"))?; - let distance = distance - .filter(|value| !value.trim().is_empty()) - .ok_or_else(|| anyhow!("topology edge requires a distance description"))?; - state.topology.insert( - edge_id.into(), - TopologyComponentState { - id: edge_id.into(), - from_place: from_place.clone(), - to_place: to_place.clone(), - distance: distance.into(), - travel_minutes, - open: true, - version, - }, - ); - } - TopologyMutationOperation::Alter => { - let value = state - .topology - .get_mut(edge_id) - .ok_or_else(|| anyhow!("topology edge does not exist"))?; - if value.from_place != *from_place || value.to_place != *to_place { - return Err(anyhow!("topology endpoints do not match")); - } - value.travel_minutes = travel_minutes - .filter(|minutes| *minutes > 0) - .ok_or_else(|| anyhow!("topology alteration requires positive travel time"))?; - value.distance = distance - .filter(|value| !value.trim().is_empty()) - .ok_or_else(|| anyhow!("topology alteration requires a distance description"))? - .into(); - value.version = version; - } - TopologyMutationOperation::Open | TopologyMutationOperation::Close => { - let value = state - .topology - .get_mut(edge_id) - .ok_or_else(|| anyhow!("topology edge does not exist"))?; - if value.from_place != *from_place || value.to_place != *to_place { - return Err(anyhow!("topology endpoints do not match")); - } - let next_open = matches!(operation, TopologyMutationOperation::Open); - if value.open == next_open { - return Err(anyhow!("topology operation is a no-op")); - } - value.open = next_open; - value.version = version; - } - TopologyMutationOperation::Retire => { - let value = state - .topology - .get(edge_id) - .ok_or_else(|| anyhow!("topology edge does not exist"))?; - if value.from_place != *from_place || value.to_place != *to_place { - return Err(anyhow!("topology endpoints do not match")); - } - state.topology.remove(edge_id); - } - } - Ok(()) -} - -fn retire_entity(state: &mut ComponentWorldState, subject: &SubjectRef) -> Result<()> { - active_subject(state, subject)?; - if state.occupancy.contains_key(subject) - || state.occupancy.values().any(|place| place == subject) - || state.custody.contains_key(subject) - || state.custody.values().any(|owner| owner == subject) - || state.memberships.iter().any(|(key, value)| { - value.active && (&key.actor == subject || &key.population == subject) - }) - || state - .topology - .values() - .any(|edge| &edge.from_place == subject || &edge.to_place == subject) - || state - .relationships - .values() - .any(|relationship| &relationship.source == subject || &relationship.target == subject) - || state.commitments.iter().any(|(key, commitment)| { - &key.subject == subject || commitment.counterparty.as_ref() == Some(subject) - }) - || state - .knowledge - .keys() - .any(|key| &key.knower == subject || &key.proposition == subject) - || state - .place_profiles - .values() - .any(|profile| profile.container.as_ref() == Some(subject)) - || state - .propositions - .values() - .any(|proposition| proposition.discoverable_at_places.contains(subject)) - { - return Err(anyhow!( - "entity retirement would leave active component references" - )); - } - let version = next_component_version(state); - let record = state - .subjects - .get_mut(subject) - .expect("active subject was resolved"); - record.lifecycle = LifecycleStatus::Retired; - record.version = version; - state.place_profiles.remove(subject); - state.propositions.remove(subject); - state.civic_systems.remove(subject); - Ok(()) -} - -pub fn validate_component_world(state: &ComponentWorldState) -> Result<()> { - for (subject, record) in &state.subjects { - if &record.subject != subject || subject.id.trim().is_empty() { - return Err(anyhow!("typed subject identity is malformed")); - } - } - for (subject, place) in &state.occupancy { - active_subject(state, subject)?; - active_subject(state, place)?; - require_kind(place, SubjectKind::Place)?; - } - for (resource, custodian) in &state.custody { - active_subject(state, resource)?; - require_kind(resource, SubjectKind::Resource)?; - active_subject(state, custodian)?; - if !state.resources.contains_key(resource) { - return Err(anyhow!("custody references a missing resource component")); - } - } - for (resource, value) in &state.resources { - active_subject(state, resource)?; - require_kind(resource, SubjectKind::Resource)?; - if &value.resource != resource - || value.label.trim().is_empty() - || value.quantity <= 0 - || value.integrity < 0 - || value.integrity > 100 - || !state.custody.contains_key(resource) - { - return Err(anyhow!( - "resource component violates conservation or bounds" - )); - } - } - for key in state - .capabilities - .keys() - .chain(state.conditions.keys()) - .chain(state.commitments.keys()) - .chain(state.memories.keys()) - { - active_subject(state, &key.subject)?; - if key.entry_id.trim().is_empty() { - return Err(anyhow!("component entry id is empty")); - } - } - for relationship in state.relationships.values() { - active_subject(state, &relationship.source)?; - active_subject(state, &relationship.target)?; - } - for (pressure, value) in &state.pressures { - active_subject(state, pressure)?; - require_kind(pressure, SubjectKind::Pressure)?; - active_subject(state, &value.owner)?; - if &value.pressure != pressure - || value.progress < 0 - || value.progress > value.threshold - || value.threshold <= 0 - { - return Err(anyhow!("pressure component violates bounds")); - } - } - for (key, value) in &state.knowledge { - active_subject(state, &key.knower)?; - active_subject(state, &key.proposition)?; - require_kind(&key.proposition, SubjectKind::Proposition)?; - if let Some(source) = &value.source { - active_subject(state, source)?; - } - if let Some(channel) = &value.channel { - active_subject(state, channel)?; - require_kind(channel, SubjectKind::Channel)?; - } - for observer in &value.concealed_from { - active_subject(state, observer)?; - } - } - for subject in state.postures.keys() { - active_subject(state, subject)?; - } - for (key, value) in &state.memberships { - active_subject(state, &key.actor)?; - active_subject(state, &key.population)?; - require_kind(&key.actor, SubjectKind::Actor)?; - require_kind(&key.population, SubjectKind::Population)?; - if !value.active && value.version == 0 { - return Err(anyhow!("inactive membership lacks history")); - } - } - for lineage in state.population_lineages.values() { - for population in lineage - .parent_populations - .iter() - .chain(&lineage.child_populations) - .chain(lineage.remainder_population.as_ref()) - { - active_subject(state, population)?; - require_kind(population, SubjectKind::Population)?; - } - } - for handle in state.identities.values() { - active_subject(state, &handle.subject)?; - if handle.id.trim().is_empty() || handle.value.trim().is_empty() { - return Err(anyhow!("identity handle is malformed")); - } - for observer in handle.known_by.iter().chain(&handle.restricted_to) { - active_subject(state, observer)?; - } - } - for (place, profile) in &state.place_profiles { - let subject = active_subject(state, place)?; - require_kind(place, SubjectKind::Place)?; - if &profile.place != place - || profile.name.trim().is_empty() - || !subject - .admitted_components - .contains(&WorldComponentKind::PlaceProfile) - || profile - .persistent_features - .iter() - .any(|feature| feature.trim().is_empty()) - { - return Err(anyhow!("place profile is malformed")); - } - if let Some(container) = &profile.container { - active_subject(state, container)?; - require_kind(container, SubjectKind::Place)?; - if container == place { - return Err(anyhow!("place cannot contain itself")); - } - } - } - for (subject, record) in &state.subjects { - if matches!( - record.lifecycle, - LifecycleStatus::Admitted | LifecycleStatus::Active - ) && subject.kind == SubjectKind::Place - && !state.place_profiles.contains_key(subject) - { - return Err(anyhow!("active place lacks its canonical profile")); - } - } - for start in state.place_profiles.keys() { - let mut seen = BTreeSet::new(); - let mut cursor = Some(start); - while let Some(place) = cursor { - if !seen.insert(place.clone()) { - return Err(anyhow!("place containment contains a cycle")); - } - cursor = state - .place_profiles - .get(place) - .and_then(|profile| profile.container.as_ref()); - } - } - let mut proposition_statements = BTreeSet::new(); - for (proposition, value) in &state.propositions { - let subject = active_subject(state, proposition)?; - require_kind(proposition, SubjectKind::Proposition)?; - if &value.proposition != proposition - || value.statement.trim().is_empty() - || !proposition_statements.insert(value.statement.clone()) - || !subject - .admitted_components - .contains(&WorldComponentKind::PropositionContent) - || value - .evidence_receipt_ids - .iter() - .any(|receipt_id| receipt_id.trim().is_empty()) - { - return Err(anyhow!("proposition content is malformed")); - } - for place in &value.discoverable_at_places { - active_subject(state, place)?; - require_kind(place, SubjectKind::Place)?; - } - } - for (subject, record) in &state.subjects { - if matches!( - record.lifecycle, - LifecycleStatus::Admitted | LifecycleStatus::Active - ) && subject.kind == SubjectKind::Proposition - && !state.propositions.contains_key(subject) - { - return Err(anyhow!("active proposition lacks canonical content")); - } - } - for edge in state.topology.values() { - active_subject(state, &edge.from_place)?; - active_subject(state, &edge.to_place)?; - require_kind(&edge.from_place, SubjectKind::Place)?; - require_kind(&edge.to_place, SubjectKind::Place)?; - if edge.distance.trim().is_empty() - || edge.travel_minutes <= 0 - || edge.from_place == edge.to_place - { - return Err(anyhow!("topology edge is malformed")); - } - } - for (jurisdiction, system) in &state.civic_systems { - active_subject(state, jurisdiction)?; - require_kind(jurisdiction, SubjectKind::Place)?; - if system.schema != "ghostlight.civic_system_manifest.v1" - || system.jurisdiction_location_id != jurisdiction.id - || system.semantic_verification_receipt_id.trim().is_empty() - { - return Err(anyhow!("canonical civic system is malformed")); - } - for id in &system.governing_institution_ids { - active_subject( - state, - &SubjectRef { - kind: SubjectKind::Institution, - id: id.clone(), - }, - )?; - } - for id in &system.resident_population_ids { - active_subject( - state, - &SubjectRef { - kind: SubjectKind::Population, - id: id.clone(), - }, - )?; - } - for id in system - .public_authority_fact_ids - .iter() - .chain(system.public_selection_fact_ids.iter()) - .chain(system.public_resource_fact_ids.iter()) - .chain(system.public_redress_fact_ids.iter()) - { - active_subject( - state, - &SubjectRef { - kind: SubjectKind::Proposition, - id: id.clone(), - }, - )?; - } - for resident_id in &system.resident_population_ids { - for proposition_id in system - .public_authority_fact_ids - .iter() - .chain(system.public_selection_fact_ids.iter()) - .chain(system.public_resource_fact_ids.iter()) - .chain(system.public_redress_fact_ids.iter()) - { - let key = KnowledgeKey { - knower: SubjectRef { - kind: SubjectKind::Population, - id: resident_id.clone(), - }, - proposition: SubjectRef { - kind: SubjectKind::Proposition, - id: proposition_id.clone(), - }, - }; - if !state - .knowledge - .get(&key) - .is_some_and(|knowledge| knowledge.status == "known") - { - return Err(anyhow!( - "canonical civic resident lost a public proposition" - )); - } - } - } - if system - .political_relation_ids - .iter() - .any(|id| !state.relationships.contains_key(id)) - { - return Err(anyhow!("canonical civic system lost a political relation")); - } - } - Ok(()) -} - -fn mutation_component_refs( - mutation: &WorldMutation, -) -> Vec<(SubjectRef, WorldComponentKind, Option)> { - use WorldComponentKind as Component; - use WorldMutation::*; - match mutation { - Relocate { subject, .. } => vec![(subject.clone(), Component::Occupancy, None)], - TransferCustody { resource, .. } => vec![(resource.clone(), Component::Custody, None)], - MutateResource { - resource, - related_resources, - .. - } => std::iter::once(resource) - .chain(related_resources) - .map(|resource| (resource.clone(), Component::ResourceState, None)) - .collect(), - ChangeCapability { - subject, - capability_id, - .. - } => vec![( - subject.clone(), - Component::Capability, - Some(capability_id.clone()), - )], - ChangeCondition { - subject, - condition_id, - .. - } => vec![( - subject.clone(), - Component::Condition, - Some(condition_id.clone()), - )], - ChangeCommitment { - subject, - commitment_id, - .. - } => vec![( - subject.clone(), - Component::Commitment, - Some(commitment_id.clone()), - )], - ChangeRelationship { - source, - relationship_id, - .. - } => vec![( - source.clone(), - Component::Relationship, - Some(relationship_id.clone()), - )], - ChangePressure { pressure, .. } => vec![(pressure.clone(), Component::Pressure, None)], - ChangeKnowledge { - proposition, - knower, - recipients, - .. - } => knower - .iter() - .chain(recipients) - .map(|subject| { - ( - subject.clone(), - Component::Knowledge, - Some(proposition.id.clone()), - ) - }) - .collect(), - ChangeMemory { - subject, memory_id, .. - } => vec![(subject.clone(), Component::Memory, Some(memory_id.clone()))], - ChangePosture { subject, .. } => vec![(subject.clone(), Component::Posture, None)], - ChangePopulationMembership { actor, .. } => { - vec![(actor.clone(), Component::PopulationMembership, None)] - } - ChangePopulationLineage { - parent_populations, - child_populations, - .. - } => parent_populations - .iter() - .chain(child_populations) - .map(|population| (population.clone(), Component::PopulationLineage, None)) - .collect(), - ChangeIdentity { - subject, handle_id, .. - } => vec![( - subject.clone(), - Component::Identity, - Some(handle_id.clone()), - )], - ChangeTopology { - from_place, - edge_id, - .. - } => vec![( - from_place.clone(), - Component::Topology, - Some(edge_id.clone()), - )], - SetCivicSystem { jurisdiction, .. } => { - vec![(jurisdiction.clone(), Component::CivicSystem, None)] - } - AdmitEntity { - subject, - initial_place, - initial_profile, - .. - } => { - let mut refs = vec![(subject.clone(), Component::Lifecycle, None)]; - if initial_place.is_some() { - refs.push((subject.clone(), Component::Occupancy, None)); - } - match initial_profile { - Some(AdmittedEntityProfile::Place { .. }) => { - refs.push((subject.clone(), Component::PlaceProfile, None)); - } - Some(AdmittedEntityProfile::Proposition { .. }) => { - refs.push((subject.clone(), Component::PropositionContent, None)); - } - None => {} - } - refs - } - RetireEntity { subject, .. } => vec![(subject.clone(), Component::Lifecycle, None)], - AdvanceWorldTime { campaign, .. } => vec![(campaign.clone(), Component::WorldTime, None)], - } -} - -pub fn validate_batch_structure( - envelope: &MutationAuthorityEnvelope, - batch: &WorldMutationBatch, - now: DateTime, -) -> Result<()> { - if envelope.schema != "ghostlight.mutation_authority_envelope.v1" - || batch.schema != "ghostlight.world_mutation_batch.v1" - { - return Err(anyhow!("mutation document uses an unsupported schema")); - } - if envelope.digest != envelope_digest(envelope)? { - return Err(anyhow!("mutation authority envelope digest is invalid")); - } - if batch.digest != mutation_batch_digest(batch)? { - return Err(anyhow!("world mutation batch digest is invalid")); - } - if envelope.campaign_id != batch.campaign_id - || envelope.world_revision != batch.expected_world_revision - || envelope.resolution_epoch != batch.expected_resolution_epoch - || envelope.digest != batch.authority_envelope_digest - { - return Err(anyhow!( - "world mutation batch is not bound to its authority snapshot" - )); - } - if envelope.expires_at < now { - return Err(anyhow!("mutation authority envelope is expired")); - } - if batch.id.trim().is_empty() || batch.source_receipt_id.trim().is_empty() { - return Err(anyhow!( - "world mutation batch lacks exact identity or source" - )); - } - - let permits = envelope - .permits - .iter() - .map(|permit| (permit.id.as_str(), permit)) - .collect::>(); - if permits.len() != envelope.permits.len() { - return Err(anyhow!("mutation authority envelope repeats a permit id")); - } - let mut uses = BTreeMap::<&str, u16>::new(); - for proposed in &batch.mutations { - let permit = permits - .get(proposed.permit_id.as_str()) - .ok_or_else(|| anyhow!("world mutation cites an unknown permit"))?; - let count = uses.entry(proposed.permit_id.as_str()).or_default(); - *count = count.saturating_add(1); - if *count > permit.maximum_uses { - return Err(anyhow!("world mutation exceeds permit use count")); - } - validate_permitted_mutation(permit, &proposed.mutation)?; - } - Ok(()) -} - -pub fn mutation_batch_json_schema( - envelope: &MutationAuthorityEnvelope, -) -> Result { - let mut schema = serde_json::to_value(schema_for!(WorldMutationBatch))?; - let variants = schema - .pointer("/$defs/WorldMutation/oneOf") - .and_then(serde_json::Value::as_array) - .cloned() - .ok_or_else(|| anyhow!("world mutation schema omitted tagged variants"))?; - let branches = envelope - .permits - .iter() - .map(|permit| permit_schema_branch(permit, &variants)) - .collect::>>()?; - let mutation_items = schema - .pointer_mut("/$defs/PermittedWorldMutation") - .ok_or_else(|| anyhow!("world mutation schema omitted permitted mutation definition"))?; - *mutation_items = serde_json::json!({"oneOf": branches}); - schema - .pointer_mut("/$defs") - .and_then(serde_json::Value::as_object_mut) - .expect("schemars emits an object definition table") - .remove("WorldMutation"); - Ok(schema) -} - -fn permit_schema_branch( - permit: &MutationPermit, - variants: &[serde_json::Value], -) -> Result { - if let Some(exact) = &permit.exact_mutation { - if exact.operation() != permit.operation { - return Err(anyhow!("exact mutation permit operation is inconsistent")); - } - return Ok(serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["permit_id","mutation"], - "properties":{ - "permit_id":{"const":permit.id}, - "mutation":{"const":exact} - } - })); - } - let (mutation_type, operation) = mutation_schema_tags(permit.operation); - let mut mutation = variants - .iter() - .find(|variant| { - variant - .pointer("/properties/type/const") - .and_then(serde_json::Value::as_str) - == Some(mutation_type) - }) - .cloned() - .ok_or_else(|| anyhow!("world mutation schema omitted {mutation_type}"))?; - if let Some(operation) = operation { - mutation["properties"]["operation"] = serde_json::json!({"const": operation}); - } - constrain_permit_schema(&mut mutation, permit)?; - Ok(serde_json::json!({ - "type":"object", - "additionalProperties":false, - "required":["permit_id","mutation"], - "properties":{ - "permit_id":{"const":permit.id}, - "mutation":mutation - } - })) -} - -#[derive(Clone, Copy)] -enum FieldShape { - Required, - Optional, - Array, -} - -fn constrain_permit_schema( - mutation: &mut serde_json::Value, - permit: &MutationPermit, -) -> Result<()> { - for (role, field, shape) in subject_schema_fields(permit.operation) { - let allowed = permit - .subject_bindings - .iter() - .find(|binding| binding.role == role) - .map(|binding| &binding.allowed_subjects); - constrain_subject_field(mutation, field, shape, allowed)?; - } - for (role, field, shape) in string_schema_fields(permit.operation) { - let constraint = permit.string_constraints.get(&role); - constrain_string_field(mutation, field, shape, constraint)?; - } - for (role, field, shape) in integer_schema_fields(permit.operation) { - let bounds = permit.integer_bounds.get(&role); - constrain_integer_field(mutation, field, shape, bounds)?; - } - Ok(()) -} - -fn constrain_subject_field( - mutation: &mut serde_json::Value, - field: &str, - shape: FieldShape, - allowed: Option<&BTreeSet>, -) -> Result<()> { - let target = mutation - .pointer_mut(&format!("/properties/{field}")) - .ok_or_else(|| anyhow!("mutation schema omitted subject field {field}"))?; - let values = allowed - .into_iter() - .flatten() - .map(serde_json::to_value) - .collect::, _>>()?; - *target = match shape { - FieldShape::Required if values.is_empty() => { - return Err(anyhow!("permit omitted required subject role for {field}")); - } - FieldShape::Required => serde_json::json!({"enum":values}), - FieldShape::Optional if values.is_empty() => serde_json::json!({"type":"null"}), - FieldShape::Optional => { - serde_json::json!({"anyOf":[{"enum":values},{"type":"null"}]}) - } - FieldShape::Array if values.is_empty() => { - serde_json::json!({"type":"array","maxItems":0}) - } - FieldShape::Array => serde_json::json!({ - "type":"array","items":{"enum":values},"uniqueItems":true - }), - }; - Ok(()) -} - -fn constrain_string_field( - mutation: &mut serde_json::Value, - field: &str, - shape: FieldShape, - constraint: Option<&StringConstraint>, -) -> Result<()> { - let target = mutation - .pointer_mut(&format!("/properties/{field}")) - .ok_or_else(|| anyhow!("mutation schema omitted string field {field}"))?; - let Some(constraint) = constraint else { - return match shape { - FieldShape::Required => Err(anyhow!("permit omitted required string role for {field}")), - FieldShape::Optional => { - *target = serde_json::json!({"type":"null"}); - Ok(()) - } - FieldShape::Array => Err(anyhow!("string arrays are not supported in permits")), - }; - }; - let mut string = serde_json::json!({ - "type":"string", - "minLength":constraint.minimum_length, - "maxLength":constraint.maximum_length - }); - if !constraint.allowed_values.is_empty() { - string["enum"] = serde_json::to_value(&constraint.allowed_values)?; - } - *target = match shape { - FieldShape::Required => string, - FieldShape::Optional => serde_json::json!({"anyOf":[string,{"type":"null"}]}), - FieldShape::Array => return Err(anyhow!("string arrays are not supported in permits")), - }; - Ok(()) -} - -fn constrain_integer_field( - mutation: &mut serde_json::Value, - field: &str, - shape: FieldShape, - bounds: Option<&IntegerBounds>, -) -> Result<()> { - let target = mutation - .pointer_mut(&format!("/properties/{field}")) - .ok_or_else(|| anyhow!("mutation schema omitted integer field {field}"))?; - let Some(bounds) = bounds else { - return match shape { - FieldShape::Required => { - Err(anyhow!("permit omitted required integer role for {field}")) - } - FieldShape::Optional => { - *target = serde_json::json!({"type":"null"}); - Ok(()) - } - FieldShape::Array => Err(anyhow!("integer arrays are not supported in permits")), - }; - }; - let integer = serde_json::json!({ - "type":"integer","minimum":bounds.minimum,"maximum":bounds.maximum - }); - *target = match shape { - FieldShape::Required => integer, - FieldShape::Optional => serde_json::json!({"anyOf":[integer,{"type":"null"}]}), - FieldShape::Array => return Err(anyhow!("integer arrays are not supported in permits")), - }; - Ok(()) -} - -fn subject_schema_fields( - operation: WorldMutationOperation, -) -> Vec<(MutationSubjectRole, &'static str, FieldShape)> { - use FieldShape::{Array, Optional, Required}; - use MutationSubjectRole::*; - use WorldMutationOperation::*; - match operation { - Relocate => vec![ - (Subject, "subject", Required), - (OriginPlace, "from_place", Required), - (DestinationPlace, "to_place", Required), - ], - TransferCustody => vec![ - (Resource, "resource", Required), - (SourceCustodian, "from_custodian", Required), - (DestinationCustodian, "to_custodian", Required), - ], - ResourceCreate => vec![ - (Resource, "resource", Required), - (Owner, "custodian", Required), - (RelatedResource, "related_resources", Array), - ], - ResourceTransform | ResourceConsume | ResourceDamage | ResourceRepair | ResourceSplit - | ResourceCombine => vec![ - (Resource, "resource", Required), - (Owner, "custodian", Optional), - (RelatedResource, "related_resources", Array), - ], - CapabilityGrant | CapabilityAlter | CapabilitySuspend | CapabilityRetire - | ConditionApply | ConditionAlter | ConditionClear | MemoryRecord | MemoryRevise - | MemoryRetire | PostureChange => vec![(Subject, "subject", Required)], - CommitmentCreate | CommitmentAlter | CommitmentFulfill | CommitmentDefault - | CommitmentRetire => vec![ - (Subject, "subject", Required), - (Counterparty, "counterparty", Optional), - ], - RelationshipCreate | RelationshipAlter | RelationshipRetire => vec![ - (RelationshipSource, "source", Required), - (RelationshipTarget, "target", Required), - ], - PressureCreate | PressureAdvance | PressureReduce | PressureResolve | PressureRetire => { - vec![(Pressure, "pressure", Required), (Owner, "owner", Required)] - } - KnowledgeAcquire | KnowledgeConceal | KnowledgeCorrect | KnowledgeInvalidate => vec![ - (Proposition, "proposition", Required), - (Knower, "knower", Required), - (Speaker, "speaker", Optional), - (Recipient, "recipients", Array), - (Channel, "channel", Optional), - ], - KnowledgeCommunicate => vec![ - (Proposition, "proposition", Required), - (Knower, "knower", Optional), - (Speaker, "speaker", Required), - (Recipient, "recipients", Array), - (Channel, "channel", Optional), - ], - PopulationJoin | PopulationLeave | PopulationTransfer => vec![ - (Actor, "actor", Required), - (SourcePopulation, "source_population", Optional), - (DestinationPopulation, "destination_population", Optional), - ], - PopulationSplit | PopulationMerge => vec![ - (ParentPopulation, "parent_populations", Array), - (ChildPopulation, "child_populations", Array), - (ChildPopulation, "remainder_population", Optional), - ], - IdentityAdopt | IdentityDisclose | IdentityRestrict | IdentityRetire => vec![ - (Subject, "subject", Required), - (Recipient, "audience", Array), - ], - TopologyAdd | TopologyAlter | TopologyOpen | TopologyClose | TopologyRetire => vec![ - (TopologyOrigin, "from_place", Required), - (TopologyDestination, "to_place", Required), - ], - CivicSystemSet => vec![(Subject, "jurisdiction", Required)], - AdmitEntity => vec![ - (Entity, "subject", Required), - (InitialPlace, "initial_place", Optional), - ], - RetireEntity => vec![(Entity, "subject", Required)], - AdvanceWorldTime => vec![(Subject, "campaign", Required)], - } -} - -fn string_schema_fields( - operation: WorldMutationOperation, -) -> Vec<(MutationStringRole, &'static str, FieldShape)> { - use FieldShape::{Optional, Required}; - use MutationStringRole::*; - use WorldMutationOperation::*; - match operation { - Relocate => vec![(RouteId, "route_id", Required)], - ResourceCreate => vec![ - (ResourceKind, "resource_kind", Required), - (ResourceLabel, "resource_label", Required), - (RecipeId, "recipe_id", Optional), - ], - ResourceTransform | ResourceSplit | ResourceCombine => vec![ - (ResourceKind, "resource_kind", Optional), - (ResourceLabel, "resource_label", Optional), - (RecipeId, "recipe_id", Required), - ], - ResourceConsume | ResourceDamage | ResourceRepair => vec![ - (ResourceKind, "resource_kind", Optional), - (ResourceLabel, "resource_label", Optional), - (RecipeId, "recipe_id", Optional), - ], - CapabilityGrant | CapabilityAlter | CapabilitySuspend | CapabilityRetire => vec![ - (CapabilityId, "capability_id", Required), - (Description, "description", Optional), - ], - ConditionApply | ConditionAlter | ConditionClear => vec![ - (ConditionId, "condition_id", Required), - (Description, "description", Optional), - ], - CommitmentCreate | CommitmentAlter | CommitmentFulfill | CommitmentDefault - | CommitmentRetire => vec![ - (CommitmentId, "commitment_id", Required), - (Description, "description", Optional), - ], - RelationshipCreate | RelationshipAlter | RelationshipRetire => vec![ - (RelationshipId, "relationship_id", Required), - (Description, "description", Optional), - ], - PressureCreate => vec![(PressureLabel, "label", Required)], - PressureAdvance | PressureReduce | PressureResolve | PressureRetire => { - vec![(PressureLabel, "label", Optional)] - } - MemoryRecord | MemoryRevise | MemoryRetire => vec![ - (MemoryId, "memory_id", Required), - (EventId, "event_id", Optional), - (Summary, "summary", Optional), - ], - PostureChange => vec![(Posture, "posture", Required)], - IdentityAdopt => vec![ - (IdentityHandleId, "handle_id", Required), - (IdentityHandleValue, "handle_value", Required), - ], - IdentityDisclose | IdentityRestrict | IdentityRetire => vec![ - (IdentityHandleId, "handle_id", Required), - (IdentityHandleValue, "handle_value", Optional), - ], - TopologyAdd | TopologyAlter => vec![ - (TopologyEdgeId, "edge_id", Required), - (Distance, "distance", Required), - ], - TopologyOpen | TopologyClose | TopologyRetire => vec![ - (TopologyEdgeId, "edge_id", Required), - (Distance, "distance", Optional), - ], - AdmitEntity => vec![(AdmissionReceiptId, "admission_receipt_id", Required)], - RetireEntity => vec![(RetirementReason, "reason", Required)], - TransferCustody | KnowledgeAcquire | KnowledgeCommunicate | KnowledgeConceal - | KnowledgeCorrect | KnowledgeInvalidate | PopulationJoin | PopulationLeave - | PopulationTransfer | PopulationSplit | PopulationMerge | CivicSystemSet - | AdvanceWorldTime => vec![], - } -} - -fn integer_schema_fields( - operation: WorldMutationOperation, -) -> Vec<(MutationIntegerRole, &'static str, FieldShape)> { - use FieldShape::{Optional, Required}; - use MutationIntegerRole::*; - use WorldMutationOperation::*; - match operation { - ResourceCreate | ResourceConsume | ResourceSplit => vec![ - (Quantity, "quantity", Required), - (Integrity, "integrity", Optional), - ], - ResourceDamage | ResourceRepair => vec![ - (Quantity, "quantity", Optional), - (Integrity, "integrity", Required), - ], - ResourceTransform | ResourceCombine => vec![ - (Quantity, "quantity", Optional), - (Integrity, "integrity", Optional), - ], - ConditionApply | ConditionAlter | ConditionClear => { - vec![(Severity, "severity", Optional)] - } - RelationshipCreate | RelationshipAlter => { - vec![(RelationshipStrengthDelta, "strength_delta", Optional)] - } - PressureAdvance | PressureReduce => vec![(PressureAmount, "amount", Required)], - PressureCreate | PressureResolve | PressureRetire => { - vec![(PressureAmount, "amount", Optional)] - } - TopologyAdd | TopologyAlter => vec![(TravelMinutes, "travel_minutes", Required)], - TopologyOpen | TopologyClose | TopologyRetire => { - vec![(TravelMinutes, "travel_minutes", Optional)] - } - AdvanceWorldTime => vec![(WorldMinutes, "minutes", Required)], - Relocate | TransferCustody | CapabilityGrant | CapabilityAlter | CapabilitySuspend - | CapabilityRetire | CommitmentCreate | CommitmentAlter | CommitmentFulfill - | CommitmentDefault | CommitmentRetire | RelationshipRetire | KnowledgeAcquire - | KnowledgeCommunicate | KnowledgeConceal | KnowledgeCorrect | KnowledgeInvalidate - | MemoryRecord | MemoryRevise | MemoryRetire | PostureChange | PopulationJoin - | PopulationLeave | PopulationTransfer | PopulationSplit | PopulationMerge - | IdentityAdopt | IdentityDisclose | IdentityRestrict | IdentityRetire | CivicSystemSet - | AdmitEntity | RetireEntity => vec![], - } -} - -fn mutation_schema_tags(operation: WorldMutationOperation) -> (&'static str, Option<&'static str>) { - use WorldMutationOperation::*; - match operation { - Relocate => ("relocate", None), - TransferCustody => ("transfer_custody", None), - ResourceCreate => ("mutate_resource", Some("create")), - ResourceTransform => ("mutate_resource", Some("transform")), - ResourceConsume => ("mutate_resource", Some("consume")), - ResourceDamage => ("mutate_resource", Some("damage")), - ResourceRepair => ("mutate_resource", Some("repair")), - ResourceSplit => ("mutate_resource", Some("split")), - ResourceCombine => ("mutate_resource", Some("combine")), - CapabilityGrant => ("change_capability", Some("grant")), - CapabilityAlter => ("change_capability", Some("alter")), - CapabilitySuspend => ("change_capability", Some("suspend")), - CapabilityRetire => ("change_capability", Some("retire")), - ConditionApply => ("change_condition", Some("apply")), - ConditionAlter => ("change_condition", Some("alter")), - ConditionClear => ("change_condition", Some("clear")), - CommitmentCreate => ("change_commitment", Some("create")), - CommitmentAlter => ("change_commitment", Some("alter")), - CommitmentFulfill => ("change_commitment", Some("fulfill")), - CommitmentDefault => ("change_commitment", Some("default")), - CommitmentRetire => ("change_commitment", Some("retire")), - RelationshipCreate => ("change_relationship", Some("create")), - RelationshipAlter => ("change_relationship", Some("alter")), - RelationshipRetire => ("change_relationship", Some("retire")), - PressureCreate => ("change_pressure", Some("create")), - PressureAdvance => ("change_pressure", Some("advance")), - PressureReduce => ("change_pressure", Some("reduce")), - PressureResolve => ("change_pressure", Some("resolve")), - PressureRetire => ("change_pressure", Some("retire")), - KnowledgeAcquire => ("change_knowledge", Some("acquire")), - KnowledgeCommunicate => ("change_knowledge", Some("communicate")), - KnowledgeConceal => ("change_knowledge", Some("conceal")), - KnowledgeCorrect => ("change_knowledge", Some("correct")), - KnowledgeInvalidate => ("change_knowledge", Some("invalidate")), - MemoryRecord => ("change_memory", Some("record")), - MemoryRevise => ("change_memory", Some("revise")), - MemoryRetire => ("change_memory", Some("retire")), - PostureChange => ("change_posture", None), - PopulationJoin => ("change_population_membership", Some("join")), - PopulationLeave => ("change_population_membership", Some("leave")), - PopulationTransfer => ("change_population_membership", Some("transfer")), - PopulationSplit => ("change_population_lineage", Some("split")), - PopulationMerge => ("change_population_lineage", Some("merge")), - IdentityAdopt => ("change_identity", Some("adopt")), - IdentityDisclose => ("change_identity", Some("disclose")), - IdentityRestrict => ("change_identity", Some("restrict")), - IdentityRetire => ("change_identity", Some("retire")), - TopologyAdd => ("change_topology", Some("add")), - TopologyAlter => ("change_topology", Some("alter")), - TopologyOpen => ("change_topology", Some("open")), - TopologyClose => ("change_topology", Some("close")), - TopologyRetire => ("change_topology", Some("retire")), - CivicSystemSet => ("set_civic_system", None), - AdmitEntity => ("admit_entity", None), - RetireEntity => ("retire_entity", None), - AdvanceWorldTime => ("advance_world_time", None), - } -} - -fn validate_permitted_mutation(permit: &MutationPermit, mutation: &WorldMutation) -> Result<()> { - if permit.operation == WorldMutationOperation::AdmitEntity && permit.exact_mutation.is_none() { - return Err(anyhow!( - "entity admission requires an exact typed mutation permit" - )); - } - if mutation.operation() != permit.operation { - return Err(anyhow!( - "world mutation operation does not match its permit" - )); - } - if let Some(exact) = &permit.exact_mutation - && exact != mutation - { - return Err(anyhow!( - "world mutation differs from the exact semantic mutation admitted by its permit" - )); - } - let roles = mutation.subject_roles(); - for binding in &permit.subject_bindings { - let actual = roles.get(&binding.role).cloned().unwrap_or_default(); - if actual.is_empty() || !actual.is_subset(&binding.allowed_subjects) { - return Err(anyhow!( - "world mutation exceeds the subjects allowed for role {:?}", - binding.role - )); - } - } - for (role, actual) in &roles { - if !permit - .subject_bindings - .iter() - .any(|binding| binding.role == *role && actual.is_subset(&binding.allowed_subjects)) - { - return Err(anyhow!( - "world mutation uses an unbound subject role {:?}", - role - )); - } - } - for (role, value) in mutation.string_roles() { - let constraint = permit.string_constraints.get(&role).ok_or_else(|| { - anyhow!( - "world mutation string for role {:?} has no permit constraint", - role - ) - })?; - let length = value.chars().count(); - if length < usize::from(constraint.minimum_length) - || length > usize::from(constraint.maximum_length) - || (!constraint.allowed_values.is_empty() - && !constraint.allowed_values.contains(&value)) - { - return Err(anyhow!( - "world mutation string for role {:?} is not permitted", - role - )); - } - } - for (role, value) in mutation.integer_roles() { - let bounds = permit.integer_bounds.get(&role).ok_or_else(|| { - anyhow!( - "world mutation integer for role {:?} has no permit bounds", - role - ) - })?; - if value < bounds.minimum || value > bounds.maximum { - return Err(anyhow!( - "world mutation integer for role {:?} is outside permit bounds", - role - )); - } - } - mutation.validate_local_shape() -} - -impl WorldMutation { - pub fn operation(&self) -> WorldMutationOperation { - use WorldMutation::*; - match self { - Relocate { .. } => WorldMutationOperation::Relocate, - TransferCustody { .. } => WorldMutationOperation::TransferCustody, - MutateResource { operation, .. } => match operation { - ResourceMutationOperation::Create => WorldMutationOperation::ResourceCreate, - ResourceMutationOperation::Transform => WorldMutationOperation::ResourceTransform, - ResourceMutationOperation::Consume => WorldMutationOperation::ResourceConsume, - ResourceMutationOperation::Damage => WorldMutationOperation::ResourceDamage, - ResourceMutationOperation::Repair => WorldMutationOperation::ResourceRepair, - ResourceMutationOperation::Split => WorldMutationOperation::ResourceSplit, - ResourceMutationOperation::Combine => WorldMutationOperation::ResourceCombine, - }, - ChangeCapability { operation, .. } => match operation { - CapabilityMutationOperation::Grant => WorldMutationOperation::CapabilityGrant, - CapabilityMutationOperation::Alter => WorldMutationOperation::CapabilityAlter, - CapabilityMutationOperation::Suspend => WorldMutationOperation::CapabilitySuspend, - CapabilityMutationOperation::Retire => WorldMutationOperation::CapabilityRetire, - }, - ChangeCondition { operation, .. } => match operation { - ConditionMutationOperation::Apply => WorldMutationOperation::ConditionApply, - ConditionMutationOperation::Alter => WorldMutationOperation::ConditionAlter, - ConditionMutationOperation::Clear => WorldMutationOperation::ConditionClear, - }, - ChangeCommitment { operation, .. } => match operation { - CommitmentMutationOperation::Create => WorldMutationOperation::CommitmentCreate, - CommitmentMutationOperation::Alter => WorldMutationOperation::CommitmentAlter, - CommitmentMutationOperation::Fulfill => WorldMutationOperation::CommitmentFulfill, - CommitmentMutationOperation::Default => WorldMutationOperation::CommitmentDefault, - CommitmentMutationOperation::Retire => WorldMutationOperation::CommitmentRetire, - }, - ChangeRelationship { operation, .. } => match operation { - RelationshipMutationOperation::Create => WorldMutationOperation::RelationshipCreate, - RelationshipMutationOperation::Alter => WorldMutationOperation::RelationshipAlter, - RelationshipMutationOperation::Retire => WorldMutationOperation::RelationshipRetire, - }, - ChangePressure { operation, .. } => match operation { - PressureMutationOperation::Create => WorldMutationOperation::PressureCreate, - PressureMutationOperation::Advance => WorldMutationOperation::PressureAdvance, - PressureMutationOperation::Reduce => WorldMutationOperation::PressureReduce, - PressureMutationOperation::Resolve => WorldMutationOperation::PressureResolve, - PressureMutationOperation::Retire => WorldMutationOperation::PressureRetire, - }, - ChangeKnowledge { operation, .. } => match operation { - KnowledgeMutationOperation::Acquire => WorldMutationOperation::KnowledgeAcquire, - KnowledgeMutationOperation::Communicate => { - WorldMutationOperation::KnowledgeCommunicate - } - KnowledgeMutationOperation::Conceal => WorldMutationOperation::KnowledgeConceal, - KnowledgeMutationOperation::Correct => WorldMutationOperation::KnowledgeCorrect, - KnowledgeMutationOperation::Invalidate => { - WorldMutationOperation::KnowledgeInvalidate - } - }, - ChangeMemory { operation, .. } => match operation { - MemoryMutationOperation::Record => WorldMutationOperation::MemoryRecord, - MemoryMutationOperation::Revise => WorldMutationOperation::MemoryRevise, - MemoryMutationOperation::Retire => WorldMutationOperation::MemoryRetire, - }, - ChangePosture { .. } => WorldMutationOperation::PostureChange, - ChangePopulationMembership { operation, .. } => match operation { - PopulationMembershipOperation::Join => WorldMutationOperation::PopulationJoin, - PopulationMembershipOperation::Leave => WorldMutationOperation::PopulationLeave, - PopulationMembershipOperation::Transfer => { - WorldMutationOperation::PopulationTransfer - } - }, - ChangePopulationLineage { operation, .. } => match operation { - PopulationLineageOperation::Split => WorldMutationOperation::PopulationSplit, - PopulationLineageOperation::Merge => WorldMutationOperation::PopulationMerge, - }, - ChangeIdentity { operation, .. } => match operation { - IdentityMutationOperation::Adopt => WorldMutationOperation::IdentityAdopt, - IdentityMutationOperation::Disclose => WorldMutationOperation::IdentityDisclose, - IdentityMutationOperation::Restrict => WorldMutationOperation::IdentityRestrict, - IdentityMutationOperation::Retire => WorldMutationOperation::IdentityRetire, - }, - ChangeTopology { operation, .. } => match operation { - TopologyMutationOperation::Add => WorldMutationOperation::TopologyAdd, - TopologyMutationOperation::Alter => WorldMutationOperation::TopologyAlter, - TopologyMutationOperation::Open => WorldMutationOperation::TopologyOpen, - TopologyMutationOperation::Close => WorldMutationOperation::TopologyClose, - TopologyMutationOperation::Retire => WorldMutationOperation::TopologyRetire, - }, - SetCivicSystem { .. } => WorldMutationOperation::CivicSystemSet, - AdmitEntity { .. } => WorldMutationOperation::AdmitEntity, - RetireEntity { .. } => WorldMutationOperation::RetireEntity, - AdvanceWorldTime { .. } => WorldMutationOperation::AdvanceWorldTime, - } - } - - fn subject_roles(&self) -> BTreeMap> { - let mut roles = BTreeMap::>::new(); - let mut add = |role, subject: &SubjectRef| { - roles.entry(role).or_default().insert(subject.clone()); - }; - use WorldMutation::*; - match self { - Relocate { - subject, - from_place, - to_place, - .. - } => { - add(MutationSubjectRole::Subject, subject); - add(MutationSubjectRole::OriginPlace, from_place); - add(MutationSubjectRole::DestinationPlace, to_place); - } - TransferCustody { - resource, - from_custodian, - to_custodian, - } => { - add(MutationSubjectRole::Resource, resource); - add(MutationSubjectRole::SourceCustodian, from_custodian); - add(MutationSubjectRole::DestinationCustodian, to_custodian); - } - MutateResource { - resource, - custodian, - related_resources, - .. - } => { - add(MutationSubjectRole::Resource, resource); - if let Some(custodian) = custodian { - add(MutationSubjectRole::Owner, custodian); - } - for related in related_resources { - add(MutationSubjectRole::RelatedResource, related); - } - } - ChangeCapability { subject, .. } - | ChangeCondition { subject, .. } - | ChangeMemory { subject, .. } - | ChangePosture { subject, .. } => add(MutationSubjectRole::Subject, subject), - ChangeCommitment { - subject, - counterparty, - .. - } => { - add(MutationSubjectRole::Subject, subject); - if let Some(counterparty) = counterparty { - add(MutationSubjectRole::Counterparty, counterparty); - } - } - ChangeRelationship { source, target, .. } => { - add(MutationSubjectRole::RelationshipSource, source); - add(MutationSubjectRole::RelationshipTarget, target); - } - ChangePressure { - pressure, owner, .. - } => { - add(MutationSubjectRole::Pressure, pressure); - add(MutationSubjectRole::Owner, owner); - } - ChangeKnowledge { - proposition, - knower, - speaker, - recipients, - channel, - .. - } => { - add(MutationSubjectRole::Proposition, proposition); - if let Some(knower) = knower { - add(MutationSubjectRole::Knower, knower); - } - if let Some(speaker) = speaker { - add(MutationSubjectRole::Speaker, speaker); - } - for recipient in recipients { - add(MutationSubjectRole::Recipient, recipient); - } - if let Some(channel) = channel { - add(MutationSubjectRole::Channel, channel); - } - } - ChangePopulationMembership { - actor, - source_population, - destination_population, - .. - } => { - add(MutationSubjectRole::Actor, actor); - if let Some(population) = source_population { - add(MutationSubjectRole::SourcePopulation, population); - } - if let Some(population) = destination_population { - add(MutationSubjectRole::DestinationPopulation, population); - } - } - ChangePopulationLineage { - parent_populations, - child_populations, - remainder_population, - .. - } => { - for population in parent_populations { - add(MutationSubjectRole::ParentPopulation, population); - } - for population in child_populations { - add(MutationSubjectRole::ChildPopulation, population); - } - if let Some(population) = remainder_population { - add(MutationSubjectRole::ChildPopulation, population); - } - } - ChangeIdentity { - subject, audience, .. - } => { - add(MutationSubjectRole::Subject, subject); - for recipient in audience { - add(MutationSubjectRole::Recipient, recipient); - } - } - ChangeTopology { - from_place, - to_place, - .. - } => { - add(MutationSubjectRole::TopologyOrigin, from_place); - add(MutationSubjectRole::TopologyDestination, to_place); - } - SetCivicSystem { jurisdiction, .. } => add(MutationSubjectRole::Subject, jurisdiction), - AdmitEntity { - subject, - initial_place, - .. - } => { - add(MutationSubjectRole::Entity, subject); - if let Some(place) = initial_place { - add(MutationSubjectRole::InitialPlace, place); - } - } - RetireEntity { subject, .. } => add(MutationSubjectRole::Entity, subject), - AdvanceWorldTime { campaign, .. } => add(MutationSubjectRole::Subject, campaign), - } - roles - } - - fn string_roles(&self) -> Vec<(MutationStringRole, String)> { - use WorldMutation::*; - let mut values = Vec::new(); - match self { - Relocate { route_id, .. } => { - values.push((MutationStringRole::RouteId, route_id.clone())) - } - MutateResource { - resource_kind, - resource_label, - recipe_id, - .. - } => { - if let Some(value) = resource_kind { - values.push((MutationStringRole::ResourceKind, value.clone())); - } - if let Some(value) = resource_label { - values.push((MutationStringRole::ResourceLabel, value.clone())); - } - if let Some(value) = recipe_id { - values.push((MutationStringRole::RecipeId, value.clone())); - } - } - ChangeCapability { - capability_id, - description, - .. - } => { - values.push((MutationStringRole::CapabilityId, capability_id.clone())); - if let Some(value) = description { - values.push((MutationStringRole::Description, value.clone())); - } - } - ChangeCondition { - condition_id, - description, - .. - } => { - values.push((MutationStringRole::ConditionId, condition_id.clone())); - if let Some(value) = description { - values.push((MutationStringRole::Description, value.clone())); - } - } - ChangeCommitment { - commitment_id, - description, - .. - } => { - values.push((MutationStringRole::CommitmentId, commitment_id.clone())); - if let Some(value) = description { - values.push((MutationStringRole::Description, value.clone())); - } - } - ChangeRelationship { - relationship_id, - description, - .. - } => { - values.push((MutationStringRole::RelationshipId, relationship_id.clone())); - if let Some(value) = description { - values.push((MutationStringRole::Description, value.clone())); - } - } - ChangePressure { label, .. } => { - if let Some(value) = label { - values.push((MutationStringRole::PressureLabel, value.clone())); - } - } - ChangeMemory { - memory_id, - event_id, - summary, - .. - } => { - values.push((MutationStringRole::MemoryId, memory_id.clone())); - if let Some(value) = event_id { - values.push((MutationStringRole::EventId, value.clone())); - } - if let Some(value) = summary { - values.push((MutationStringRole::Summary, value.clone())); - } - } - ChangePosture { posture, .. } => { - values.push((MutationStringRole::Posture, posture.clone())) - } - ChangeIdentity { - handle_id, - handle_value, - .. - } => { - values.push((MutationStringRole::IdentityHandleId, handle_id.clone())); - if let Some(value) = handle_value { - values.push((MutationStringRole::IdentityHandleValue, value.clone())); - } - } - ChangeTopology { - edge_id, distance, .. - } => { - values.push((MutationStringRole::TopologyEdgeId, edge_id.clone())); - if let Some(value) = distance { - values.push((MutationStringRole::Distance, value.clone())); - } - } - AdmitEntity { - admission_receipt_id, - .. - } => values.push(( - MutationStringRole::AdmissionReceiptId, - admission_receipt_id.clone(), - )), - RetireEntity { reason, .. } => { - values.push((MutationStringRole::RetirementReason, reason.clone())) - } - TransferCustody { .. } - | ChangeKnowledge { .. } - | ChangePopulationMembership { .. } - | ChangePopulationLineage { .. } - | SetCivicSystem { .. } - | AdvanceWorldTime { .. } => {} - } - values - } - - fn integer_roles(&self) -> Vec<(MutationIntegerRole, i64)> { - use WorldMutation::*; - let mut values = Vec::new(); - match self { - MutateResource { - quantity, - integrity, - .. - } => { - if let Some(value) = quantity { - values.push((MutationIntegerRole::Quantity, *value)); - } - if let Some(value) = integrity { - values.push((MutationIntegerRole::Integrity, *value)); - } - } - ChangeCondition { severity, .. } => { - if let Some(value) = severity { - values.push((MutationIntegerRole::Severity, *value)); - } - } - ChangeRelationship { strength_delta, .. } => { - if let Some(value) = strength_delta { - values.push((MutationIntegerRole::RelationshipStrengthDelta, *value)); - } - } - ChangePressure { amount, .. } => { - if let Some(value) = amount { - values.push((MutationIntegerRole::PressureAmount, *value)); - } - } - ChangeTopology { travel_minutes, .. } => { - if let Some(value) = travel_minutes { - values.push((MutationIntegerRole::TravelMinutes, *value)); - } - } - AdvanceWorldTime { minutes, .. } => { - values.push((MutationIntegerRole::WorldMinutes, *minutes)); - } - Relocate { .. } - | TransferCustody { .. } - | ChangeCapability { .. } - | ChangeCommitment { .. } - | ChangeKnowledge { .. } - | ChangeMemory { .. } - | ChangePosture { .. } - | ChangePopulationMembership { .. } - | ChangePopulationLineage { .. } - | ChangeIdentity { .. } - | SetCivicSystem { .. } - | AdmitEntity { .. } - | RetireEntity { .. } => {} - } - values - } - - fn validate_local_shape(&self) -> Result<()> { - let nonempty = |label: &str, value: &str| -> Result<()> { - if value.trim().is_empty() { - Err(anyhow!("world mutation {label} is empty")) - } else { - Ok(()) - } - }; - for subject in self.subject_roles().values().flatten() { - nonempty("subject id", &subject.id)?; - } - use WorldMutation::*; - match self { - Relocate { route_id, .. } => nonempty("route id", route_id)?, - MutateResource { - operation, - custodian, - related_resources, - resource_label, - quantity, - integrity, - .. - } => match operation { - ResourceMutationOperation::Create - | ResourceMutationOperation::Consume - | ResourceMutationOperation::Split - if quantity.is_none() => - { - return Err(anyhow!("resource mutation requires an exact quantity")); - } - ResourceMutationOperation::Damage | ResourceMutationOperation::Repair - if integrity.is_none() => - { - return Err(anyhow!("resource mutation requires an integrity amount")); - } - ResourceMutationOperation::Transform - | ResourceMutationOperation::Split - | ResourceMutationOperation::Combine - if related_resources.is_empty() => - { - return Err(anyhow!("resource mutation requires related resources")); - } - ResourceMutationOperation::Create if custodian.is_none() => { - return Err(anyhow!("resource creation requires an exact custodian")); - } - ResourceMutationOperation::Create - if resource_label.as_deref().is_none_or(str::is_empty) => - { - return Err(anyhow!("resource creation requires an exact label")); - } - _ if custodian.is_none() => { - return Err(anyhow!( - "resource mutation requires exact custody authority" - )); - } - _ => {} - }, - ChangeCapability { capability_id, .. } => nonempty("capability id", capability_id)?, - ChangeCondition { condition_id, .. } => nonempty("condition id", condition_id)?, - ChangeCommitment { commitment_id, .. } => nonempty("commitment id", commitment_id)?, - ChangeRelationship { - operation, - relationship_id, - description, - strength_delta, - .. - } => { - nonempty("relationship id", relationship_id)?; - if matches!(operation, RelationshipMutationOperation::Create) - && description.as_deref().is_none_or(str::is_empty) - { - return Err(anyhow!("relationship creation requires a description")); - } - if matches!(operation, RelationshipMutationOperation::Alter) - && description.is_none() - && strength_delta.is_none() - { - return Err(anyhow!("relationship alteration is empty")); - } - } - ChangePressure { - operation, amount, .. - } if matches!( - operation, - PressureMutationOperation::Advance | PressureMutationOperation::Reduce - ) && amount.is_none() => - { - return Err(anyhow!("pressure change requires an exact amount")); - } - ChangeKnowledge { - operation, - knower, - speaker, - recipients, - .. - } => match operation { - KnowledgeMutationOperation::Acquire - | KnowledgeMutationOperation::Conceal - | KnowledgeMutationOperation::Correct - | KnowledgeMutationOperation::Invalidate - if knower.is_none() => - { - return Err(anyhow!("knowledge mutation requires an exact knower")); - } - KnowledgeMutationOperation::Communicate - if speaker.is_none() || recipients.is_empty() => - { - return Err(anyhow!( - "knowledge communication requires a speaker and exact recipients" - )); - } - _ => {} - }, - ChangeMemory { memory_id, .. } => nonempty("memory id", memory_id)?, - ChangePosture { posture, .. } => { - nonempty("posture", posture)?; - if posture.chars().count() > MAX_POSTURE_CHARS { - return Err(anyhow!("posture exceeds {MAX_POSTURE_CHARS} characters")); - } - } - ChangePopulationMembership { - operation, - source_population, - destination_population, - .. - } => match operation { - PopulationMembershipOperation::Join if destination_population.is_none() => { - return Err(anyhow!("population join requires a destination")); - } - PopulationMembershipOperation::Leave if source_population.is_none() => { - return Err(anyhow!("population leave requires a source")); - } - PopulationMembershipOperation::Transfer - if source_population.is_none() || destination_population.is_none() => - { - return Err(anyhow!( - "population transfer requires source and destination" - )); - } - _ => {} - }, - ChangePopulationLineage { - operation, - parent_populations, - child_populations, - remainder_population, - } => match operation { - PopulationLineageOperation::Split - if parent_populations.len() != 1 - || child_populations.is_empty() - || remainder_population.is_none() => - { - return Err(anyhow!( - "population split requires one parent, children, and a remainder" - )); - } - PopulationLineageOperation::Merge - if parent_populations.len() < 2 || child_populations.len() != 1 => - { - return Err(anyhow!( - "population merge requires multiple parents and one child" - )); - } - _ => {} - }, - ChangeIdentity { - operation, - handle_id, - handle_value, - audience, - .. - } => { - nonempty("identity handle id", handle_id)?; - if matches!(operation, IdentityMutationOperation::Adopt) - && handle_value.as_deref().is_none_or(str::is_empty) - { - return Err(anyhow!("identity adoption requires a handle value")); - } - if matches!( - operation, - IdentityMutationOperation::Disclose | IdentityMutationOperation::Restrict - ) && audience.is_empty() - { - return Err(anyhow!( - "identity disclosure change requires an exact audience" - )); - } - } - ChangeTopology { - operation, - edge_id, - distance, - travel_minutes, - .. - } => { - nonempty("topology edge id", edge_id)?; - if matches!( - operation, - TopologyMutationOperation::Add | TopologyMutationOperation::Alter - ) && (travel_minutes.is_none() - || distance - .as_deref() - .is_none_or(|value| value.trim().is_empty())) - { - return Err(anyhow!( - "topology creation or alteration requires distance and travel time" - )); - } - if !matches!( - operation, - TopologyMutationOperation::Add | TopologyMutationOperation::Alter - ) && distance.is_some() - { - return Err(anyhow!( - "topology open, close, or retire cannot rewrite distance" - )); - } - } - SetCivicSystem { - jurisdiction, - system, - } => { - require_kind(jurisdiction, SubjectKind::Place)?; - if system.schema != "ghostlight.civic_system_manifest.v1" - || system.jurisdiction_location_id != jurisdiction.id - || system.governing_institution_ids.is_empty() - || system.resident_population_ids.is_empty() - || system.public_authority_fact_ids.is_empty() - || system.public_selection_fact_ids.is_empty() - || system.public_resource_fact_ids.is_empty() - || system.public_redress_fact_ids.is_empty() - || system.political_relation_ids.is_empty() - { - return Err(anyhow!("civic system mutation is incomplete")); - } - nonempty( - "civic semantic verifier receipt", - &system.semantic_verification_receipt_id, - )?; - } - AdmitEntity { - subject, - initial_components, - initial_place, - initial_profile, - admission_receipt_id, - } => { - if initial_components.is_empty() { - return Err(anyhow!("entity admission requires initial components")); - } - if initial_components.contains(&WorldComponentKind::Occupancy) - != initial_place.is_some() - { - return Err(anyhow!( - "entity admission occupancy requires one exact initial place" - )); - } - if let Some(place) = initial_place { - require_kind(place, SubjectKind::Place)?; - } - match (subject.kind.clone(), initial_profile) { - ( - SubjectKind::Place, - Some(AdmittedEntityProfile::Place { - name, - container, - persistent_features, - }), - ) => { - if !initial_components.contains(&WorldComponentKind::PlaceProfile) - || !initial_components.contains(&WorldComponentKind::Topology) - || initial_place.is_some() - { - return Err(anyhow!( - "place admission requires place-profile and topology components without occupancy" - )); - } - nonempty("place name", name)?; - if let Some(container) = container { - require_kind(container, SubjectKind::Place)?; - nonempty("place container id", &container.id)?; - if container == subject { - return Err(anyhow!("place cannot contain itself")); - } - } - if persistent_features - .iter() - .any(|feature| feature.trim().is_empty()) - { - return Err(anyhow!("place profile contains an empty feature")); - } - } - ( - SubjectKind::Proposition, - Some(AdmittedEntityProfile::Proposition { - statement, - evidence_receipt_ids, - discoverable_at_places, - .. - }), - ) => { - if !initial_components.contains(&WorldComponentKind::PropositionContent) - || !initial_components.contains(&WorldComponentKind::Knowledge) - || initial_place.is_some() - { - return Err(anyhow!( - "proposition admission requires proposition-content and knowledge components without occupancy" - )); - } - nonempty("proposition statement", statement)?; - for receipt_id in evidence_receipt_ids { - nonempty("proposition evidence receipt id", receipt_id)?; - } - for place in discoverable_at_places { - require_kind(place, SubjectKind::Place)?; - nonempty("proposition discovery place id", &place.id)?; - } - } - (SubjectKind::Place, _) => { - return Err(anyhow!("place admission requires an exact place profile")); - } - (SubjectKind::Proposition, _) => { - return Err(anyhow!( - "proposition admission requires exact proposition content" - )); - } - (_, Some(_)) => { - return Err(anyhow!( - "entity admission profile does not match the subject kind" - )); - } - (_, None) - if initial_components.contains(&WorldComponentKind::PlaceProfile) - || initial_components - .contains(&WorldComponentKind::PropositionContent) => - { - return Err(anyhow!( - "non-place/proposition admission cannot claim definition components" - )); - } - (_, None) => {} - } - nonempty("admission receipt id", admission_receipt_id)?; - } - RetireEntity { reason, .. } => nonempty("retirement reason", reason)?, - AdvanceWorldTime { minutes, .. } if *minutes <= 0 => { - return Err(anyhow!("world time must advance by a positive duration")); - } - TransferCustody { .. } | ChangePressure { .. } | AdvanceWorldTime { .. } => {} - } - Ok(()) - } -} - -/// Compile a single-use permit that authorizes exactly one already-admitted -/// semantic mutation. This is the compatibility cut for legacy outcome -/// records: they may be lowered into the algebra, but they do not retain an -/// independent write policy. -pub fn exact_mutation_permit( - id: impl Into, - mutation: &WorldMutation, -) -> Result { - mutation.validate_local_shape()?; - let subject_bindings = mutation - .subject_roles() - .into_iter() - .map(|(role, allowed_subjects)| MutationSubjectBinding { - role, - allowed_subjects, - }) - .collect(); - let mut string_constraints = BTreeMap::new(); - for (role, value) in mutation.string_roles() { - let length = u16::try_from(value.chars().count()) - .map_err(|_| anyhow!("world mutation string exceeds permit capacity"))?; - let constraint = string_constraints - .entry(role) - .or_insert_with(|| StringConstraint { - allowed_values: BTreeSet::new(), - minimum_length: 1, - maximum_length: length.max(1), - }); - constraint.maximum_length = constraint.maximum_length.max(length); - constraint.allowed_values.insert(value); - } - let integer_bounds = mutation - .integer_roles() - .into_iter() - .map(|(role, value)| { - ( - role, - IntegerBounds { - minimum: value, - maximum: value, - }, - ) - }) - .collect(); - Ok(MutationPermit { - id: id.into(), - operation: mutation.operation(), - subject_bindings, - string_constraints, - integer_bounds, - exact_mutation: Some(mutation.clone()), - maximum_uses: 1, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use chrono::Duration; - - fn subject(kind: SubjectKind, id: &str) -> SubjectRef { - SubjectRef { - kind, - id: id.into(), - } - } - - fn exact(values: &[&str]) -> StringConstraint { - StringConstraint { - allowed_values: values.iter().map(|value| (*value).into()).collect(), - minimum_length: 1, - maximum_length: 240, - } - } - - fn relocate_permit() -> MutationPermit { - MutationPermit { - id: "permit:move-east".into(), - operation: WorldMutationOperation::Relocate, - subject_bindings: vec![ - MutationSubjectBinding { - role: MutationSubjectRole::Subject, - allowed_subjects: BTreeSet::from([subject(SubjectKind::Actor, "actor:ash")]), - }, - MutationSubjectBinding { - role: MutationSubjectRole::OriginPlace, - allowed_subjects: BTreeSet::from([subject(SubjectKind::Place, "place:camp")]), - }, - MutationSubjectBinding { - role: MutationSubjectRole::DestinationPlace, - allowed_subjects: BTreeSet::from([subject( - SubjectKind::Place, - "place:east-trail", - )]), - }, - ], - string_constraints: BTreeMap::from([( - MutationStringRole::RouteId, - exact(&["route:camp-east"]), - )]), - integer_bounds: BTreeMap::new(), - exact_mutation: None, - maximum_uses: 1, - } - } - - fn envelope() -> MutationAuthorityEnvelope { - let mut envelope = MutationAuthorityEnvelope { - schema: "ghostlight.mutation_authority_envelope.v1".into(), - id: "authority:move-east".into(), - campaign_id: Uuid::nil(), - world_revision: 40, - resolution_epoch: None, - procedure: MutationProcedure::ForegroundAttempt, - source_subject: Some(subject(SubjectKind::Actor, "actor:ash")), - outcome: MutationOutcomeBinding::Foreground(OutcomeBand::Success), - effect_ceiling: "Ash may reach the eastern trail; no other subject moves.".into(), - permits: vec![relocate_permit()], - authority_receipt_ids: BTreeSet::from(["assessment:move-east".into()]), - expires_at: Utc::now() + Duration::minutes(5), - digest: String::new(), - }; - envelope.digest = envelope_digest(&envelope).unwrap(); - envelope - } - - fn valid_batch(envelope: &MutationAuthorityEnvelope) -> WorldMutationBatch { - let mut batch = WorldMutationBatch { - schema: "ghostlight.world_mutation_batch.v1".into(), - id: "batch:move-east".into(), - campaign_id: envelope.campaign_id, - expected_world_revision: envelope.world_revision, - expected_resolution_epoch: envelope.resolution_epoch, - authority_envelope_digest: envelope.digest.clone(), - source_receipt_id: "assessment:move-east".into(), - means_digest: Some("sha256:means".into()), - intended_effect_digest: Some("sha256:intent".into()), - mutations: vec![PermittedWorldMutation { - permit_id: "permit:move-east".into(), - mutation: WorldMutation::Relocate { - subject: subject(SubjectKind::Actor, "actor:ash"), - from_place: subject(SubjectKind::Place, "place:camp"), - to_place: subject(SubjectKind::Place, "place:east-trail"), - route_id: "route:camp-east".into(), - }, - }], - digest: String::new(), - }; - batch.digest = mutation_batch_digest(&batch).unwrap(); - batch - } - - #[test] - fn exact_permit_accepts_only_its_bound_transition() { - let envelope = envelope(); - let batch = valid_batch(&envelope); - validate_batch_structure(&envelope, &batch, Utc::now()).unwrap(); - - let mut stolen = batch.clone(); - let WorldMutation::Relocate { subject, .. } = &mut stolen.mutations[0].mutation else { - panic!("fixture mutation changed kind"); - }; - *subject = subject_ref(SubjectKind::Actor, "actor:sable"); - stolen.digest = mutation_batch_digest(&stolen).unwrap(); - assert!( - validate_batch_structure(&envelope, &stolen, Utc::now()) - .unwrap_err() - .to_string() - .contains("role Subject") - ); - } - - #[test] - fn exact_permit_binds_semantic_description_not_only_subject_and_operation() { - let mutation = WorldMutation::ChangeRelationship { - source: subject(SubjectKind::Actor, "actor:ash"), - target: subject(SubjectKind::Actor, "actor:sable"), - operation: RelationshipMutationOperation::Create, - relationship_id: "relationship:ash:sable".into(), - description: Some("Ash trusts Sable with the route.".into()), - strength_delta: None, - }; - let permit = exact_mutation_permit("permit:relationship", &mutation).unwrap(); - validate_permitted_mutation(&permit, &mutation).unwrap(); - - let mut rewritten = mutation; - let WorldMutation::ChangeRelationship { description, .. } = &mut rewritten else { - unreachable!(); - }; - *description = Some("Ash owes Sable absolute obedience.".into()); - assert!(validate_permitted_mutation(&permit, &rewritten).is_err()); - } - - #[test] - fn exact_admission_permit_binds_the_complete_place_profile() { - let mutation = WorldMutation::AdmitEntity { - subject: subject(SubjectKind::Place, "place:annex"), - initial_components: BTreeSet::from([ - WorldComponentKind::PlaceProfile, - WorldComponentKind::Topology, - ]), - initial_place: None, - initial_profile: Some(AdmittedEntityProfile::Place { - name: "Annex".into(), - container: Some(subject(SubjectKind::Place, "place:camp")), - persistent_features: BTreeSet::from(["sealed gate".into()]), - }), - admission_receipt_id: "region-expansion:test".into(), - }; - let permit = exact_mutation_permit("permit:annex", &mutation).unwrap(); - validate_permitted_mutation(&permit, &mutation).unwrap(); - let mut rewritten = mutation; - let WorldMutation::AdmitEntity { - initial_profile: Some(AdmittedEntityProfile::Place { name, .. }), - .. - } = &mut rewritten - else { - unreachable!(); - }; - *name = "Conveniently Adjacent Dream Annex".into(); - assert!(validate_permitted_mutation(&permit, &rewritten).is_err()); - } - - #[test] - fn stale_or_partially_invalid_batch_has_no_structural_admission() { - let envelope = envelope(); - let mut batch = valid_batch(&envelope); - batch.mutations.push(batch.mutations[0].clone()); - batch.digest = mutation_batch_digest(&batch).unwrap(); - assert!( - validate_batch_structure(&envelope, &batch, Utc::now()) - .unwrap_err() - .to_string() - .contains("use count") - ); - - let mut stale = valid_batch(&envelope); - stale.expected_world_revision += 1; - stale.digest = mutation_batch_digest(&stale).unwrap(); - assert!( - validate_batch_structure(&envelope, &stale, Utc::now()) - .unwrap_err() - .to_string() - .contains("authority snapshot") - ); - } - - #[test] - fn action_specific_schema_omits_unavailable_mutation_variants() { - let envelope = envelope(); - let schema = mutation_batch_json_schema(&envelope).unwrap(); - let rendered = serde_json::to_string(&schema).unwrap(); - assert!(rendered.contains("relocate")); - assert!(!rendered.contains("transfer_custody")); - assert!(!rendered.contains("change_identity")); - - let instance = serde_json::to_value(valid_batch(&envelope)).unwrap(); - assert!( - jsonschema::validator_for(&schema) - .unwrap() - .is_valid(&instance) - ); - - let mut stolen = valid_batch(&envelope); - let WorldMutation::Relocate { to_place, .. } = &mut stolen.mutations[0].mutation else { - unreachable!(); - }; - *to_place = subject(SubjectKind::Place, "place:unreachable"); - stolen.digest = mutation_batch_digest(&stolen).unwrap(); - let stolen = serde_json::to_value(stolen).unwrap(); - assert!( - !jsonschema::validator_for(&schema) - .unwrap() - .is_valid(&stolen) - ); - } - - #[test] - fn identity_disclosure_requires_exact_audience_authority() { - let sable = subject(SubjectKind::Actor, "actor:sable"); - let ash = subject(SubjectKind::Actor, "actor:ash"); - let stranger = subject(SubjectKind::Actor, "actor:stranger"); - let permit = MutationPermit { - id: "permit:sable-disclosure".into(), - operation: WorldMutationOperation::IdentityDisclose, - subject_bindings: vec![ - MutationSubjectBinding { - role: MutationSubjectRole::Subject, - allowed_subjects: BTreeSet::from([sable.clone()]), - }, - MutationSubjectBinding { - role: MutationSubjectRole::Recipient, - allowed_subjects: BTreeSet::from([ash.clone()]), - }, - ], - string_constraints: BTreeMap::from([ - ( - MutationStringRole::IdentityHandleId, - exact(&["identity:sable:given-handle"]), - ), - (MutationStringRole::IdentityHandleValue, exact(&["Sable"])), - ]), - integer_bounds: BTreeMap::new(), - exact_mutation: None, - maximum_uses: 1, - }; - let mutation = WorldMutation::ChangeIdentity { - subject: sable, - operation: IdentityMutationOperation::Disclose, - handle_id: "identity:sable:given-handle".into(), - handle_value: Some("Sable".into()), - audience: vec![ash], - }; - validate_permitted_mutation(&permit, &mutation).unwrap(); - - let mut leaked = mutation; - let WorldMutation::ChangeIdentity { audience, .. } = &mut leaked else { - unreachable!(); - }; - audience.push(stranger); - assert!(validate_permitted_mutation(&permit, &leaked).is_err()); - } - - fn component_world() -> ComponentWorldState { - let campaign = subject(SubjectKind::Campaign, "campaign:test"); - let ash = subject(SubjectKind::Actor, "actor:ash"); - let sable = subject(SubjectKind::Actor, "actor:sable"); - let rival = subject(SubjectKind::Actor, "actor:rival"); - let clinic = subject(SubjectKind::Institution, "institution:clinic"); - let camp = subject(SubjectKind::Place, "place:camp"); - let trail = subject(SubjectKind::Place, "place:trail"); - let refugees = subject(SubjectKind::Population, "population:refugees"); - let medicine = subject(SubjectKind::Resource, "resource:medicine-lot"); - let proposition = subject(SubjectKind::Proposition, "proposition:east-trail"); - let mut subjects = BTreeMap::new(); - for value in [ - campaign.clone(), - ash.clone(), - sable.clone(), - rival, - clinic, - camp.clone(), - trail, - refugees.clone(), - medicine.clone(), - proposition.clone(), - ] { - let admitted_components = match &value.kind { - SubjectKind::Place => BTreeSet::from([ - WorldComponentKind::PlaceProfile, - WorldComponentKind::Topology, - ]), - SubjectKind::Proposition => BTreeSet::from([ - WorldComponentKind::Knowledge, - WorldComponentKind::PropositionContent, - ]), - _ => BTreeSet::new(), - }; - subjects.insert( - value.clone(), - TypedSubject { - schema: "ghostlight.typed_subject.v1".into(), - subject: value, - lifecycle: LifecycleStatus::Active, - admitted_components, - version: 4, - }, - ); - } - ComponentWorldState { - schema: "ghostlight.component_world_state.v1".into(), - campaign_id: Uuid::nil(), - revision: 4, - resolution_epoch: 2, - world_time: Utc::now(), - subjects, - occupancy: BTreeMap::from([ - (ash.clone(), camp.clone()), - (sable.clone(), camp.clone()), - (campaign, camp.clone()), - ]), - custody: BTreeMap::from([(medicine.clone(), sable.clone())]), - resources: BTreeMap::from([( - medicine.clone(), - ResourceComponentState { - schema: "ghostlight.resource_component.v1".into(), - resource: medicine, - resource_kind: "medicine".into(), - label: "medicine lot".into(), - quantity: 10, - integrity: 100, - qualities: BTreeSet::new(), - version: 4, - }, - )]), - capabilities: BTreeMap::new(), - conditions: BTreeMap::new(), - commitments: BTreeMap::new(), - relationships: BTreeMap::new(), - pressures: BTreeMap::new(), - knowledge: BTreeMap::from([( - KnowledgeKey { - knower: sable, - proposition: proposition.clone(), - }, - KnowledgeComponentState { - status: "known".into(), - source: None, - channel: None, - concealed_from: BTreeSet::new(), - version: 4, - }, - )]), - memories: BTreeMap::new(), - postures: BTreeMap::new(), - memberships: BTreeMap::from([( - MembershipKey { - actor: ash, - population: refugees, - }, - PopulationMembershipState { - active: true, - version: 4, - }, - )]), - population_lineages: BTreeMap::new(), - identities: BTreeMap::new(), - place_profiles: BTreeMap::from([ - ( - camp.clone(), - PlaceComponentState { - place: camp.clone(), - name: "Camp".into(), - container: None, - persistent_features: BTreeSet::new(), - version: 4, - }, - ), - ( - subject(SubjectKind::Place, "place:trail"), - PlaceComponentState { - place: subject(SubjectKind::Place, "place:trail"), - name: "Trail".into(), - container: None, - persistent_features: BTreeSet::new(), - version: 4, - }, - ), - ]), - propositions: BTreeMap::from([( - proposition.clone(), - PropositionComponentState { - proposition, - statement: "The eastern trail exists.".into(), - scope: FactScope::CanonBaseline, - evidence_receipt_ids: BTreeSet::new(), - discoverable_at_places: BTreeSet::from([camp.clone()]), - version: 4, - }, - )]), - topology: BTreeMap::from([( - "route:camp-trail".into(), - TopologyComponentState { - id: "route:camp-trail".into(), - from_place: camp, - to_place: subject(SubjectKind::Place, "place:trail"), - distance: "near".into(), - travel_minutes: 30, - open: true, - version: 4, - }, - )]), - civic_systems: BTreeMap::new(), - } - } - - #[test] - fn public_civic_knowledge_is_a_continuing_component_invariant() { - let mut state = component_world(); - let jurisdiction = subject(SubjectKind::Place, "place:camp"); - let institution = subject(SubjectKind::Institution, "institution:clinic"); - let resident = subject(SubjectKind::Population, "population:refugees"); - let proposition = subject(SubjectKind::Proposition, "proposition:east-trail"); - state.relationships.insert( - "relation:clinic-refugees".into(), - RelationshipComponentState { - source: institution, - target: resident.clone(), - description: "administers the camp under public challenge".into(), - strength: Some(55), - version: state.revision, - }, - ); - let resident_knowledge = KnowledgeKey { - knower: resident, - proposition: proposition.clone(), - }; - state.knowledge.insert( - resident_knowledge.clone(), - KnowledgeComponentState { - status: "known".into(), - source: None, - channel: None, - concealed_from: BTreeSet::new(), - version: state.revision, - }, - ); - state.civic_systems.insert( - jurisdiction, - CivicSystemManifest { - schema: "ghostlight.civic_system_manifest.v1".into(), - version: 0, - jurisdiction_location_id: "place:camp".into(), - governing_institution_ids: BTreeSet::from(["institution:clinic".into()]), - resident_population_ids: BTreeSet::from(["population:refugees".into()]), - public_authority_fact_ids: BTreeSet::from(["proposition:east-trail".into()]), - public_selection_fact_ids: BTreeSet::from(["proposition:east-trail".into()]), - public_resource_fact_ids: BTreeSet::from(["proposition:east-trail".into()]), - public_redress_fact_ids: BTreeSet::from(["proposition:east-trail".into()]), - political_relation_ids: BTreeSet::from(["relation:clinic-refugees".into()]), - semantic_verification_receipt_id: "receipt:civic".into(), - }, - ); - validate_component_world(&state).unwrap(); - - state.knowledge.remove(&resident_knowledge); - let error = validate_component_world(&state).unwrap_err(); - assert!( - error - .to_string() - .contains("civic resident lost a public proposition"), - "{error}" - ); - } - - #[test] - fn posture_mutation_rejects_an_oversized_canonical_value() { - let mutation = WorldMutation::ChangePosture { - subject: subject(SubjectKind::Institution, "institution:clinic"), - posture: "x".repeat(MAX_POSTURE_CHARS + 1), - }; - - let error = mutation.validate_local_shape().unwrap_err(); - assert!(error.to_string().contains("exceeds 460 characters")); - } - - fn permit( - id: &str, - operation: WorldMutationOperation, - subjects: Vec<(MutationSubjectRole, BTreeSet)>, - strings: Vec<(MutationStringRole, StringConstraint)>, - integers: Vec<(MutationIntegerRole, IntegerBounds)>, - ) -> MutationPermit { - MutationPermit { - id: id.into(), - operation, - subject_bindings: subjects - .into_iter() - .map(|(role, allowed_subjects)| MutationSubjectBinding { - role, - allowed_subjects, - }) - .collect(), - string_constraints: strings.into_iter().collect(), - integer_bounds: integers.into_iter().collect(), - exact_mutation: None, - maximum_uses: 1, - } - } - - fn envelope_for( - state: &ComponentWorldState, - permits: Vec, - ) -> MutationAuthorityEnvelope { - let mut envelope = MutationAuthorityEnvelope { - schema: "ghostlight.mutation_authority_envelope.v1".into(), - id: "authority:component-test".into(), - campaign_id: state.campaign_id, - world_revision: state.revision, - resolution_epoch: Some(state.resolution_epoch), - procedure: MutationProcedure::StrategicOutcome, - source_subject: Some(subject(SubjectKind::Actor, "actor:sable")), - outcome: MutationOutcomeBinding::Strategic(StrategicOutcomeBand::Success), - effect_ceiling: "Only the exact permitted component transitions may commit.".into(), - permits, - authority_receipt_ids: BTreeSet::from(["outcome:test".into()]), - expires_at: Utc::now() + Duration::minutes(5), - digest: String::new(), - }; - envelope.digest = envelope_digest(&envelope).unwrap(); - envelope - } - - fn batch_for( - state: &ComponentWorldState, - envelope: &MutationAuthorityEnvelope, - mutations: Vec<(&str, WorldMutation)>, - ) -> WorldMutationBatch { - let mut batch = WorldMutationBatch { - schema: "ghostlight.world_mutation_batch.v1".into(), - id: format!("batch:{}", Uuid::new_v4().simple()), - campaign_id: state.campaign_id, - expected_world_revision: state.revision, - expected_resolution_epoch: Some(state.resolution_epoch), - authority_envelope_digest: envelope.digest.clone(), - source_receipt_id: "outcome:test".into(), - means_digest: Some("sha256:means".into()), - intended_effect_digest: Some("sha256:intent".into()), - mutations: mutations - .into_iter() - .map(|(permit_id, mutation)| PermittedWorldMutation { - permit_id: permit_id.into(), - mutation, - }) - .collect(), - digest: String::new(), - }; - batch.digest = mutation_batch_digest(&batch).unwrap(); - batch - } - - #[test] - fn component_batch_is_atomic_when_a_late_mutation_fails() { - let state = component_world(); - let medicine = subject(SubjectKind::Resource, "resource:medicine-lot"); - let sable = subject(SubjectKind::Actor, "actor:sable"); - let clinic = subject(SubjectKind::Institution, "institution:clinic"); - let camp = subject(SubjectKind::Place, "place:camp"); - let trail = subject(SubjectKind::Place, "place:trail"); - let permits = vec![ - permit( - "permit:transfer", - WorldMutationOperation::TransferCustody, - vec![ - ( - MutationSubjectRole::Resource, - BTreeSet::from([medicine.clone()]), - ), - ( - MutationSubjectRole::SourceCustodian, - BTreeSet::from([sable.clone()]), - ), - ( - MutationSubjectRole::DestinationCustodian, - BTreeSet::from([clinic.clone()]), - ), - ], - vec![], - vec![], - ), - permit( - "permit:move", - WorldMutationOperation::Relocate, - vec![ - ( - MutationSubjectRole::Subject, - BTreeSet::from([sable.clone()]), - ), - ( - MutationSubjectRole::OriginPlace, - BTreeSet::from([camp.clone()]), - ), - ( - MutationSubjectRole::DestinationPlace, - BTreeSet::from([trail.clone()]), - ), - ], - vec![(MutationStringRole::RouteId, exact(&["route:camp-trail"]))], - vec![], - ), - ]; - let envelope = envelope_for(&state, permits); - let batch = batch_for( - &state, - &envelope, - vec![ - ( - "permit:transfer", - WorldMutation::TransferCustody { - resource: medicine, - from_custodian: sable.clone(), - to_custodian: clinic, - }, - ), - ( - "permit:move", - WorldMutation::Relocate { - subject: sable, - from_place: camp, - to_place: trail, - route_id: "route:camp-trail".into(), - }, - ), - ], - ); - let mut invalid_state = state.clone(); - invalid_state - .occupancy - .remove(&subject(SubjectKind::Actor, "actor:sable")); - assert!( - apply_component_world_batch(&invalid_state, &envelope, &batch, Utc::now()).is_err() - ); - assert_eq!(invalid_state.custody, state.custody); - assert_eq!(invalid_state.revision, state.revision); - } - - #[test] - fn exact_relocation_permit_cannot_cross_a_closed_or_different_route() { - let state = component_world(); - let sable = subject(SubjectKind::Actor, "actor:sable"); - let camp = subject(SubjectKind::Place, "place:camp"); - let trail = subject(SubjectKind::Place, "place:trail"); - let permit = permit( - "permit:move", - WorldMutationOperation::Relocate, - vec![ - ( - MutationSubjectRole::Subject, - BTreeSet::from([sable.clone()]), - ), - ( - MutationSubjectRole::OriginPlace, - BTreeSet::from([camp.clone()]), - ), - ( - MutationSubjectRole::DestinationPlace, - BTreeSet::from([trail.clone()]), - ), - ], - vec![(MutationStringRole::RouteId, exact(&["route:camp-trail"]))], - vec![], - ); - let envelope = envelope_for(&state, vec![permit]); - let batch = batch_for( - &state, - &envelope, - vec![( - "permit:move", - WorldMutation::Relocate { - subject: sable.clone(), - from_place: camp.clone(), - to_place: trail.clone(), - route_id: "route:camp-trail".into(), - }, - )], - ); - - let mut closed = state.clone(); - closed.topology.get_mut("route:camp-trail").unwrap().open = false; - assert!(apply_component_world_batch(&closed, &envelope, &batch, Utc::now()).is_err()); - assert_eq!(closed.occupancy[&sable], camp); - assert_eq!(closed.revision, state.revision); - - let mut redirected = state.clone(); - redirected - .topology - .get_mut("route:camp-trail") - .unwrap() - .to_place = subject(SubjectKind::Place, "place:east-trail"); - assert!(apply_component_world_batch(&redirected, &envelope, &batch, Utc::now()).is_err()); - assert_eq!(redirected.occupancy[&sable], camp); - assert_eq!(redirected.revision, state.revision); - } - - #[test] - fn resource_split_and_transfer_conserve_quantity_and_exact_custody() { - let state = component_world(); - let source = subject(SubjectKind::Resource, "resource:medicine-lot"); - let child = subject(SubjectKind::Resource, "resource:medicine-dose"); - let sable = subject(SubjectKind::Actor, "actor:sable"); - let clinic = subject(SubjectKind::Institution, "institution:clinic"); - let permits = vec![ - permit( - "permit:split", - WorldMutationOperation::ResourceSplit, - vec![ - ( - MutationSubjectRole::Resource, - BTreeSet::from([source.clone()]), - ), - ( - MutationSubjectRole::RelatedResource, - BTreeSet::from([child.clone()]), - ), - (MutationSubjectRole::Owner, BTreeSet::from([sable.clone()])), - ], - vec![( - MutationStringRole::RecipeId, - exact(&["recipe:measure-dose"]), - )], - vec![( - MutationIntegerRole::Quantity, - IntegerBounds { - minimum: 1, - maximum: 4, - }, - )], - ), - permit( - "permit:transfer-dose", - WorldMutationOperation::TransferCustody, - vec![ - ( - MutationSubjectRole::Resource, - BTreeSet::from([child.clone()]), - ), - ( - MutationSubjectRole::SourceCustodian, - BTreeSet::from([sable.clone()]), - ), - ( - MutationSubjectRole::DestinationCustodian, - BTreeSet::from([clinic.clone()]), - ), - ], - vec![], - vec![], - ), - ]; - let envelope = envelope_for(&state, permits); - let batch = batch_for( - &state, - &envelope, - vec![ - ( - "permit:split", - WorldMutation::MutateResource { - resource: source.clone(), - operation: ResourceMutationOperation::Split, - custodian: Some(sable.clone()), - related_resources: vec![child.clone()], - resource_kind: None, - resource_label: None, - recipe_id: Some("recipe:measure-dose".into()), - quantity: Some(4), - integrity: None, - }, - ), - ( - "permit:transfer-dose", - WorldMutation::TransferCustody { - resource: child.clone(), - from_custodian: sable, - to_custodian: clinic.clone(), - }, - ), - ], - ); - let applied = apply_component_world_batch(&state, &envelope, &batch, Utc::now()).unwrap(); - assert_eq!(applied.state.resources[&source].quantity, 6); - assert_eq!(applied.state.resources[&child].quantity, 4); - assert_eq!(applied.state.custody[&child], clinic); - assert_eq!( - applied.state.resources[&source].quantity + applied.state.resources[&child].quantity, - 10 - ); - assert_eq!(applied.state.revision, 5); - } - - #[test] - fn communicated_knowledge_reaches_only_exact_recipients() { - let state = component_world(); - let sable = subject(SubjectKind::Actor, "actor:sable"); - let ash = subject(SubjectKind::Actor, "actor:ash"); - let rival = subject(SubjectKind::Actor, "actor:rival"); - let proposition = subject(SubjectKind::Proposition, "proposition:east-trail"); - let permit = permit( - "permit:tell-ash", - WorldMutationOperation::KnowledgeCommunicate, - vec![ - ( - MutationSubjectRole::Proposition, - BTreeSet::from([proposition.clone()]), - ), - ( - MutationSubjectRole::Speaker, - BTreeSet::from([sable.clone()]), - ), - ( - MutationSubjectRole::Recipient, - BTreeSet::from([ash.clone()]), - ), - ], - vec![], - vec![], - ); - let envelope = envelope_for(&state, vec![permit]); - let batch = batch_for( - &state, - &envelope, - vec![( - "permit:tell-ash", - WorldMutation::ChangeKnowledge { - operation: KnowledgeMutationOperation::Communicate, - proposition: proposition.clone(), - knower: None, - speaker: Some(sable), - recipients: vec![ash.clone()], - channel: None, - }, - )], - ); - let applied = apply_component_world_batch(&state, &envelope, &batch, Utc::now()).unwrap(); - assert!(applied.state.knowledge.contains_key(&KnowledgeKey { - knower: ash, - proposition: proposition.clone() - })); - assert!(!applied.state.knowledge.contains_key(&KnowledgeKey { - knower: rival, - proposition - })); - } - - #[test] - fn sable_identity_survives_population_and_occupancy_changes_without_global_disclosure() { - let mut state = component_world(); - let sable = subject(SubjectKind::Actor, "actor:sable"); - let ash = subject(SubjectKind::Actor, "actor:ash"); - let rival = subject(SubjectKind::Actor, "actor:rival"); - state.identities.insert( - "identity:sable:given-handle".into(), - IdentityHandleState { - schema: "ghostlight.identity_handle.v1".into(), - id: "identity:sable:given-handle".into(), - subject: sable.clone(), - value: "Sable".into(), - active: true, - known_by: BTreeSet::from([sable.clone()]), - restricted_to: BTreeSet::new(), - source_revision: 4, - }, - ); - let permit = permit( - "permit:disclose-sable", - WorldMutationOperation::IdentityDisclose, - vec![ - ( - MutationSubjectRole::Subject, - BTreeSet::from([sable.clone()]), - ), - ( - MutationSubjectRole::Recipient, - BTreeSet::from([ash.clone()]), - ), - ], - vec![( - MutationStringRole::IdentityHandleId, - exact(&["identity:sable:given-handle"]), - )], - vec![], - ); - let envelope = envelope_for(&state, vec![permit]); - let batch = batch_for( - &state, - &envelope, - vec![( - "permit:disclose-sable", - WorldMutation::ChangeIdentity { - subject: sable.clone(), - operation: IdentityMutationOperation::Disclose, - handle_id: "identity:sable:given-handle".into(), - handle_value: None, - audience: vec![ash.clone()], - }, - )], - ); - let applied = apply_component_world_batch(&state, &envelope, &batch, Utc::now()).unwrap(); - let handle = &applied.state.identities["identity:sable:given-handle"]; - assert!(handle.known_by.contains(&sable)); - assert!(handle.known_by.contains(&ash)); - assert!(!handle.known_by.contains(&rival)); - assert_eq!(handle.subject, sable); - } - - fn subject_ref(kind: SubjectKind, id: &str) -> SubjectRef { - subject(kind, id) - } -} diff --git a/crates/ghostlight-dungeon/src/turn.rs b/crates/ghostlight-dungeon/src/turn.rs deleted file mode 100644 index 9bc0cea..0000000 --- a/crates/ghostlight-dungeon/src/turn.rs +++ /dev/null @@ -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, -} - -/// 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, - model_name: &str, - campaign: &Campaign, - speaker_actor_id: &str, - speech: &str, -) -> Result<(SpeechAddressPlan, Vec)> { - 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::>(); - 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::>(); - 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::>() - .into_iter() - .rev() - .map(|turn| { - serde_json::json!({ - "speaker":turn.speaker, - "text":turn.text, - "persona_response_actor_ids":turn.persona_response_actor_ids, - }) - }) - .collect::>(); - 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, -} -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.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, - pub gestalt_reactions: Vec, - pub receipts: Vec, -} - -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 { - 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::>(); - 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::>(); - 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 { - 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::>(); - turns.reverse(); - turns -} - -fn reserved_public_identities( - campaign: &Campaign, - actor: &crate::domain::ActorState, -) -> BTreeSet { - 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::>(); - 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 { - 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 { - 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 { - 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.") - ); - } -} diff --git a/crates/ghostlight-dungeon/src/vault.rs b/crates/ghostlight-dungeon/src/vault.rs deleted file mode 100644 index 5acdc94..0000000 --- a/crates/ghostlight-dungeon/src/vault.rs +++ /dev/null @@ -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, - pub player_authority_lanes: Vec, -} - -pub fn bundled_vault_manifests() -> Vec { - 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, detail: impl Into) -> Self { - Self { - provider: provider.into(), - detail: detail.into(), - } - } -} - -pub fn is_vault_unavailable(error: &anyhow::Error) -> bool { - error - .chain() - .any(|cause| cause.downcast_ref::().is_some()) -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct VaultQuery { - pub query: String, - pub authority_lanes: Vec, - pub temporal_scope: String, - pub limit: u8, -} - -#[async_trait] -pub trait VaultProvider: Send + Sync { - async fn search(&self, query: &VaultQuery) -> Result; - async fn surrounding_context(&self, source_id: &str, chunk_index: u32) - -> Result; - async fn exact_document(&self, source_id: &str) -> Result; - fn provider_id(&self) -> &'static str; -} - -#[derive(Clone)] -pub struct FixtureVault { - pub witnesses: Vec, -} -#[async_trait] -impl VaultProvider for FixtureVault { - async fn search(&self, query: &VaultQuery) -> Result { - 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 { - 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 { - self.exact_document(source_id).await - } - fn provider_id(&self) -> &'static str { - "fixture" - } -} - -#[derive(Clone)] -pub struct VoidBotMcpVault { - client: Client, - endpoint: String, - manifests: BTreeMap, -} -impl VoidBotMcpVault { - pub fn new(endpoint: impl Into) -> 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 { - 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| 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| 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 { - 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::>>()?; - Ok(receipt(&manifest.provider_id, &effective_query, witnesses)) - } - async fn surrounding_context( - &self, - source_id: &str, - chunk_index: u32, - ) -> Result { - 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::>() - .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 { - 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 { - 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, -) -> 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, - } -} diff --git a/crates/ghostlight-dungeon/src/windows_secret.rs b/crates/ghostlight-dungeon/src/windows_secret.rs deleted file mode 100644 index 786997d..0000000 --- a/crates/ghostlight-dungeon/src/windows_secret.rs +++ /dev/null @@ -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) -> Result { - 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()); - } -} diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs new file mode 100644 index 0000000..c008778 --- /dev/null +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -0,0 +1,4672 @@ +//! The two cognition modes behind one exact world opportunity. +//! +//! This organ may ask models to think. It cannot mint authority: it reads one +//! `WorldMailbox` snapshot, binds one controller-owned opportunity, and submits +//! one typed exercise or decline through that same mailbox. The model-facing +//! tools never carry caller, controller, world, opportunity, revision, or +//! affordance fields. + +use crate::world::{ + AffordanceId, AffordanceKind, CommandId, CommitReceipt, ControllerMode, DecisionAction, + DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, SubjectId, SubjectSnapshot, + SubmitReceipt, WorldMailbox, WorldSnapshot, +}; +use async_trait::async_trait; +use chrono::Utc; +use codex_connector::{ + CodexConnectorClient, CodexConnectorClientError, CodexInputItem, CodexProviderRequest, + CodexRefusal, CodexToolChoice, CodexToolDefinition, CodexTransportDisposition, + CodexTransportEventPayload, CodexTransportInvocation, CodexTransportOutcome, + provider_request_sha256, +}; +use cultcache_legacy::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; +use ghostlight_persona_projection::{ + CaptureToolFeedback, InterpretationAccumulator, InterpretationFinalization, + InterpretationReport, InterpreterPrompt, OperationalAgentPrompt, PersonaPrompt, PersonaTurn, + PersonaTurnBinding, ProjectorPrompt, RecordGapToolCall, TranslationGapKind, + build_interpreter_prompt, build_operational_agent_prompt, build_persona_prompt, + build_projector_prompt, sha256, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeMap, + net::SocketAddr, + path::Path, + sync::{Arc, Mutex}, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; +use thiserror::Error; +use zeroize::Zeroizing; + +const MAX_CONNECTOR_FRAME_BYTES: usize = 1_052_672; +const REQUEST_EXPIRY: Duration = Duration::from_secs(300); +const TOOL_STEP_BUDGET: usize = 4; +const PERSONA_WORD_BUDGET: usize = 180; +const CONTROLLER_WORK_ROW: &str = "controller_work.v3"; +const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v3"; + +const SPEAK_TOOL: &str = "speak"; +const RECORD_GAP_TOOL: &str = "record_gap"; +const RECORD_NEED_TOOL: &str = "record_need"; +const FINISH_INTERPRETATION_TOOL: &str = "finish_interpretation"; +const FINISH_WITHOUT_PROPOSAL_TOOL: &str = "finish_without_proposal"; +const PERSONA_PROVIDER_INSTRUCTIONS: &str = + "Respond only in natural prose to the lived moment in the user message."; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) enum InferencePurpose { + Projector, + Persona, + Interpreter, + OperationalAgent, +} + +/// One exact provider request. Keeping the native request visible at this seam +/// makes the prose-only Persona boundary structurally inspectable. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct InferenceRequest { + purpose: InferencePurpose, + provider: CodexProviderRequest, +} + +/// The exact connector invocation, including expiry and native provenance. +/// Replaying this value may recover a completed connector response; rebuilding +/// it under the same request ID would be a replay conflict. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct PreparedInference { + purpose: InferencePurpose, + invocation: CodexTransportInvocation, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +enum InferenceEvent { + Text(String), + ToolCall { + call_id: String, + name: String, + arguments: String, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct InferenceOutput { + events: Vec, + receipt_digest: String, +} + +impl InferenceOutput { + fn prose_only(self, purpose: InferencePurpose) -> Result<(String, String), ControllerError> { + let mut prose = String::new(); + for event in self.events { + match event { + InferenceEvent::Text(text) => prose.push_str(&text), + InferenceEvent::ToolCall { .. } => { + return Err(ControllerError::ProviderContract { + purpose, + detail: "a prose-only request returned a tool call".into(), + }); + } + } + } + if self.receipt_digest.is_empty() || self.receipt_digest.trim() != self.receipt_digest { + return Err(ControllerError::ProviderContract { + purpose, + detail: "provider output has no receipt digest".into(), + }); + } + Ok((prose, self.receipt_digest)) + } +} + +#[derive(Clone, Debug, Error, PartialEq, Eq)] +#[error("{detail}")] +pub(crate) struct InferenceFault { + disposition: InferenceFaultDisposition, + detail: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum InferenceFaultDisposition { + Retryable, + RecoveryRequired, + IntegrityViolation, +} + +impl InferenceFault { + fn new(detail: impl Into) -> Self { + Self { + disposition: InferenceFaultDisposition::RecoveryRequired, + detail: detail.into(), + } + } + + fn retryable(detail: impl Into) -> Self { + Self { + disposition: InferenceFaultDisposition::Retryable, + detail: detail.into(), + } + } + + fn integrity_violation(detail: impl Into) -> Self { + Self { + disposition: InferenceFaultDisposition::IntegrityViolation, + detail: detail.into(), + } + } + + fn recovery_required(&self) -> bool { + self.disposition == InferenceFaultDisposition::RecoveryRequired + } + + fn integrity_was_violated(&self) -> bool { + self.disposition == InferenceFaultDisposition::IntegrityViolation + } +} + +#[async_trait] +trait InferencePort: Send + Sync { + fn prepare(&self, request: InferenceRequest) -> Result; + + async fn infer(&self, request: PreparedInference) -> Result; +} + +/// Production lowering to CodexConnector. There is deliberately no retry, +/// fallback model, output repair, or stage registry here; transport failure is +/// returned to the owning controller flow with its pending evidence intact. +#[derive(Clone)] +struct CodexConnectorInferencePort { + client: CodexConnectorClient, + caller_runtime_id: String, +} + +impl CodexConnectorInferencePort { + fn new( + endpoint: SocketAddr, + connection_key: String, + caller_runtime_id: impl Into, + ) -> Result { + let caller_runtime_id = caller_runtime_id.into(); + if caller_runtime_id.trim().is_empty() || caller_runtime_id.trim() != caller_runtime_id { + return Err(InferenceFault::new( + "CodexConnector caller runtime must be one exact nonempty identity", + )); + } + let client = CodexConnectorClient::new( + endpoint, + connection_key, + MAX_CONNECTOR_FRAME_BYTES, + Some(REQUEST_EXPIRY), + ) + .map_err(|error| InferenceFault::new(error.to_string()))?; + Ok(Self { + client, + caller_runtime_id, + }) + } + + fn from_secret_file( + endpoint: SocketAddr, + path: impl AsRef, + caller_runtime_id: impl Into, + ) -> Result { + let bytes = Zeroizing::new( + std::fs::read(path.as_ref()).map_err(|error| InferenceFault::new(error.to_string()))?, + ); + let raw = std::str::from_utf8(bytes.as_slice()) + .map_err(|error| InferenceFault::new(error.to_string()))?; + let key = raw.trim_end_matches(['\r', '\n']); + if key.is_empty() || key.len() != raw.trim().len() { + return Err(InferenceFault::new( + "CodexConnector key file is empty or has surrounding whitespace", + )); + } + Self::new(endpoint, key.to_owned(), caller_runtime_id) + } + + fn prepare_request( + &self, + request: InferenceRequest, + ) -> Result { + let request_bytes = + serde_json::to_vec(&request).map_err(|error| InferenceFault::new(error.to_string()))?; + let invocation = CodexTransportInvocation::new( + self.caller_runtime_id.clone(), + unix_ms()?.saturating_add(REQUEST_EXPIRY.as_millis() as u64), + Sha256::digest(request_bytes).into(), + request.provider, + ) + .map_err(|error| InferenceFault::new(error.to_string()))?; + Ok(PreparedInference { + purpose: request.purpose, + invocation, + }) + } + + fn execute(&self, request: PreparedInference) -> Result { + if request.invocation.caller_runtime_id != self.caller_runtime_id { + return Err(InferenceFault::integrity_violation( + "persisted inference caller does not match the configured runtime identity", + )); + } + let result = self + .client + .execute(&request.invocation) + .map_err(|error| match error { + CodexConnectorClientError::Connection(_) => { + InferenceFault::retryable(error.to_string()) + } + CodexConnectorClientError::InvalidConfig + | CodexConnectorClientError::FrameSize + | CodexConnectorClientError::Encoding + | CodexConnectorClientError::Transport(_) => { + InferenceFault::integrity_violation(error.to_string()) + } + })?; + let (events, receipt) = match result.disposition { + CodexTransportDisposition::Refused(reason) => { + let detail = format!("CodexConnector refused request: {reason:?}"); + return Err(match reason { + CodexRefusal::InFlight | CodexRefusal::Capacity => { + InferenceFault::retryable(detail) + } + CodexRefusal::Expired | CodexRefusal::Indeterminate => { + InferenceFault::new(detail) + } + CodexRefusal::IdentitySubstitution + | CodexRefusal::ProviderDigestSubstitution + | CodexRefusal::Policy + | CodexRefusal::ReplayConflict + | CodexRefusal::Malformed => InferenceFault::integrity_violation(detail), + }); + } + CodexTransportDisposition::Transported { events, receipt } => (events, receipt), + }; + if let CodexTransportOutcome::Failed { + failure_kind, + message, + } = &receipt.outcome + { + return Err(InferenceFault::new(format!( + "Codex provider failed ({failure_kind}): {message}" + ))); + } + let events = events + .into_iter() + .map(|event| match event.payload { + CodexTransportEventPayload::TextDelta { text } => InferenceEvent::Text(text), + CodexTransportEventPayload::ToolCall { + call_id, + name, + arguments, + } => InferenceEvent::ToolCall { + call_id, + name, + arguments, + }, + }) + .collect(); + let receipt_bytes = rmp_serde::to_vec_named(&receipt) + .map_err(|error| InferenceFault::new(error.to_string()))?; + Ok(InferenceOutput { + events, + receipt_digest: format!("sha256:{:x}", Sha256::digest(&receipt_bytes)), + }) + } +} + +#[async_trait] +impl InferencePort for CodexConnectorInferencePort { + fn prepare(&self, request: InferenceRequest) -> Result { + self.prepare_request(request) + } + + async fn infer(&self, request: PreparedInference) -> Result { + let port = self.clone(); + tokio::task::spawn_blocking(move || port.execute(request)) + .await + .map_err(|error| InferenceFault::new(error.to_string()))? + } +} + +fn unix_ms() -> Result { + let millis = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| InferenceFault::new(error.to_string()))? + .as_millis(); + u64::try_from(millis).map_err(|_| InferenceFault::new("system time exceeds u64 milliseconds")) +} + +/// One command has one durable tagged cognition checkpoint. Every in-flight +/// variant owns the exact connector invocation before transport; terminal +/// variants retain completed provider outputs so their capture is derived, +/// never separately persisted. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "mode", content = "checkpoint", rename_all = "snake_case")] +enum ControllerWork { + Narrative(NarrativeCheckpoint), + Operational(OperationalCheckpoint), +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "stage", rename_all = "snake_case")] +enum NarrativeCheckpoint { + Projector { + command_id: CommandId, + identity: String, + typed_view: String, + persona_model: String, + interpreter_model: String, + opportunity: DecisionOpportunity, + speak_affordance: AffordanceId, + invocation: PreparedInference, + }, + Persona { + command_id: CommandId, + identity: String, + typed_view: String, + interpreter_model: String, + opportunity: DecisionOpportunity, + speak_affordance: AffordanceId, + projector_output: InferenceOutput, + invocation: PreparedInference, + }, + InterpreterInFlight { + command_id: CommandId, + turn: PersonaTurn, + interpreter_prompt: String, + opportunity: DecisionOpportunity, + speak_affordance: AffordanceId, + completed: Vec, + invocation: PreparedInference, + }, + ReadyToSubmit { + command_id: CommandId, + turn: PersonaTurn, + interpreter_prompt: String, + opportunity: DecisionOpportunity, + speak_affordance: AffordanceId, + completed: Vec, + }, + NoProposal { + command_id: CommandId, + turn: PersonaTurn, + interpreter_prompt: String, + opportunity: DecisionOpportunity, + completed: Vec, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "stage", rename_all = "snake_case")] +enum OperationalCheckpoint { + AgentInFlight { + command_id: CommandId, + agent_prompt: String, + opportunity: DecisionOpportunity, + speak_affordance: AffordanceId, + completed: Vec, + invocation: PreparedInference, + }, + ReadyToSubmit { + command_id: CommandId, + agent_prompt: String, + opportunity: DecisionOpportunity, + speak_affordance: AffordanceId, + completed: Vec, + }, + NoProposal { + command_id: CommandId, + agent_prompt: String, + opportunity: DecisionOpportunity, + completed: Vec, + }, +} + +impl ControllerWork { + fn command_id(&self) -> CommandId { + match self { + Self::Narrative(checkpoint) => checkpoint.command_id(), + Self::Operational(checkpoint) => checkpoint.command_id(), + } + } + + fn mode(&self) -> ControllerMode { + match self { + Self::Narrative(_) => ControllerMode::NarrativePersona, + Self::Operational(_) => ControllerMode::OperationalAgent, + } + } + + fn is_initial(&self) -> bool { + match self { + Self::Narrative(NarrativeCheckpoint::Projector { .. }) => true, + Self::Operational(OperationalCheckpoint::AgentInFlight { completed, .. }) => { + completed.is_empty() + } + _ => false, + } + } + + fn integrity_is_valid(&self) -> bool { + match self { + Self::Narrative(checkpoint) => checkpoint.integrity_is_valid(), + Self::Operational(checkpoint) => checkpoint.integrity_is_valid(), + } + } +} + +impl NarrativeCheckpoint { + fn command_id(&self) -> CommandId { + match self { + Self::Projector { command_id, .. } + | Self::Persona { command_id, .. } + | Self::InterpreterInFlight { command_id, .. } + | Self::ReadyToSubmit { command_id, .. } + | Self::NoProposal { command_id, .. } => *command_id, + } + } + + fn opportunity(&self) -> &DecisionOpportunity { + match self { + Self::Projector { opportunity, .. } + | Self::Persona { opportunity, .. } + | Self::InterpreterInFlight { opportunity, .. } + | Self::ReadyToSubmit { opportunity, .. } + | Self::NoProposal { opportunity, .. } => opportunity, + } + } + + fn persona_prose(&self) -> Option<&str> { + match self { + Self::InterpreterInFlight { turn, .. } + | Self::ReadyToSubmit { turn, .. } + | Self::NoProposal { turn, .. } => Some(turn.source_prose()), + Self::Projector { .. } | Self::Persona { .. } => None, + } + } + + fn integrity_is_valid(&self) -> bool { + match self { + Self::Projector { + command_id, + identity, + typed_view, + persona_model, + interpreter_model, + opportunity, + speak_affordance, + invocation, + } => { + base_checkpoint_is_valid( + identity, + typed_view, + opportunity, + *speak_affordance, + ControllerMode::NarrativePersona, + ) && canonical_model(persona_model) + && canonical_model(interpreter_model) + && exact_request_identity( + invocation, + *command_id, + InferencePurpose::Projector, + 0, + ) + && prose_request_shape_is_valid(invocation) + } + Self::Persona { + command_id, + identity, + typed_view, + interpreter_model, + opportunity, + speak_affordance, + projector_output, + invocation, + } => { + let Ok((lived_stream, _)) = projector_output + .clone() + .prose_only(InferencePurpose::Projector) + else { + return false; + }; + let prompt = build_persona_prompt(&PersonaPrompt { + identity, + lived_stream: &lived_stream, + domain_guidance: "", + word_budget: PERSONA_WORD_BUDGET, + }); + base_checkpoint_is_valid( + identity, + typed_view, + opportunity, + *speak_affordance, + ControllerMode::NarrativePersona, + ) && canonical_model(interpreter_model) + && canonical_model(&invocation.invocation.request.model) + && persona_request(*command_id, &invocation.invocation.request.model, prompt) + .is_ok_and(|expected| { + prepared_matches_request(invocation, &expected, *command_id, 0) + }) + && persona_request_shape_is_valid(invocation) + } + Self::InterpreterInFlight { + command_id, + turn, + interpreter_prompt, + opportunity, + speak_affordance, + completed, + invocation, + } => { + turn_matches_opportunity(turn, opportunity) + && opportunity.controller_mode == ControllerMode::NarrativePersona + && opportunity.affordance_ids.contains(speak_affordance) + && !interpreter_prompt.is_empty() + && canonical_model(&invocation.invocation.request.model) + && match evaluate_interpreter_loop(turn, interpreter_prompt, completed) { + Ok(InterpreterLoopEvaluation::Continue { conversation }) => { + interpreter_request( + *command_id, + completed.len(), + &invocation.invocation.request.model, + conversation, + ) + .is_ok_and(|expected| { + prepared_matches_request( + invocation, + &expected, + *command_id, + completed.len(), + ) + }) + } + Ok(InterpreterLoopEvaluation::Complete { .. }) | Err(_) => false, + } + } + Self::ReadyToSubmit { + turn, + interpreter_prompt, + opportunity, + speak_affordance, + completed, + .. + } => { + turn_matches_opportunity(turn, opportunity) + && opportunity.controller_mode == ControllerMode::NarrativePersona + && opportunity.affordance_ids.contains(speak_affordance) + && derive_narrative_capture(turn, interpreter_prompt, completed) + .is_ok_and(|capture| capture.proposal.is_some()) + } + Self::NoProposal { + turn, + interpreter_prompt, + opportunity, + completed, + .. + } => { + turn_matches_opportunity(turn, opportunity) + && opportunity.controller_mode == ControllerMode::NarrativePersona + && derive_narrative_capture(turn, interpreter_prompt, completed) + .is_ok_and(|capture| capture.proposal.is_none()) + } + } + } +} + +impl OperationalCheckpoint { + fn command_id(&self) -> CommandId { + match self { + Self::AgentInFlight { command_id, .. } + | Self::ReadyToSubmit { command_id, .. } + | Self::NoProposal { command_id, .. } => *command_id, + } + } + + fn opportunity(&self) -> &DecisionOpportunity { + match self { + Self::AgentInFlight { opportunity, .. } + | Self::ReadyToSubmit { opportunity, .. } + | Self::NoProposal { opportunity, .. } => opportunity, + } + } + + fn integrity_is_valid(&self) -> bool { + match self { + Self::AgentInFlight { + command_id, + agent_prompt, + opportunity, + speak_affordance, + completed, + invocation, + } => { + opportunity.controller_mode == ControllerMode::OperationalAgent + && opportunity.affordance_ids.contains(speak_affordance) + && !agent_prompt.is_empty() + && canonical_model(&invocation.invocation.request.model) + && match evaluate_operational_loop(agent_prompt, completed) { + Ok(OperationalLoopEvaluation::Continue { conversation }) => { + operational_request( + *command_id, + completed.len(), + &invocation.invocation.request.model, + conversation, + ) + .is_ok_and(|expected| { + prepared_matches_request( + invocation, + &expected, + *command_id, + completed.len(), + ) + }) + } + Ok(OperationalLoopEvaluation::Complete { .. }) | Err(_) => false, + } + } + Self::ReadyToSubmit { + agent_prompt, + opportunity, + speak_affordance, + completed, + .. + } => { + opportunity.controller_mode == ControllerMode::OperationalAgent + && opportunity.affordance_ids.contains(speak_affordance) + && derive_operational_capture(agent_prompt, completed) + .is_ok_and(|capture| capture.proposal.is_some()) + } + Self::NoProposal { + agent_prompt, + opportunity, + completed, + .. + } => { + opportunity.controller_mode == ControllerMode::OperationalAgent + && derive_operational_capture(agent_prompt, completed) + .is_ok_and(|capture| capture.proposal.is_none()) + } + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct NarrativeCapture { + pub(crate) proposal: Option, + pub(crate) gaps: Vec, + pub(crate) finalization: InterpretationFinalization, + pub(crate) inference_receipts: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct SourceRange { + pub(crate) start_byte: usize, + pub(crate) end_byte: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct TranslationGapSummary { + pub(crate) kind: TranslationGapKind, + pub(crate) source: SourceRange, + pub(crate) detail: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct OperationalCapture { + pub(crate) proposal: Option, + pub(crate) needs: Vec, + pub(crate) inference_receipts: Vec, +} + +fn base_checkpoint_is_valid( + identity: &str, + typed_view: &str, + opportunity: &DecisionOpportunity, + speak_affordance: AffordanceId, + mode: ControllerMode, +) -> bool { + !identity.is_empty() + && identity.trim() == identity + && !typed_view.is_empty() + && opportunity.controller_mode == mode + && opportunity.affordance_ids.contains(&speak_affordance) +} + +fn turn_matches_opportunity(turn: &PersonaTurn, opportunity: &DecisionOpportunity) -> bool { + turn.receipt_is_valid() + && encoded_id(&opportunity.world_id) + .is_ok_and(|world_id| world_id == turn.binding().world_id) + && encoded_id(&opportunity.controller_id) + .is_ok_and(|controller_id| controller_id == turn.binding().controller_id) + && opportunity + .digest() + .is_ok_and(|digest| digest == turn.binding().opportunity_digest) + && opportunity.revision == turn.binding().world_revision + && opportunity.state_digest == turn.binding().state_digest +} + +fn derive_narrative_capture( + turn: &PersonaTurn, + interpreter_prompt: &str, + completed: &[InferenceOutput], +) -> Result { + match evaluate_interpreter_loop(turn, interpreter_prompt, completed)? { + InterpreterLoopEvaluation::Complete { capture } => Ok(capture), + InterpreterLoopEvaluation::Continue { .. } => Err(ControllerError::Serialization( + "terminal Interpreter checkpoint has unfinished evidence".into(), + )), + } +} + +fn derive_operational_capture( + agent_prompt: &str, + completed: &[InferenceOutput], +) -> Result { + match evaluate_operational_loop(agent_prompt, completed)? { + OperationalLoopEvaluation::Complete { capture } => Ok(capture), + OperationalLoopEvaluation::Continue { .. } => Err(ControllerError::Serialization( + "terminal operational checkpoint has unfinished evidence".into(), + )), + } +} + +fn canonical_model(model: &str) -> bool { + !model.is_empty() && model.chars().all(|character| !character.is_whitespace()) +} + +fn exact_request_identity( + request: &PreparedInference, + command_id: CommandId, + purpose: InferencePurpose, + round: usize, +) -> bool { + let provider = &request.invocation.request; + let native = InferenceRequest { + purpose: request.purpose, + provider: provider.clone(), + }; + request.purpose == purpose + && provider.validate().is_ok() + && !request.invocation.caller_runtime_id.is_empty() + && request.invocation.caller_runtime_id.trim() == request.invocation.caller_runtime_id + && request.invocation.expires_at_unix_ms > 0 + && serde_json::to_vec(&native) + .ok() + .map(|bytes| <[u8; 32]>::from(Sha256::digest(bytes))) + .is_some_and(|digest| digest == request.invocation.native_request_sha256) + && provider_request_sha256(provider) + .is_ok_and(|digest| digest == request.invocation.provider_request_sha256) + && provider_request_id(command_id, purpose, round) + .is_ok_and(|expected| provider.request_id == expected) + && conversation_id(command_id, purpose, round) + .is_ok_and(|expected| provider.conversation_id == expected) +} + +fn prepared_matches_request( + prepared: &PreparedInference, + expected: &InferenceRequest, + command_id: CommandId, + round: usize, +) -> bool { + prepared.invocation.request == expected.provider + && exact_request_identity(prepared, command_id, expected.purpose, round) +} + +fn prose_request_shape_is_valid(request: &PreparedInference) -> bool { + let provider = &request.invocation.request; + provider.input.len() == 1 + && matches!( + provider.input.first(), + Some(CodexInputItem::UserText { .. }) + ) + && provider.tools.is_empty() + && provider.tool_choice == CodexToolChoice::Auto + && !provider.parallel_tool_calls + && provider.output_format_name.is_none() + && provider.output_schema_json.is_none() + && provider.previous_response_id.is_none() +} + +fn persona_request_shape_is_valid(request: &PreparedInference) -> bool { + prose_request_shape_is_valid(request) + && request.invocation.request.instructions == PERSONA_PROVIDER_INSTRUCTIONS +} + +#[derive(Clone, Debug, Error, PartialEq, Eq)] +enum ControllerWorkStoreError { + #[error("Eve command ID already belongs to the other controller mode")] + CommandModeConflict, + #[error("{detail}")] + Fault { detail: String }, +} + +impl ControllerWorkStoreError { + fn new(detail: impl Into) -> Self { + Self::Fault { + detail: detail.into(), + } + } +} + +#[async_trait] +trait ControllerWorkStore: Send + Sync { + async fn lookup( + &self, + command_id: CommandId, + ) -> Result; + + /// Owns the only legal checkpoint transition for either cognition mode. + async fn persist( + &self, + work: &ControllerWork, + ) -> Result; + + /// Proves custody of the backing path without interpreting ordinary model + /// or world pending states as store failure. + async fn custody_probe(&self) -> Result; +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum ControllerWorkLookup { + Missing, + Confirmed(ControllerWork), + CustodyUncertain(ControllerWork), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ControllerWorkWrite { + Applied, + AlreadyPresent, + CustodyUncertain, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ControllerWorkCustody { + Owned { + narrative_commands: usize, + operational_commands: usize, + }, + /// A compare-and-swap or post-write ownership check did not confirm. The + /// process must reopen the journal before doing any other controller work. + Uncertain { + command_id: CommandId, + mode: ControllerMode, + }, +} + +struct ControllerWorkJournal { + store: OwnedRedbMessagePackBackingStore, + rows: Vec, + work: BTreeMap, + uncertain: Option, +} + +/// The one controller-work journal. It owns durable cognition evidence and +/// exact handoff progress for both modes, but never owns a world decision. +struct CultCacheControllerWorkStore { + journal: Mutex, +} + +impl CultCacheControllerWorkStore { + fn open(path: impl AsRef) -> Result { + let store = OwnedRedbMessagePackBackingStore::new(path.as_ref()) + .map_err(|error| ControllerWorkStoreError::new(error.to_string()))?; + store + .validate_path_identity() + .map_err(|error| ControllerWorkStoreError::new(error.to_string()))?; + let rows = store + .pull_all() + .map_err(|error| ControllerWorkStoreError::new(error.to_string()))?; + let mut work_by_command = BTreeMap::new(); + for row in &rows { + if row.r#type != CONTROLLER_WORK_ROW + || row.schema_id.as_deref() != Some(CONTROLLER_WORK_SCHEMA) + { + return Err(ControllerWorkStoreError::new(format!( + "unexpected row {}/{} in controller work store", + row.r#type, row.key + ))); + } + let work = decode_controller_work(row)?; + let command_id = work.command_id(); + let key = store_key(command_id)?; + if !work.integrity_is_valid() || row.key != key { + return Err(ControllerWorkStoreError::new(format!( + "controller work row {} failed its checkpoint binding", + row.key + ))); + } + if work_by_command.insert(command_id, work).is_some() { + return Err(ControllerWorkStoreError::new(format!( + "duplicate controller command row {}", + row.key + ))); + } + } + Ok(Self { + journal: Mutex::new(ControllerWorkJournal { + store, + rows, + work: work_by_command, + uncertain: None, + }), + }) + } +} + +fn decode_controller_work( + row: &CultCacheEnvelope, +) -> Result { + let value: ControllerWork = rmp_serde::from_slice(&row.payload) + .map_err(|error| ControllerWorkStoreError::new(error.to_string()))?; + let canonical = rmp_serde::to_vec_named(&value) + .map_err(|error| ControllerWorkStoreError::new(error.to_string()))?; + if canonical != row.payload { + return Err(ControllerWorkStoreError::new(format!( + "controller work row {} is not canonical", + row.key + ))); + } + Ok(value) +} + +#[async_trait] +impl ControllerWorkStore for CultCacheControllerWorkStore { + async fn lookup( + &self, + command_id: CommandId, + ) -> Result { + let journal = self.journal.lock().map_err(|_| { + ControllerWorkStoreError::new("controller work store lock was poisoned") + })?; + if let Some(uncertain) = &journal.uncertain { + return if uncertain.command_id() == command_id { + Ok(ControllerWorkLookup::CustodyUncertain(uncertain.clone())) + } else { + Err(ControllerWorkStoreError::new( + "controller work store ownership is uncertain; reopen before another command", + )) + }; + } + verify_journal_custody(&journal)?; + Ok(journal + .work + .get(&command_id) + .cloned() + .map(ControllerWorkLookup::Confirmed) + .unwrap_or(ControllerWorkLookup::Missing)) + } + + async fn persist( + &self, + work: &ControllerWork, + ) -> Result { + if !work.integrity_is_valid() { + return Err(ControllerWorkStoreError::new( + "refused controller work with an invalid checkpoint", + )); + } + let command_id = work.command_id(); + let key = store_key(command_id)?; + let mut journal = self.journal.lock().map_err(|_| { + ControllerWorkStoreError::new("controller work store lock was poisoned") + })?; + if let Some(uncertain) = &journal.uncertain { + return if uncertain == work { + Ok(ControllerWorkWrite::CustodyUncertain) + } else { + Err(ControllerWorkStoreError::new( + "controller work store ownership is uncertain; reopen before mutation", + )) + }; + } + verify_journal_custody(&journal)?; + if let Some(existing) = journal.work.get(&command_id) { + if existing == work { + return Ok(ControllerWorkWrite::AlreadyPresent); + } + if existing.mode() != work.mode() { + return Err(ControllerWorkStoreError::CommandModeConflict); + } + if !valid_controller_work_progression(existing, work) { + return Err(ControllerWorkStoreError::new(format!( + "controller command {key} attempted an illegal checkpoint transition" + ))); + } + } else if !work.is_initial() { + return Err(ControllerWorkStoreError::new(format!( + "controller command {key} did not begin before its provider boundary" + ))); + } + let row = CultCacheEnvelope { + key: key.clone(), + r#type: CONTROLLER_WORK_ROW.into(), + payload: rmp_serde::to_vec_named(work) + .map_err(|error| ControllerWorkStoreError::new(error.to_string()))?, + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(CONTROLLER_WORK_SCHEMA.into()), + }; + let mut next_rows = journal + .rows + .iter() + .filter(|existing| !(existing.r#type == CONTROLLER_WORK_ROW && existing.key == key)) + .cloned() + .collect::>(); + next_rows.push(row); + next_rows + .sort_by(|left, right| (&left.r#type, &left.key).cmp(&(&right.r#type, &right.key))); + if journal.store.validate_path_identity().is_err() { + journal.uncertain = Some(work.clone()); + return Ok(ControllerWorkWrite::CustodyUncertain); + } + let written = journal + .store + .replace_and_append_if_snapshot_unchanged(&journal.rows, next_rows.clone()); + if !matches!(written, Ok(true)) || journal.store.validate_path_identity().is_err() { + journal.uncertain = Some(work.clone()); + return Ok(ControllerWorkWrite::CustodyUncertain); + } + journal.rows = next_rows; + journal.work.insert(command_id, work.clone()); + Ok(ControllerWorkWrite::Applied) + } + + async fn custody_probe(&self) -> Result { + let journal = self.journal.lock().map_err(|_| { + ControllerWorkStoreError::new("controller work store lock was poisoned") + })?; + if let Some(uncertain) = &journal.uncertain { + return Ok(ControllerWorkCustody::Uncertain { + command_id: uncertain.command_id(), + mode: uncertain.mode(), + }); + } + verify_journal_custody(&journal)?; + Ok(ControllerWorkCustody::Owned { + narrative_commands: journal + .work + .values() + .filter(|work| work.mode() == ControllerMode::NarrativePersona) + .count(), + operational_commands: journal + .work + .values() + .filter(|work| work.mode() == ControllerMode::OperationalAgent) + .count(), + }) + } +} + +fn verify_journal_custody(journal: &ControllerWorkJournal) -> Result<(), ControllerWorkStoreError> { + journal + .store + .validate_path_identity() + .map_err(|error| ControllerWorkStoreError::new(error.to_string()))?; + let current_rows = journal + .store + .pull_all() + .map_err(|error| ControllerWorkStoreError::new(error.to_string()))?; + if current_rows != journal.rows { + return Err(ControllerWorkStoreError::new( + "controller work snapshot changed outside its owning store", + )); + } + Ok(()) +} + +fn valid_controller_work_progression(existing: &ControllerWork, next: &ControllerWork) -> bool { + if !existing.integrity_is_valid() || !next.integrity_is_valid() { + return false; + } + match (existing, next) { + (ControllerWork::Narrative(existing), ControllerWork::Narrative(next)) => { + valid_narrative_progression(existing, next) + } + (ControllerWork::Operational(existing), ControllerWork::Operational(next)) => { + valid_operational_progression(existing, next) + } + _ => false, + } +} + +fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeCheckpoint) -> bool { + match (existing, next) { + ( + NarrativeCheckpoint::Projector { + command_id, + identity, + typed_view, + persona_model, + interpreter_model, + opportunity, + speak_affordance, + invocation: existing_invocation, + }, + NarrativeCheckpoint::Persona { + command_id: next_command_id, + identity: next_identity, + typed_view: next_typed_view, + interpreter_model: next_interpreter_model, + opportunity: next_opportunity, + speak_affordance: next_speak_affordance, + invocation, + .. + }, + ) => { + command_id == next_command_id + && identity == next_identity + && typed_view == next_typed_view + && interpreter_model == next_interpreter_model + && opportunity == next_opportunity + && speak_affordance == next_speak_affordance + && &invocation.invocation.request.model == persona_model + && invocation.invocation.caller_runtime_id + == existing_invocation.invocation.caller_runtime_id + } + ( + NarrativeCheckpoint::Persona { + command_id, + identity, + typed_view, + interpreter_model, + opportunity, + speak_affordance, + projector_output, + invocation: existing_invocation, + }, + NarrativeCheckpoint::InterpreterInFlight { + command_id: next_command_id, + turn, + interpreter_prompt, + opportunity: next_opportunity, + speak_affordance: next_speak_affordance, + completed, + invocation, + }, + ) => { + let Ok((lived_stream, projector_receipt)) = projector_output + .clone() + .prose_only(InferencePurpose::Projector) + else { + return false; + }; + let expected_prompt = build_interpreter_prompt(&InterpreterPrompt { + identity, + typed_context: typed_view, + lived_stream: &lived_stream, + persona_output: turn.source_prose(), + output_schema: None, + domain_guidance: "", + }); + command_id == next_command_id + && opportunity == next_opportunity + && speak_affordance == next_speak_affordance + && completed.is_empty() + && interpreter_prompt == &expected_prompt + && turn.binding().projector_receipt_digest == projector_receipt + && &invocation.invocation.request.model == interpreter_model + && invocation.invocation.caller_runtime_id + == existing_invocation.invocation.caller_runtime_id + } + ( + NarrativeCheckpoint::InterpreterInFlight { + command_id, + turn, + interpreter_prompt, + opportunity, + speak_affordance, + completed, + invocation: existing_invocation, + }, + NarrativeCheckpoint::InterpreterInFlight { + command_id: next_command_id, + turn: next_turn, + interpreter_prompt: next_interpreter_prompt, + opportunity: next_opportunity, + speak_affordance: next_speak_affordance, + completed: next_completed, + invocation: next_invocation, + }, + ) => { + command_id == next_command_id + && turn == next_turn + && interpreter_prompt == next_interpreter_prompt + && opportunity == next_opportunity + && speak_affordance == next_speak_affordance + && completed_advances(completed, next_completed) + && existing_invocation.invocation.request.model + == next_invocation.invocation.request.model + && existing_invocation.invocation.caller_runtime_id + == next_invocation.invocation.caller_runtime_id + } + ( + NarrativeCheckpoint::InterpreterInFlight { + command_id, + turn, + interpreter_prompt, + opportunity, + speak_affordance, + completed, + .. + }, + NarrativeCheckpoint::ReadyToSubmit { + command_id: next_command_id, + turn: next_turn, + interpreter_prompt: next_interpreter_prompt, + opportunity: next_opportunity, + speak_affordance: next_speak_affordance, + completed: next_completed, + }, + ) => { + command_id == next_command_id + && turn == next_turn + && interpreter_prompt == next_interpreter_prompt + && opportunity == next_opportunity + && speak_affordance == next_speak_affordance + && completed_advances(completed, next_completed) + } + ( + NarrativeCheckpoint::InterpreterInFlight { + command_id, + turn, + interpreter_prompt, + opportunity, + completed, + .. + }, + NarrativeCheckpoint::NoProposal { + command_id: next_command_id, + turn: next_turn, + interpreter_prompt: next_interpreter_prompt, + opportunity: next_opportunity, + completed: next_completed, + }, + ) => { + command_id == next_command_id + && turn == next_turn + && interpreter_prompt == next_interpreter_prompt + && opportunity == next_opportunity + && completed_advances(completed, next_completed) + } + _ => false, + } +} + +fn valid_operational_progression( + existing: &OperationalCheckpoint, + next: &OperationalCheckpoint, +) -> bool { + match (existing, next) { + ( + OperationalCheckpoint::AgentInFlight { + command_id, + agent_prompt, + opportunity, + speak_affordance, + completed, + invocation: existing_invocation, + }, + OperationalCheckpoint::AgentInFlight { + command_id: next_command_id, + agent_prompt: next_agent_prompt, + opportunity: next_opportunity, + speak_affordance: next_speak_affordance, + completed: next_completed, + invocation: next_invocation, + }, + ) => { + command_id == next_command_id + && agent_prompt == next_agent_prompt + && opportunity == next_opportunity + && speak_affordance == next_speak_affordance + && completed_advances(completed, next_completed) + && existing_invocation.invocation.request.model + == next_invocation.invocation.request.model + && existing_invocation.invocation.caller_runtime_id + == next_invocation.invocation.caller_runtime_id + } + ( + OperationalCheckpoint::AgentInFlight { + command_id, + agent_prompt, + opportunity, + speak_affordance, + completed, + .. + }, + OperationalCheckpoint::ReadyToSubmit { + command_id: next_command_id, + agent_prompt: next_agent_prompt, + opportunity: next_opportunity, + speak_affordance: next_speak_affordance, + completed: next_completed, + }, + ) => { + command_id == next_command_id + && agent_prompt == next_agent_prompt + && opportunity == next_opportunity + && speak_affordance == next_speak_affordance + && completed_advances(completed, next_completed) + } + ( + OperationalCheckpoint::AgentInFlight { + command_id, + agent_prompt, + opportunity, + completed, + .. + }, + OperationalCheckpoint::NoProposal { + command_id: next_command_id, + agent_prompt: next_agent_prompt, + opportunity: next_opportunity, + completed: next_completed, + }, + ) => { + command_id == next_command_id + && agent_prompt == next_agent_prompt + && opportunity == next_opportunity + && completed_advances(completed, next_completed) + } + _ => false, + } +} + +fn completed_advances(existing: &[InferenceOutput], next: &[InferenceOutput]) -> bool { + next.len() == existing.len() + 1 && next.starts_with(existing) +} + +fn store_key(command_id: CommandId) -> Result { + serde_json::to_value(command_id) + .map_err(|error| ControllerWorkStoreError::new(error.to_string()))? + .as_str() + .map(str::to_owned) + .ok_or_else(|| ControllerWorkStoreError::new("command ID did not encode as a string")) +} + +#[derive(Clone, Debug)] +pub(crate) struct ControllerModels { + pub(crate) projector: String, + pub(crate) persona: String, + pub(crate) interpreter: String, + pub(crate) operational_agent: String, +} + +impl ControllerModels { + fn are_canonical(&self) -> bool { + [ + &self.projector, + &self.persona, + &self.interpreter, + &self.operational_agent, + ] + .into_iter() + .all(|model| canonical_model(model)) + } +} + +#[derive(Debug, Error)] +pub(crate) enum ControllerOpenError { + #[error("controller model IDs must be exact nonempty identifiers without whitespace")] + InvalidModels, + #[error("CodexConnector controller transport could not open: {0}")] + Connector(#[from] InferenceFault), + #[error("controller work journal could not open: {0}")] + WorkStore(String), +} + +impl From for ControllerOpenError { + fn from(error: ControllerWorkStoreError) -> Self { + Self::WorkStore(error.to_string()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub(crate) struct SpeakProposal { + text: String, +} + +impl SpeakProposal { + pub(crate) fn text(&self) -> &str { + &self.text + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct ControllerNeed { + pub(crate) detail: String, +} + +#[derive(Debug)] +pub(crate) enum SubmissionDisposition { + NoProposal(SubmitReceipt), + Completed(SubmitReceipt), + /// Derived on demand from the WorldMailbox journal. Controller work never + /// persists a second opinion about the canonical commit. + PreviouslyConfirmed(CommitReceipt), +} + +#[derive(Debug)] +pub(crate) struct NarrativeDecision { + turn: PersonaTurn, + capture: NarrativeCapture, + submission: SubmissionDisposition, +} + +impl NarrativeDecision { + pub(crate) fn persona_turn(&self) -> &PersonaTurn { + &self.turn + } + + pub(crate) fn capture(&self) -> &NarrativeCapture { + &self.capture + } + + pub(crate) fn submission(&self) -> &SubmissionDisposition { + &self.submission + } + + pub(crate) fn into_parts(self) -> (PersonaTurn, NarrativeCapture, SubmissionDisposition) { + (self.turn, self.capture, self.submission) + } +} + +#[derive(Debug)] +pub(crate) enum NarrativeRun { + Completed(NarrativeDecision), + Pending(NarrativePending), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ControllerPendingReason { + /// The exact persisted connector invocation can be presented again. The + /// connector decides whether this is an admitted completed replay. + InferenceRetryable, + /// The connector reported an indeterminate, expired, or otherwise + /// non-replayable provider outcome. Integrity violations are errors and + /// quarantine the controller organ instead of entering this state. + InferenceRecoveryRequired, + WorldUnavailable, + WorldOutcomeUnknown, + /// The exact work remains attached for reporting, but the journal owner + /// must be reopened before this process may continue. + StoreReopenRequired, +} + +fn inference_pending_reason(error: &ControllerError) -> Option { + match error { + ControllerError::Inference { source, .. } if source.integrity_was_violated() => None, + ControllerError::Inference { source, .. } if source.recovery_required() => { + Some(ControllerPendingReason::InferenceRecoveryRequired) + } + ControllerError::Inference { .. } => Some(ControllerPendingReason::InferenceRetryable), + ControllerError::ProviderContract { .. } => { + Some(ControllerPendingReason::InferenceRecoveryRequired) + } + _ => None, + } +} + +#[derive(Debug)] +pub(crate) struct NarrativePending { + work: NarrativeCheckpoint, + reason: ControllerPendingReason, +} + +impl NarrativePending { + pub(crate) fn mode(&self) -> ControllerMode { + ControllerMode::NarrativePersona + } + + pub(crate) fn reason(&self) -> ControllerPendingReason { + self.reason + } + + pub(crate) fn persona_prose(&self) -> Option<&str> { + self.work.persona_prose() + } +} + +#[derive(Debug)] +pub(crate) struct OperationalDecision { + capture: OperationalCapture, + submission: SubmissionDisposition, +} + +impl OperationalDecision { + pub(crate) fn capture(&self) -> &OperationalCapture { + &self.capture + } + + pub(crate) fn submission(&self) -> &SubmissionDisposition { + &self.submission + } + + pub(crate) fn into_parts(self) -> (OperationalCapture, SubmissionDisposition) { + (self.capture, self.submission) + } +} + +#[derive(Debug)] +pub(crate) enum OperationalRun { + Completed(OperationalDecision), + Pending(OperationalPending), +} + +#[derive(Debug)] +pub(crate) struct OperationalPending { + work: OperationalCheckpoint, + reason: ControllerPendingReason, +} + +impl OperationalPending { + pub(crate) fn mode(&self) -> ControllerMode { + ControllerMode::OperationalAgent + } + + pub(crate) fn reason(&self) -> ControllerPendingReason { + self.reason + } +} + +#[derive(Debug, Error)] +pub(crate) enum ControllerError { + #[error("world snapshot failed: {0}")] + Snapshot(MailboxError), + #[error("subject has no exact {expected:?} opportunity")] + NoOpportunity { expected: ControllerMode }, + #[error("subject has more than one current decision opportunity")] + AmbiguousOpportunity, + #[error("Eve opportunity does not match this exact controller command")] + OpportunityMismatch, + #[error("controller opportunity has no Speak affordance")] + SpeakUnavailable, + #[error("Eve command ID does not match persisted controller work")] + CommandMismatch, + #[error("no persisted controller work exists for this Eve command")] + MissingControllerWork, + #[error("{purpose:?} inference failed: {source}")] + Inference { + purpose: InferencePurpose, + #[source] + source: InferenceFault, + }, + #[error("{purpose:?} provider contract failed: {detail}")] + ProviderContract { + purpose: InferencePurpose, + detail: String, + }, + #[error("controller work was not persisted: {0}")] + WorkPersistence(String), + #[error("world command was rejected: {0}")] + World(#[from] KernelError), + #[error("controller view serialization failed: {0}")] + Serialization(String), +} + +impl ControllerError { + /// Quarantine only the cognition organ. WorldMailbox and AppSession remain + /// authoritative and available; this error must never become a daemon-wide + /// fatal signal. + pub(crate) fn requires_quarantine(&self) -> bool { + match self { + Self::WorkPersistence(_) | Self::Serialization(_) => true, + Self::Inference { source, .. } => source.integrity_was_violated(), + _ => false, + } + } +} + +impl From for ControllerError { + fn from(error: ControllerWorkStoreError) -> Self { + match error { + ControllerWorkStoreError::CommandModeConflict => Self::CommandMismatch, + error @ ControllerWorkStoreError::Fault { .. } => { + Self::WorkPersistence(error.to_string()) + } + } + } +} + +enum ControllerWorldCommand { + Exercise(DecisionInvocation), + Decline, +} + +enum ControllerWorldSubmission { + Completed(SubmissionDisposition), + Pending(ControllerPendingReason), +} + +pub(crate) struct ControllerRunner { + mailbox: WorldMailbox, + inference: Arc, + work: Arc, + models: ControllerModels, +} + +impl ControllerRunner { + /// Opens the complete production controller organ. Runtime supplies + /// deployment configuration, but cannot replace either the inference + /// transport or the durable controller-work owner. + pub(crate) fn open( + mailbox: WorldMailbox, + connector_endpoint: SocketAddr, + connector_key_path: impl AsRef, + caller_runtime_id: impl Into, + controller_work_path: impl AsRef, + models: ControllerModels, + ) -> Result { + if !models.are_canonical() { + return Err(ControllerOpenError::InvalidModels); + } + let inference = CodexConnectorInferencePort::from_secret_file( + connector_endpoint, + connector_key_path, + caller_runtime_id, + )?; + let work = CultCacheControllerWorkStore::open(controller_work_path)?; + Ok(Self { + mailbox, + inference: Arc::new(inference), + work: Arc::new(work), + models, + }) + } + + #[cfg(test)] + fn with_test_ports( + mailbox: WorldMailbox, + inference: Arc, + work: Arc, + models: ControllerModels, + ) -> Self { + Self { + mailbox, + inference, + work, + models, + } + } + + pub(crate) async fn custody_probe(&self) -> Result { + Ok(self.work.custody_probe().await?) + } + + pub(crate) async fn run_narrative( + &self, + command_id: CommandId, + opportunity: &DecisionOpportunity, + ) -> Result { + match self.work.lookup(command_id).await? { + ControllerWorkLookup::Confirmed(ControllerWork::Narrative(checkpoint)) => { + if checkpoint.opportunity() != opportunity { + return Err(ControllerError::OpportunityMismatch); + } + return self + .resume_persisted_narrative(command_id, checkpoint) + .await; + } + ControllerWorkLookup::CustodyUncertain(ControllerWork::Narrative(checkpoint)) => { + if checkpoint.opportunity() != opportunity { + return Err(ControllerError::OpportunityMismatch); + } + return Ok(narrative_pending( + checkpoint, + ControllerPendingReason::StoreReopenRequired, + )); + } + ControllerWorkLookup::Confirmed(ControllerWork::Operational(_)) + | ControllerWorkLookup::CustodyUncertain(ControllerWork::Operational(_)) => { + return Err(ControllerError::CommandMismatch); + } + ControllerWorkLookup::Missing => {} + } + let selected = self + .select( + opportunity.scope.subject_id, + ControllerMode::NarrativePersona, + opportunity, + ) + .await?; + let identity = selected.subject.label.clone(); + let typed_view = selected.typed_view()?; + let projector_context = selected.projector_context()?; + let visible_stimulus = selected.visible_stimulus()?; + let projector_prompt = build_projector_prompt(&ProjectorPrompt { + identity: &identity, + typed_context: &projector_context, + visible_stimulus: &visible_stimulus, + domain_guidance: "", + word_budget: PERSONA_WORD_BUDGET, + }); + let checkpoint = NarrativeCheckpoint::Projector { + command_id, + identity, + typed_view, + persona_model: self.models.persona.clone(), + interpreter_model: self.models.interpreter.clone(), + opportunity: selected.opportunity, + speak_affordance: selected.speak_affordance, + invocation: self.prepare(projector_request( + command_id, + &self.models.projector, + projector_prompt, + )?)?, + }; + if self + .persist(ControllerWork::Narrative(checkpoint.clone())) + .await? + == ControllerWorkWrite::CustodyUncertain + { + return Ok(narrative_pending( + checkpoint, + ControllerPendingReason::StoreReopenRequired, + )); + } + self.resume_persisted_narrative(command_id, checkpoint) + .await + } + + pub(crate) async fn run_operational( + &self, + command_id: CommandId, + opportunity: &DecisionOpportunity, + ) -> Result { + match self.work.lookup(command_id).await? { + ControllerWorkLookup::Confirmed(ControllerWork::Operational(checkpoint)) => { + if checkpoint.opportunity() != opportunity { + return Err(ControllerError::OpportunityMismatch); + } + return self + .resume_persisted_operational(command_id, checkpoint) + .await; + } + ControllerWorkLookup::CustodyUncertain(ControllerWork::Operational(checkpoint)) => { + if checkpoint.opportunity() != opportunity { + return Err(ControllerError::OpportunityMismatch); + } + return Ok(operational_pending( + checkpoint, + ControllerPendingReason::StoreReopenRequired, + )); + } + ControllerWorkLookup::Confirmed(ControllerWork::Narrative(_)) + | ControllerWorkLookup::CustodyUncertain(ControllerWork::Narrative(_)) => { + return Err(ControllerError::CommandMismatch); + } + ControllerWorkLookup::Missing => {} + } + let selected = self + .select( + opportunity.scope.subject_id, + ControllerMode::OperationalAgent, + opportunity, + ) + .await?; + let identity = selected.subject.label.clone(); + let typed_view = selected.typed_view()?; + let agent_prompt = build_operational_agent_prompt(&OperationalAgentPrompt { + identity: &identity, + typed_view: &typed_view, + available_tools: "speak(text), record_need(detail), finish_without_proposal()", + decision_pressure: "Choose whether this decision owner should speak now.", + domain_guidance: "", + step_budget: TOOL_STEP_BUDGET, + }); + let initial_conversation = match evaluate_operational_loop(&agent_prompt, &[])? { + OperationalLoopEvaluation::Continue { conversation } => conversation, + OperationalLoopEvaluation::Complete { .. } => { + return Err(ControllerError::Serialization( + "empty operational evidence unexpectedly finalized".into(), + )); + } + }; + let checkpoint = OperationalCheckpoint::AgentInFlight { + command_id, + agent_prompt, + opportunity: selected.opportunity, + speak_affordance: selected.speak_affordance, + completed: Vec::new(), + invocation: self.prepare(operational_request( + command_id, + 0, + &self.models.operational_agent, + initial_conversation, + )?)?, + }; + if self + .persist(ControllerWork::Operational(checkpoint.clone())) + .await? + == ControllerWorkWrite::CustodyUncertain + { + return Ok(operational_pending( + checkpoint, + ControllerPendingReason::StoreReopenRequired, + )); + } + self.resume_persisted_operational(command_id, checkpoint) + .await + } + + async fn resume_persisted_operational( + &self, + command_id: CommandId, + checkpoint: OperationalCheckpoint, + ) -> Result { + if checkpoint.command_id() != command_id { + return Err(ControllerError::CommandMismatch); + } + match checkpoint { + checkpoint @ OperationalCheckpoint::AgentInFlight { .. } => { + self.run_operational_pending(checkpoint).await + } + checkpoint @ OperationalCheckpoint::ReadyToSubmit { .. } => { + self.submit_operational(checkpoint).await + } + checkpoint @ OperationalCheckpoint::NoProposal { .. } => { + self.submit_operational(checkpoint).await + } + } + } + + async fn run_operational_pending( + &self, + mut checkpoint: OperationalCheckpoint, + ) -> Result { + loop { + let OperationalCheckpoint::AgentInFlight { + command_id, + agent_prompt, + opportunity, + speak_affordance, + mut completed, + invocation, + } = checkpoint.clone() + else { + return Err(ControllerError::Serialization( + "operational runner received a terminal checkpoint".into(), + )); + }; + self.ensure_opportunity_current(&opportunity).await?; + let model = invocation.invocation.request.model.clone(); + let output = match self.infer(invocation).await { + Ok(output) => output, + Err(error) => match inference_pending_reason(&error) { + Some(reason) => return Ok(operational_pending(checkpoint, reason)), + None => return Err(error), + }, + }; + completed.push(output); + match evaluate_operational_loop(&agent_prompt, &completed) { + Ok(OperationalLoopEvaluation::Complete { capture }) => { + let next = if capture.proposal.is_some() { + OperationalCheckpoint::ReadyToSubmit { + command_id, + agent_prompt, + opportunity, + speak_affordance, + completed, + } + } else { + OperationalCheckpoint::NoProposal { + command_id, + agent_prompt, + opportunity, + completed, + } + }; + if self + .persist(ControllerWork::Operational(next.clone())) + .await? + == ControllerWorkWrite::CustodyUncertain + { + return Ok(operational_pending( + next, + ControllerPendingReason::StoreReopenRequired, + )); + } + return self.submit_operational(next).await; + } + Ok(OperationalLoopEvaluation::Continue { conversation }) => { + let round = completed.len(); + let next = OperationalCheckpoint::AgentInFlight { + command_id, + agent_prompt, + opportunity, + speak_affordance, + completed, + invocation: self.prepare(operational_request( + command_id, + round, + &model, + conversation, + )?)?, + }; + match self + .persist(ControllerWork::Operational(next.clone())) + .await? + { + ControllerWorkWrite::Applied | ControllerWorkWrite::AlreadyPresent => { + checkpoint = next; + } + ControllerWorkWrite::CustodyUncertain => { + return Ok(operational_pending( + next, + ControllerPendingReason::StoreReopenRequired, + )); + } + } + } + Err(error) => match inference_pending_reason(&error) { + Some(reason) => return Ok(operational_pending(checkpoint, reason)), + None => return Err(error), + }, + } + } + } + + fn prepare(&self, request: InferenceRequest) -> Result { + let purpose = request.purpose; + self.inference + .prepare(request) + .map_err(|source| ControllerError::Inference { purpose, source }) + } + + async fn infer(&self, request: PreparedInference) -> Result { + let purpose = request.purpose; + self.inference + .infer(request) + .await + .map_err(|source| ControllerError::Inference { purpose, source }) + } + + async fn select( + &self, + subject_id: SubjectId, + expected: ControllerMode, + exact_opportunity: &DecisionOpportunity, + ) -> Result { + let snapshot = self + .mailbox + .snapshot() + .await + .map_err(ControllerError::Snapshot)?; + let Some(subject) = snapshot + .subjects + .iter() + .find(|subject| subject.id == subject_id) + .cloned() + else { + return Err(ControllerError::NoOpportunity { expected }); + }; + if subject.controller_mode != expected { + return Err(ControllerError::NoOpportunity { expected }); + } + if exact_opportunity.scope.subject_id != subject.id + || exact_opportunity.controller_id != subject.controller_id + || exact_opportunity.controller_mode != expected + { + return Err(ControllerError::OpportunityMismatch); + } + let matches = snapshot + .opportunities + .iter() + .filter(|opportunity| *opportunity == exact_opportunity) + .cloned() + .collect::>(); + let [opportunity] = matches.as_slice() else { + return if matches.is_empty() { + Err(ControllerError::NoOpportunity { expected }) + } else { + Err(ControllerError::AmbiguousOpportunity) + }; + }; + let speak_affordance = subject + .affordances + .get(&AffordanceKind::Speak) + .copied() + .filter(|id| opportunity.affordance_ids.contains(id)) + .ok_or(ControllerError::SpeakUnavailable)?; + Ok(SelectedDecision { + snapshot, + subject, + opportunity: opportunity.clone(), + speak_affordance, + }) + } + + async fn ensure_opportunity_current( + &self, + opportunity: &DecisionOpportunity, + ) -> Result<(), ControllerError> { + self.select( + opportunity.scope.subject_id, + opportunity.controller_mode, + opportunity, + ) + .await + .map(|_| ()) + } + + async fn resume_persisted_narrative( + &self, + command_id: CommandId, + checkpoint: NarrativeCheckpoint, + ) -> Result { + if checkpoint.command_id() != command_id { + return Err(ControllerError::CommandMismatch); + } + match checkpoint { + checkpoint @ NarrativeCheckpoint::Projector { .. } => { + self.run_projector(checkpoint).await + } + checkpoint @ NarrativeCheckpoint::Persona { .. } => self.run_persona(checkpoint).await, + checkpoint @ NarrativeCheckpoint::InterpreterInFlight { .. } => { + self.interpret_pending(checkpoint).await + } + checkpoint @ NarrativeCheckpoint::ReadyToSubmit { .. } => { + self.submit_narrative(checkpoint).await + } + checkpoint @ NarrativeCheckpoint::NoProposal { .. } => { + self.submit_narrative(checkpoint).await + } + } + } + + async fn run_projector( + &self, + checkpoint: NarrativeCheckpoint, + ) -> Result { + let NarrativeCheckpoint::Projector { + command_id, + identity, + typed_view, + persona_model, + interpreter_model, + opportunity, + speak_affordance, + invocation, + } = checkpoint.clone() + else { + return Err(ControllerError::Serialization( + "Projector runner received another checkpoint".into(), + )); + }; + self.ensure_opportunity_current(&opportunity).await?; + let projector_output = match self.infer(invocation).await { + Ok(output) => output, + Err(error) => match inference_pending_reason(&error) { + Some(reason) => return Ok(narrative_pending(checkpoint, reason)), + None => return Err(error), + }, + }; + let lived_stream = match projector_output + .clone() + .prose_only(InferencePurpose::Projector) + { + Ok((prose, _)) => prose, + Err(error) => match inference_pending_reason(&error) { + Some(reason) => return Ok(narrative_pending(checkpoint, reason)), + None => return Err(error), + }, + }; + let persona_prompt = build_persona_prompt(&PersonaPrompt { + identity: &identity, + lived_stream: &lived_stream, + domain_guidance: "", + word_budget: PERSONA_WORD_BUDGET, + }); + let next = NarrativeCheckpoint::Persona { + command_id, + identity, + typed_view, + interpreter_model, + opportunity, + speak_affordance, + projector_output, + invocation: self.prepare(persona_request( + command_id, + &persona_model, + persona_prompt, + )?)?, + }; + match self + .persist(ControllerWork::Narrative(next.clone())) + .await? + { + ControllerWorkWrite::CustodyUncertain => Ok(narrative_pending( + next, + ControllerPendingReason::StoreReopenRequired, + )), + ControllerWorkWrite::Applied | ControllerWorkWrite::AlreadyPresent => { + self.run_persona(next).await + } + } + } + + async fn run_persona( + &self, + checkpoint: NarrativeCheckpoint, + ) -> Result { + let NarrativeCheckpoint::Persona { + command_id, + identity, + typed_view, + interpreter_model, + opportunity, + speak_affordance, + projector_output, + invocation, + } = checkpoint.clone() + else { + return Err(ControllerError::Serialization( + "Persona runner received another checkpoint".into(), + )); + }; + let (lived_stream, projector_receipt) = projector_output + .clone() + .prose_only(InferencePurpose::Projector)?; + self.ensure_opportunity_current(&opportunity).await?; + let persona = match self + .infer(invocation) + .await + .and_then(|output| output.prose_only(InferencePurpose::Persona)) + { + Ok(persona) => persona, + Err(error) => match inference_pending_reason(&error) { + Some(reason) => return Ok(narrative_pending(checkpoint, reason)), + None => return Err(error), + }, + }; + let turn = PersonaTurn::record( + PersonaTurnBinding { + world_id: encoded_id(&opportunity.world_id)?, + controller_id: encoded_id(&opportunity.controller_id)?, + opportunity_digest: opportunity.digest()?, + world_revision: opportunity.revision, + state_digest: opportunity.state_digest.clone(), + projector_receipt_digest: projector_receipt, + persona_inference_receipt_digest: persona.1, + }, + persona.0, + ); + let interpreter_prompt = build_interpreter_prompt(&InterpreterPrompt { + identity: &identity, + typed_context: &typed_view, + lived_stream: &lived_stream, + persona_output: turn.source_prose(), + output_schema: None, + domain_guidance: "", + }); + let initial_conversation = match evaluate_interpreter_loop(&turn, &interpreter_prompt, &[])? + { + InterpreterLoopEvaluation::Continue { conversation } => conversation, + InterpreterLoopEvaluation::Complete { .. } => { + return Err(ControllerError::Serialization( + "empty Interpreter evidence unexpectedly finalized".into(), + )); + } + }; + let next = NarrativeCheckpoint::InterpreterInFlight { + command_id, + turn, + interpreter_prompt, + opportunity, + speak_affordance, + completed: Vec::new(), + invocation: self.prepare(interpreter_request( + command_id, + 0, + &interpreter_model, + initial_conversation, + )?)?, + }; + match self + .persist(ControllerWork::Narrative(next.clone())) + .await? + { + ControllerWorkWrite::CustodyUncertain => Ok(narrative_pending( + next, + ControllerPendingReason::StoreReopenRequired, + )), + ControllerWorkWrite::Applied | ControllerWorkWrite::AlreadyPresent => { + self.interpret_pending(next).await + } + } + } + + async fn interpret_pending( + &self, + mut checkpoint: NarrativeCheckpoint, + ) -> Result { + loop { + let NarrativeCheckpoint::InterpreterInFlight { + command_id, + turn, + interpreter_prompt, + opportunity, + speak_affordance, + mut completed, + invocation, + } = checkpoint.clone() + else { + return Err(ControllerError::Serialization( + "Interpreter runner received a terminal checkpoint".into(), + )); + }; + self.ensure_opportunity_current(&opportunity).await?; + let model = invocation.invocation.request.model.clone(); + let output = match self.infer(invocation).await { + Ok(output) => output, + Err(error) => match inference_pending_reason(&error) { + Some(reason) => return Ok(narrative_pending(checkpoint, reason)), + None => return Err(error), + }, + }; + completed.push(output); + match evaluate_interpreter_loop(&turn, &interpreter_prompt, &completed) { + Ok(InterpreterLoopEvaluation::Complete { capture }) => { + let next = if capture.proposal.is_some() { + NarrativeCheckpoint::ReadyToSubmit { + command_id, + turn, + interpreter_prompt, + opportunity, + speak_affordance, + completed, + } + } else { + NarrativeCheckpoint::NoProposal { + command_id, + turn, + interpreter_prompt, + opportunity, + completed, + } + }; + if self + .persist(ControllerWork::Narrative(next.clone())) + .await? + == ControllerWorkWrite::CustodyUncertain + { + return Ok(narrative_pending( + next, + ControllerPendingReason::StoreReopenRequired, + )); + } + return self.submit_narrative(next).await; + } + Ok(InterpreterLoopEvaluation::Continue { conversation }) => { + let round = completed.len(); + let next = NarrativeCheckpoint::InterpreterInFlight { + command_id, + turn, + interpreter_prompt, + opportunity, + speak_affordance, + completed, + invocation: self.prepare(interpreter_request( + command_id, + round, + &model, + conversation, + )?)?, + }; + match self + .persist(ControllerWork::Narrative(next.clone())) + .await? + { + ControllerWorkWrite::Applied | ControllerWorkWrite::AlreadyPresent => { + checkpoint = next; + } + ControllerWorkWrite::CustodyUncertain => { + return Ok(narrative_pending( + next, + ControllerPendingReason::StoreReopenRequired, + )); + } + } + } + Err(error) => match inference_pending_reason(&error) { + Some(reason) => return Ok(narrative_pending(checkpoint, reason)), + None => return Err(error), + }, + } + } + } + + async fn submit_narrative( + &self, + checkpoint: NarrativeCheckpoint, + ) -> Result { + let (command_id, opportunity) = match &checkpoint { + NarrativeCheckpoint::ReadyToSubmit { + command_id, + opportunity, + .. + } + | NarrativeCheckpoint::NoProposal { + command_id, + opportunity, + .. + } => (*command_id, opportunity.clone()), + _ => { + return Err(ControllerError::Serialization( + "narrative submission requires terminal controller work".into(), + )); + } + }; + if matches!( + self.work.custody_probe().await?, + ControllerWorkCustody::Uncertain { .. } + ) { + return Ok(narrative_pending( + checkpoint, + ControllerPendingReason::StoreReopenRequired, + )); + } + let command = match &checkpoint { + NarrativeCheckpoint::ReadyToSubmit { .. } => { + ControllerWorldCommand::Exercise(narrative_invocation(&checkpoint)?) + } + NarrativeCheckpoint::NoProposal { .. } => ControllerWorldCommand::Decline, + _ => unreachable!("terminal checkpoint was established above"), + }; + match self + .submit_controller_world(command_id, &opportunity, command) + .await? + { + ControllerWorldSubmission::Completed(submission) => { + completed_narrative(&checkpoint, submission) + } + ControllerWorldSubmission::Pending(reason) => Ok(narrative_pending(checkpoint, reason)), + } + } + + async fn persist(&self, work: ControllerWork) -> Result { + Ok(self.work.persist(&work).await?) + } + + async fn submit_operational( + &self, + checkpoint: OperationalCheckpoint, + ) -> Result { + let (command_id, opportunity) = match &checkpoint { + OperationalCheckpoint::ReadyToSubmit { + command_id, + opportunity, + .. + } + | OperationalCheckpoint::NoProposal { + command_id, + opportunity, + .. + } => (*command_id, opportunity.clone()), + OperationalCheckpoint::AgentInFlight { .. } => { + return Err(ControllerError::Serialization( + "operational submission requires terminal controller work".into(), + )); + } + }; + if matches!( + self.work.custody_probe().await?, + ControllerWorkCustody::Uncertain { .. } + ) { + return Ok(operational_pending( + checkpoint, + ControllerPendingReason::StoreReopenRequired, + )); + } + let command = match &checkpoint { + OperationalCheckpoint::ReadyToSubmit { .. } => { + ControllerWorldCommand::Exercise(operational_invocation(&checkpoint)?) + } + OperationalCheckpoint::NoProposal { .. } => ControllerWorldCommand::Decline, + OperationalCheckpoint::AgentInFlight { .. } => { + unreachable!("terminal checkpoint was established above") + } + }; + match self + .submit_controller_world(command_id, &opportunity, command) + .await? + { + ControllerWorldSubmission::Completed(submission) => { + completed_operational(&checkpoint, submission) + } + ControllerWorldSubmission::Pending(reason) => { + Ok(operational_pending(checkpoint, reason)) + } + } + } + + async fn submit_controller_world( + &self, + command_id: CommandId, + opportunity: &DecisionOpportunity, + command: ControllerWorldCommand, + ) -> Result { + let committed = match &command { + ControllerWorldCommand::Exercise(invocation) => { + self.mailbox + .controller_receipt(command_id, opportunity, invocation) + .await + } + ControllerWorldCommand::Decline => { + self.mailbox + .controller_decline_receipt(command_id, opportunity) + .await + } + }; + match committed { + Ok(Some(receipt)) => { + let submission = match command { + ControllerWorldCommand::Exercise(_) => { + SubmissionDisposition::PreviouslyConfirmed(receipt) + } + ControllerWorldCommand::Decline => { + SubmissionDisposition::NoProposal(SubmitReceipt::AlreadyApplied(receipt)) + } + }; + return Ok(ControllerWorldSubmission::Completed(submission)); + } + Ok(None) => {} + Err(MailboxError::Unavailable) => { + return Ok(ControllerWorldSubmission::Pending( + ControllerPendingReason::WorldUnavailable, + )); + } + Err(MailboxError::OutcomeUnknown { .. }) => { + return Ok(ControllerWorldSubmission::Pending( + ControllerPendingReason::WorldOutcomeUnknown, + )); + } + Err(MailboxError::Kernel(error)) => return Err(ControllerError::World(error)), + } + + let submitted = match command { + ControllerWorldCommand::Exercise(invocation) => self + .mailbox + .submit_controller(command_id, opportunity, invocation) + .await + .map(SubmissionDisposition::Completed), + ControllerWorldCommand::Decline => self + .mailbox + .submit_controller_decline(command_id, opportunity) + .await + .map(SubmissionDisposition::NoProposal), + }; + match submitted { + Ok(submission) => Ok(ControllerWorldSubmission::Completed(submission)), + Err(MailboxError::OutcomeUnknown { .. }) => Ok(ControllerWorldSubmission::Pending( + ControllerPendingReason::WorldOutcomeUnknown, + )), + Err(MailboxError::Unavailable) => Ok(ControllerWorldSubmission::Pending( + ControllerPendingReason::WorldUnavailable, + )), + Err(MailboxError::Kernel(error)) => Err(ControllerError::World(error)), + } + } +} + +#[derive(Clone)] +struct SelectedDecision { + snapshot: WorldSnapshot, + subject: SubjectSnapshot, + opportunity: DecisionOpportunity, + speak_affordance: AffordanceId, +} + +impl SelectedDecision { + fn projector_context(&self) -> Result { + serde_json::to_string_pretty(&json!({ + "world": { + "title": self.snapshot.title, + "revision": self.snapshot.revision, + "state_digest": self.snapshot.state_digest, + }, + "subject": { + "id": self.subject.id, + "label": self.subject.label, + "kind": self.subject.kind, + }, + "permission": { + "speak": true, + }, + })) + .map_err(|error| ControllerError::Serialization(error.to_string())) + } + + fn typed_view(&self) -> Result { + serde_json::to_string_pretty(&json!({ + "world": { + "title": self.snapshot.title, + "revision": self.snapshot.revision, + "state_digest": self.snapshot.state_digest, + }, + "subject": { + "id": self.subject.id, + "label": self.subject.label, + "kind": self.subject.kind, + }, + "permission": { + "speak": true, + }, + "visible_events": self.visible_events(), + })) + .map_err(|error| ControllerError::Serialization(error.to_string())) + } + + fn visible_stimulus(&self) -> Result { + serde_json::to_string_pretty(&self.visible_events()) + .map_err(|error| ControllerError::Serialization(error.to_string())) + } + + fn visible_events(&self) -> Vec { + self.snapshot + .events + .iter() + .map(|event| match &event.invocation.action { + DecisionAction::Speak { text } => json!({ + "revision": event.revision, + "speaker_subject_id": event.scope.subject_id, + "text": text, + }), + }) + .collect() + } +} + +fn speak_invocation(speak_affordance: AffordanceId, text: String) -> DecisionInvocation { + DecisionInvocation { + affordance_id: speak_affordance, + action: DecisionAction::Speak { text }, + } +} + +fn narrative_invocation( + checkpoint: &NarrativeCheckpoint, +) -> Result { + let NarrativeCheckpoint::ReadyToSubmit { + turn, + interpreter_prompt, + speak_affordance, + completed, + .. + } = checkpoint + else { + return Err(ControllerError::Serialization( + "Persona work is not ready to submit".into(), + )); + }; + let span = derive_narrative_capture(turn, interpreter_prompt, completed)? + .proposal + .ok_or_else(|| { + ControllerError::Serialization("Persona work has no exact proposal span".into()) + })?; + let text = turn + .source_prose() + .get(span.start_byte..span.end_byte) + .ok_or_else(|| ControllerError::Serialization("Persona proposal span is not exact".into()))? + .to_owned(); + Ok(speak_invocation(*speak_affordance, text)) +} + +fn operational_invocation( + checkpoint: &OperationalCheckpoint, +) -> Result { + let OperationalCheckpoint::ReadyToSubmit { + agent_prompt, + speak_affordance, + completed, + .. + } = checkpoint + else { + return Err(ControllerError::Serialization( + "operational work is not ready to submit".into(), + )); + }; + let text = derive_operational_capture(agent_prompt, completed)? + .proposal + .ok_or_else(|| { + ControllerError::Serialization("operational work has no exact proposal".into()) + })?; + Ok(speak_invocation(*speak_affordance, text)) +} + +fn narrative_capture( + report: &InterpretationReport, + inference_receipts: Vec, +) -> NarrativeCapture { + NarrativeCapture { + proposal: report.proposals().first().map(|proposal| SourceRange { + start_byte: proposal.source().start_byte(), + end_byte: proposal.source().end_byte(), + }), + gaps: report + .gaps() + .iter() + .map(|gap| TranslationGapSummary { + kind: gap.kind(), + source: SourceRange { + start_byte: gap.source().start_byte(), + end_byte: gap.source().end_byte(), + }, + detail: gap.detail().to_owned(), + }) + .collect(), + finalization: report.finalization(), + inference_receipts, + } +} + +fn completed_narrative( + checkpoint: &NarrativeCheckpoint, + submission: SubmissionDisposition, +) -> Result { + let (turn, interpreter_prompt, completed) = match checkpoint { + NarrativeCheckpoint::ReadyToSubmit { + turn, + interpreter_prompt, + completed, + .. + } + | NarrativeCheckpoint::NoProposal { + turn, + interpreter_prompt, + completed, + .. + } => (turn, interpreter_prompt, completed), + _ => { + return Err(ControllerError::Serialization( + "completed Persona work is not terminal".into(), + )); + } + }; + Ok(NarrativeRun::Completed(NarrativeDecision { + turn: turn.clone(), + capture: derive_narrative_capture(turn, interpreter_prompt, completed)?, + submission, + })) +} + +fn narrative_pending(work: NarrativeCheckpoint, reason: ControllerPendingReason) -> NarrativeRun { + NarrativeRun::Pending(NarrativePending { work, reason }) +} + +fn completed_operational( + checkpoint: &OperationalCheckpoint, + submission: SubmissionDisposition, +) -> Result { + let (agent_prompt, completed) = match checkpoint { + OperationalCheckpoint::ReadyToSubmit { + agent_prompt, + completed, + .. + } + | OperationalCheckpoint::NoProposal { + agent_prompt, + completed, + .. + } => (agent_prompt, completed), + OperationalCheckpoint::AgentInFlight { .. } => { + return Err(ControllerError::Serialization( + "completed operational work is not terminal".into(), + )); + } + }; + Ok(OperationalRun::Completed(OperationalDecision { + capture: derive_operational_capture(agent_prompt, completed)?, + submission, + })) +} + +fn operational_pending( + work: OperationalCheckpoint, + reason: ControllerPendingReason, +) -> OperationalRun { + OperationalRun::Pending(OperationalPending { work, reason }) +} + +fn encoded_id(id: &T) -> Result { + let value = serde_json::to_value(id) + .map_err(|error| ControllerError::Serialization(error.to_string()))?; + value + .as_str() + .map(str::to_owned) + .ok_or_else(|| ControllerError::Serialization("opaque ID was not a string".into())) +} + +fn tool_decode_need(name: &str, arguments: &str, detail: &str) -> ControllerNeed { + ControllerNeed { + detail: format!( + "tool `{name}` arguments were not usable ({detail}); raw_argument_digest={}", + sha256(arguments) + ), + } +} + +enum InterpreterLoopEvaluation { + Continue { conversation: Vec }, + Complete { capture: NarrativeCapture }, +} + +fn evaluate_interpreter_loop( + source: &PersonaTurn, + prompt: &str, + completed: &[InferenceOutput], +) -> Result { + let mut conversation = vec![CodexInputItem::UserText { + text: prompt.to_owned(), + }]; + let mut accumulator = InterpretationAccumulator::new(source.clone()); + let mut captured_speech = false; + let mut receipts = Vec::new(); + + for (round, output) in completed.iter().enumerate() { + if output.receipt_digest.is_empty() || output.receipt_digest.trim() != output.receipt_digest + { + return Err(ControllerError::ProviderContract { + purpose: InferencePurpose::Interpreter, + detail: "provider output has no canonical receipt digest".into(), + }); + } + receipts.push(output.receipt_digest.clone()); + let mut called_tool = false; + let mut finished = false; + for event in &output.events { + match event { + InferenceEvent::Text(text) => { + if !text.is_empty() { + conversation.push(CodexInputItem::AssistantText { text: text.clone() }); + } + } + InferenceEvent::ToolCall { + call_id, + name, + arguments, + } => { + called_tool = true; + conversation.push(CodexInputItem::ToolCall { + call_id: call_id.clone(), + name: name.clone(), + arguments: arguments.clone(), + }); + let result = match name.as_str() { + SPEAK_TOOL => match serde_json::from_str::(arguments) + { + Ok(call) if !captured_speech => { + let derived_text = source + .source_prose() + .get(call.source_start_byte..call.source_end_byte) + .unwrap_or_default() + .to_owned(); + let feedback = accumulator.capture_proposal( + SpeakProposal { text: derived_text }, + call.source_start_byte, + call.source_end_byte, + ); + captured_speech = feedback == CaptureToolFeedback::Accepted; + format!("{feedback:?}") + } + Ok(call) => { + let feedback = accumulator.record_gap(RecordGapToolCall { + kind: TranslationGapKind::Ambiguity, + source_start_byte: call.source_start_byte, + source_end_byte: call.source_end_byte, + detail: "More than one speech proposal was offered; this runner permits one decision invocation per opportunity.".into(), + }); + format!("{feedback:?}") + } + Err(error) => format!( + "{:?}", + accumulator.record_tool_decode_failure( + name, + arguments, + &error.to_string(), + ) + ), + }, + RECORD_GAP_TOOL => { + match serde_json::from_str::(arguments) { + Ok(call) => format!("{:?}", accumulator.record_gap(call)), + Err(error) => format!( + "{:?}", + accumulator.record_tool_decode_failure( + name, + arguments, + &error.to_string(), + ) + ), + } + } + FINISH_INTERPRETATION_TOOL => { + match serde_json::from_str::(arguments) { + Ok(_) => { + finished = true; + "interpretation finished".into() + } + Err(error) => format!( + "{:?}", + accumulator.record_tool_decode_failure( + name, + arguments, + &error.to_string(), + ) + ), + } + } + _ => format!( + "{:?}", + accumulator.record_tool_decode_failure( + name, + arguments, + "tool is not available for this exact opportunity", + ) + ), + }; + conversation.push(CodexInputItem::ToolResult { + call_id: call_id.clone(), + output: result, + }); + } + } + } + + let finalization = if finished || !called_tool { + Some(InterpretationFinalization::InterpreterFinished) + } else if round + 1 == TOOL_STEP_BUDGET { + Some(InterpretationFinalization::StepBudgetExhausted) + } else { + None + }; + if let Some(finalization) = finalization { + if round + 1 != completed.len() { + return Err(ControllerError::Serialization( + "interpreter evidence continued after total finalization".into(), + )); + } + let report = accumulator.finalize(finalization); + return Ok(InterpreterLoopEvaluation::Complete { + capture: narrative_capture(&report, receipts), + }); + } + } + + if completed.len() >= TOOL_STEP_BUDGET { + return Err(ControllerError::Serialization( + "interpreter evidence exceeded its step budget".into(), + )); + } + Ok(InterpreterLoopEvaluation::Continue { conversation }) +} + +enum OperationalLoopEvaluation { + Continue { conversation: Vec }, + Complete { capture: OperationalCapture }, +} + +fn evaluate_operational_loop( + prompt: &str, + completed: &[InferenceOutput], +) -> Result { + let mut conversation = vec![CodexInputItem::UserText { + text: prompt.to_owned(), + }]; + let mut proposal = None; + let mut needs = Vec::new(); + let mut receipts = Vec::new(); + + for (round, output) in completed.iter().enumerate() { + if output.receipt_digest.is_empty() || output.receipt_digest.trim() != output.receipt_digest + { + return Err(ControllerError::ProviderContract { + purpose: InferencePurpose::OperationalAgent, + detail: "provider output has no canonical receipt digest".into(), + }); + } + receipts.push(output.receipt_digest.clone()); + let mut called_tool = false; + let mut terminal_choice = None; + for event in &output.events { + match event { + InferenceEvent::Text(text) => { + if !text.is_empty() { + conversation.push(CodexInputItem::AssistantText { text: text.clone() }); + } + } + InferenceEvent::ToolCall { + call_id, + name, + arguments, + } => { + called_tool = true; + conversation.push(CodexInputItem::ToolCall { + call_id: call_id.clone(), + name: name.clone(), + arguments: arguments.clone(), + }); + let result = match name.as_str() { + SPEAK_TOOL => match serde_json::from_str::(arguments) + { + Ok(call) if terminal_choice.is_none() => { + proposal = Some(call.text); + terminal_choice = Some(SPEAK_TOOL); + "speech proposal captured".into() + } + Ok(_) => { + needs.push(ControllerNeed { + detail: "The agent offered more than one terminal choice for one opportunity.".into(), + }); + "one terminal choice is already captured".into() + } + Err(error) => { + needs.push(tool_decode_need(name, arguments, &error.to_string())); + "arguments recorded as a need".into() + } + }, + RECORD_NEED_TOOL => match serde_json::from_str::(arguments) + { + Ok(call) => { + needs.push(ControllerNeed { + detail: call.detail, + }); + "need recorded".into() + } + Err(error) => { + needs.push(tool_decode_need(name, arguments, &error.to_string())); + "arguments recorded as a need".into() + } + }, + FINISH_WITHOUT_PROPOSAL_TOOL => { + match serde_json::from_str::(arguments) { + Ok(_) => { + if terminal_choice.is_some() { + return Err(ControllerError::ProviderContract { + purpose: InferencePurpose::OperationalAgent, + detail: "finish_without_proposal contradicted an existing terminal choice".into(), + }); + } + terminal_choice = Some(FINISH_WITHOUT_PROPOSAL_TOOL); + "decision finished without a proposal".into() + } + Err(error) => { + needs.push(tool_decode_need( + name, + arguments, + &error.to_string(), + )); + "arguments recorded as a need".into() + } + } + } + _ => { + needs.push(tool_decode_need( + name, + arguments, + "tool is not available for this exact opportunity", + )); + "unavailable tool recorded as a need".into() + } + }; + conversation.push(CodexInputItem::ToolResult { + call_id: call_id.clone(), + output: result, + }); + } + } + } + + let is_complete = + terminal_choice.is_some() || !called_tool || round + 1 == TOOL_STEP_BUDGET; + if is_complete { + if round + 1 != completed.len() { + return Err(ControllerError::Serialization( + "operational evidence continued after total finalization".into(), + )); + } + if round + 1 == TOOL_STEP_BUDGET && terminal_choice.is_none() && called_tool { + needs.push(ControllerNeed { + detail: "The operational-agent step budget ended before explicit completion." + .into(), + }); + } + return Ok(OperationalLoopEvaluation::Complete { + capture: OperationalCapture { + proposal, + needs, + inference_receipts: receipts, + }, + }); + } + } + + if completed.len() >= TOOL_STEP_BUDGET { + return Err(ControllerError::Serialization( + "operational evidence exceeded its step budget".into(), + )); + } + Ok(OperationalLoopEvaluation::Continue { conversation }) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct InterpreterSpeakCall { + source_start_byte: usize, + source_end_byte: usize, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct OperationalSpeakCall { + text: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RecordNeedCall { + detail: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct EmptyToolCall {} + +fn projector_request( + command_id: CommandId, + model: &str, + prompt: String, +) -> Result { + text_request( + command_id, + InferencePurpose::Projector, + model, + "Render the private view in the user message as one lived narrative stream. Return only that prose.", + prompt, + 1_200, + ) +} + +fn persona_request( + command_id: CommandId, + model: &str, + prompt: String, +) -> Result { + // This boundary is deliberately not lowered through a generic stage + // constructor. Its only model-visible input is the dedicated natural-prose + // prompt plus the smallest nonempty instruction required by the provider + // transport contract. + let mut provider = CodexProviderRequest::new( + provider_request_id(command_id, InferencePurpose::Persona, 0)?, + conversation_id(command_id, InferencePurpose::Persona, 0)?, + model, + PERSONA_PROVIDER_INSTRUCTIONS, + ); + provider.input = vec![CodexInputItem::UserText { text: prompt }]; + provider.reasoning_effort = Some("low".into()); + provider.tools = Vec::new(); + provider.tool_choice = CodexToolChoice::Auto; + provider.parallel_tool_calls = false; + provider.output_format_name = None; + provider.output_schema_json = None; + provider.max_output_tokens = Some(1_200); + Ok(InferenceRequest { + purpose: InferencePurpose::Persona, + provider, + }) +} + +fn text_request( + command_id: CommandId, + purpose: InferencePurpose, + model: &str, + instructions: &str, + prompt: String, + max_output_tokens: u32, +) -> Result { + let request = provider_request_id(command_id, purpose, 0)?; + let conversation = conversation_id(command_id, purpose, 0)?; + let mut provider = CodexProviderRequest::new(request, conversation, model, instructions); + provider.input = vec![CodexInputItem::UserText { text: prompt }]; + provider.reasoning_effort = Some("low".into()); + provider.tools = Vec::new(); + provider.tool_choice = CodexToolChoice::Auto; + provider.parallel_tool_calls = false; + provider.output_format_name = None; + provider.output_schema_json = None; + provider.max_output_tokens = Some(max_output_tokens); + Ok(InferenceRequest { purpose, provider }) +} + +fn interpreter_request( + command_id: CommandId, + round: usize, + model: &str, + input: Vec, +) -> Result { + tool_request( + command_id, + round, + InferencePurpose::Interpreter, + model, + "Translate the preserved Persona prose using only the supplied capture tools. Untranslatable meaning is recorded, never repaired or rejected.", + input, + interpreter_tools(), + ) +} + +fn operational_request( + command_id: CommandId, + round: usize, + model: &str, + input: Vec, +) -> Result { + tool_request( + command_id, + round, + InferencePurpose::OperationalAgent, + model, + "Use only the supplied tools for this permissioned decision. Returning no proposal is valid.", + input, + operational_tools(), + ) +} + +fn tool_request( + command_id: CommandId, + round: usize, + purpose: InferencePurpose, + model: &str, + instructions: &str, + input: Vec, + tools: Vec, +) -> Result { + let mut provider = CodexProviderRequest::new( + provider_request_id(command_id, purpose, round)?, + conversation_id(command_id, purpose, round)?, + model, + instructions, + ); + provider.input = input; + provider.reasoning_effort = Some("medium".into()); + provider.tools = tools; + provider.tool_choice = CodexToolChoice::Auto; + provider.parallel_tool_calls = false; + provider.output_format_name = None; + provider.output_schema_json = None; + provider.max_output_tokens = Some(1_200); + Ok(InferenceRequest { purpose, provider }) +} + +fn interpreter_tools() -> Vec { + vec![ + tool( + SPEAK_TOOL, + "Capture one exact spoken utterance by byte span in the preserved Persona prose; the harness derives the utterance verbatim.", + json!({ + "type":"object", + "additionalProperties":false, + "properties":{ + "source_start_byte":{"type":"integer","minimum":0}, + "source_end_byte":{"type":"integer","minimum":1} + }, + "required":["source_start_byte","source_end_byte"] + }), + ), + tool( + RECORD_GAP_TOOL, + "Preserve meaningful source prose that has no safe current typed translation.", + json!({ + "type":"object", + "additionalProperties":false, + "properties":{ + "kind":{"type":"string","enum":["ambiguity","missing_reference","missing_affordance","missing_primitive","unresolved"]}, + "source_start_byte":{"type":"integer","minimum":0}, + "source_end_byte":{"type":"integer","minimum":1}, + "detail":{"type":"string"} + }, + "required":["kind","source_start_byte","source_end_byte","detail"] + }), + ), + tool( + FINISH_INTERPRETATION_TOOL, + "Finish the total interpretation after all supported captures and gaps are recorded.", + empty_schema(), + ), + ] +} + +fn operational_tools() -> Vec { + vec![ + tool( + SPEAK_TOOL, + "Propose one exact utterance for this decision owner.", + json!({ + "type":"object", + "additionalProperties":false, + "properties":{"text":{"type":"string"}}, + "required":["text"] + }), + ), + tool( + RECORD_NEED_TOOL, + "Record information or capability the agent would need but does not currently have.", + json!({ + "type":"object", + "additionalProperties":false, + "properties":{"detail":{"type":"string"}}, + "required":["detail"] + }), + ), + tool( + FINISH_WITHOUT_PROPOSAL_TOOL, + "Finish this opportunity without proposing an action.", + empty_schema(), + ), + ] +} + +fn empty_schema() -> Value { + json!({"type":"object","additionalProperties":false,"properties":{}}) +} + +fn tool(name: &str, description: &str, schema: Value) -> CodexToolDefinition { + CodexToolDefinition { + name: name.into(), + description: description.into(), + parameters_json: serde_json::to_string(&schema) + .expect("static controller tool schemas must serialize"), + } +} + +fn provider_request_id( + command_id: CommandId, + purpose: InferencePurpose, + round: usize, +) -> Result { + Ok(format!( + "ghostlight-request-{}-{}-{round}", + encoded_id(&command_id)?, + purpose_name(purpose) + )) +} + +fn conversation_id( + command_id: CommandId, + purpose: InferencePurpose, + round: usize, +) -> Result { + Ok(format!( + "ghostlight-conversation-{}-{}-{round}", + encoded_id(&command_id)?, + purpose_name(purpose) + )) +} + +fn purpose_name(purpose: InferencePurpose) -> &'static str { + match purpose { + InferencePurpose::Projector => "projector", + InferencePurpose::Persona => "persona", + InferencePurpose::Interpreter => "interpreter", + InferencePurpose::OperationalAgent => "operational", + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::world::{ + AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, ControllerId, CreateWorld, + DecisionScope, DraftSubjectHandle, NewController, NewDecisionSubject, PrincipalId, + SubjectKind, WorldId, WorldPhase, + }; + use std::{ + collections::BTreeSet, + sync::atomic::{AtomicBool, Ordering}, + }; + + #[test] + fn controller_work_decode_rejects_an_alternate_messagepack_shape() { + let command_id = CommandId::new(); + let opportunity = fixture_opportunity(ControllerMode::OperationalAgent); + let work = operational_in_flight( + command_id, + &opportunity, + "Hold the bridge.", + "operational-model", + vec![], + ); + let payload = rmp_serde::to_vec(&work).unwrap(); + assert_eq!( + rmp_serde::from_slice::(&payload).unwrap(), + work + ); + let row = CultCacheEnvelope { + key: store_key(command_id).unwrap(), + r#type: CONTROLLER_WORK_ROW.into(), + payload, + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(CONTROLLER_WORK_SCHEMA.into()), + }; + assert!(decode_controller_work(&row).is_err()); + } + + #[test] + fn in_flight_progression_cannot_substitute_a_model() { + let operational_command = CommandId::new(); + let operational_opportunity = fixture_opportunity(ControllerMode::OperationalAgent); + let existing_operational = operational_in_flight( + operational_command, + &operational_opportunity, + "Hold the bridge.", + "operational-model-a", + vec![], + ); + let completed_operational = vec![InferenceOutput { + events: vec![InferenceEvent::ToolCall { + call_id: "need".into(), + name: RECORD_NEED_TOOL.into(), + arguments: json!({"detail":"The wind reading is missing."}).to_string(), + }], + receipt_digest: "sha256:operational-round-zero".into(), + }]; + let substituted_operational = operational_in_flight( + operational_command, + &operational_opportunity, + "Hold the bridge.", + "operational-model-b", + completed_operational, + ); + assert!(existing_operational.integrity_is_valid()); + assert!(substituted_operational.integrity_is_valid()); + assert!(!valid_controller_work_progression( + &existing_operational, + &substituted_operational + )); + + let narrative_command = CommandId::new(); + let narrative_opportunity = fixture_opportunity(ControllerMode::NarrativePersona); + let turn = fixture_persona_turn(&narrative_opportunity, "I wait."); + let existing_narrative = narrative_interpreter_in_flight( + narrative_command, + &narrative_opportunity, + &turn, + "Interpret the prose.", + "interpreter-model-a", + vec![], + ); + let completed_narrative = vec![InferenceOutput { + events: vec![InferenceEvent::ToolCall { + call_id: "gap".into(), + name: RECORD_GAP_TOOL.into(), + arguments: json!({ + "kind":"unresolved", + "source_start_byte":0, + "source_end_byte":1, + "detail":"The intended action is unclear." + }) + .to_string(), + }], + receipt_digest: "sha256:narrative-round-zero".into(), + }]; + let substituted_narrative = narrative_interpreter_in_flight( + narrative_command, + &narrative_opportunity, + &turn, + "Interpret the prose.", + "interpreter-model-b", + completed_narrative, + ); + assert!(existing_narrative.integrity_is_valid()); + assert!(substituted_narrative.integrity_is_valid()); + assert!(!valid_controller_work_progression( + &existing_narrative, + &substituted_narrative + )); + } + + #[test] + fn persona_provider_request_is_structurally_prose_only() { + let command_id = CommandId::new(); + let request = persona_request( + command_id, + "persona-model", + build_persona_prompt(&PersonaPrompt { + identity: "An old bridge keeper with sore hands.", + lived_stream: "Rain drums on the tollhouse roof.", + domain_guidance: "Answer with dry patience.", + word_budget: 80, + }), + ) + .unwrap(); + assert_eq!(request.purpose, InferencePurpose::Persona); + assert!(request.provider.validate().is_ok()); + assert_eq!(request.provider.instructions, PERSONA_PROVIDER_INSTRUCTIONS); + assert!(request.provider.tools.is_empty()); + assert_eq!(request.provider.tool_choice, CodexToolChoice::Auto); + assert!(!request.provider.parallel_tool_calls); + assert!(request.provider.output_format_name.is_none()); + assert!(request.provider.output_schema_json.is_none()); + assert!(request.provider.previous_response_id.is_none()); + assert_eq!(request.provider.input.len(), 1); + let encoded = serde_json::to_string(&request.provider) + .unwrap() + .to_lowercase(); + for leak in [ + "world_id", + "controller_id", + "opportunity", + "affordance_id", + "execute the supplied", + "output contract", + ] { + assert!(!encoded.contains(leak), "Persona request leaked `{leak}`"); + } + } + + #[test] + fn controller_tool_schemas_cannot_claim_authority_or_envelopes() { + for definition in interpreter_tools().into_iter().chain(operational_tools()) { + let schema: Value = serde_json::from_str(&definition.parameters_json).unwrap(); + assert_eq!(schema["additionalProperties"], false); + let properties = schema["properties"].as_object().unwrap(); + for forbidden in [ + "caller", + "caller_id", + "controller_id", + "world_id", + "opportunity", + "revision", + "expected_revision", + "affordance_id", + "command_id", + ] { + assert!(!properties.contains_key(forbidden)); + } + } + assert_eq!( + operational_tools() + .iter() + .map(|tool| tool.name.as_str()) + .collect::>(), + vec![SPEAK_TOOL, RECORD_NEED_TOOL, FINISH_WITHOUT_PROPOSAL_TOOL] + ); + let interpreter_speak = interpreter_tools() + .into_iter() + .find(|tool| tool.name == SPEAK_TOOL) + .unwrap(); + let schema: Value = serde_json::from_str(&interpreter_speak.parameters_json).unwrap(); + assert!( + !schema["properties"] + .as_object() + .unwrap() + .contains_key("text") + ); + assert!( + serde_json::from_str::( + r#"{"source_start_byte":0,"source_end_byte":4,"text":"invented"}"# + ) + .is_err(), + "Interpreter speech cannot carry text independent of its source span" + ); + } + + #[test] + fn provider_request_and_conversation_ids_are_deterministic_from_the_eve_command() { + let command_id = CommandId::new(); + let first = persona_request(command_id, "persona-model", "prompt".into()).unwrap(); + let replay = persona_request(command_id, "persona-model", "prompt".into()).unwrap(); + assert_eq!(first, replay); + assert_eq!( + conversation_id(command_id, InferencePurpose::Interpreter, 0).unwrap(), + conversation_id(command_id, InferencePurpose::Interpreter, 0).unwrap() + ); + assert_ne!( + conversation_id(command_id, InferencePurpose::Interpreter, 0).unwrap(), + conversation_id(command_id, InferencePurpose::Interpreter, 1).unwrap() + ); + let round_zero = interpreter_request( + command_id, + 0, + "interpreter-model", + vec![CodexInputItem::UserText { + text: "prompt".into(), + }], + ) + .unwrap(); + let round_one = interpreter_request( + command_id, + 1, + "interpreter-model", + vec![CodexInputItem::UserText { + text: "prompt".into(), + }], + ) + .unwrap(); + assert!(round_zero.provider.validate().is_ok()); + assert!(round_one.provider.validate().is_ok()); + assert_ne!(round_zero, round_one); + } + + struct RecordingPort { + outputs: Mutex>>, + persisted_before_interpreter: Arc, + } + + #[async_trait] + impl InferencePort for RecordingPort { + fn prepare(&self, request: InferenceRequest) -> Result { + fixture_prepared(request) + } + + async fn infer( + &self, + _request: PreparedInference, + ) -> Result { + assert!(self.persisted_before_interpreter.load(Ordering::SeqCst)); + self.outputs.lock().unwrap().remove(0) + } + } + + struct ExactReplayPort { + expected: PreparedInference, + output: Mutex>>, + seen: AtomicBool, + } + + #[async_trait] + impl InferencePort for ExactReplayPort { + fn prepare(&self, _request: InferenceRequest) -> Result { + Err(InferenceFault::new( + "exact replay unexpectedly attempted to prepare a new invocation", + )) + } + + async fn infer( + &self, + request: PreparedInference, + ) -> Result { + assert_eq!(request, self.expected); + assert!(!self.seen.swap(true, Ordering::SeqCst)); + self.output.lock().unwrap().take().unwrap() + } + } + + fn fixture_prepared(request: InferenceRequest) -> Result { + let native_request_sha256 = Sha256::digest( + serde_json::to_vec(&request).map_err(|error| InferenceFault::new(error.to_string()))?, + ) + .into(); + let purpose = request.purpose; + let invocation = CodexTransportInvocation::new( + "ghostlight-controller-test", + 4_102_444_800_000, + native_request_sha256, + request.provider, + ) + .map_err(|error| InferenceFault::new(error.to_string()))?; + Ok(PreparedInference { + purpose, + invocation, + }) + } + + fn fixture_opportunity(mode: ControllerMode) -> DecisionOpportunity { + DecisionOpportunity { + world_id: WorldId::issue(), + revision: 7, + state_digest: "sha256:fixture-state".into(), + scope: DecisionScope { + subject_id: SubjectId::issue(), + }, + controller_id: ControllerId::issue(), + controller_mode: mode, + affordance_ids: vec![AffordanceId::issue()], + } + } + + fn operational_in_flight( + command_id: CommandId, + opportunity: &DecisionOpportunity, + agent_prompt: &str, + model: &str, + completed: Vec, + ) -> ControllerWork { + let OperationalLoopEvaluation::Continue { conversation } = + evaluate_operational_loop(agent_prompt, &completed).unwrap() + else { + panic!("operational fixture unexpectedly finalized") + }; + let request = + operational_request(command_id, completed.len(), model, conversation).unwrap(); + ControllerWork::Operational(OperationalCheckpoint::AgentInFlight { + command_id, + agent_prompt: agent_prompt.into(), + opportunity: opportunity.clone(), + speak_affordance: opportunity.affordance_ids[0], + completed, + invocation: fixture_prepared(request).unwrap(), + }) + } + + fn fixture_persona_turn(opportunity: &DecisionOpportunity, source_prose: &str) -> PersonaTurn { + PersonaTurn::record( + PersonaTurnBinding { + world_id: encoded_id(&opportunity.world_id).unwrap(), + controller_id: encoded_id(&opportunity.controller_id).unwrap(), + opportunity_digest: opportunity.digest().unwrap(), + world_revision: opportunity.revision, + state_digest: opportunity.state_digest.clone(), + projector_receipt_digest: "sha256:projector".into(), + persona_inference_receipt_digest: "sha256:persona".into(), + }, + source_prose, + ) + } + + fn narrative_interpreter_in_flight( + command_id: CommandId, + opportunity: &DecisionOpportunity, + turn: &PersonaTurn, + interpreter_prompt: &str, + model: &str, + completed: Vec, + ) -> ControllerWork { + let InterpreterLoopEvaluation::Continue { conversation } = + evaluate_interpreter_loop(turn, interpreter_prompt, &completed).unwrap() + else { + panic!("Interpreter fixture unexpectedly finalized") + }; + let request = + interpreter_request(command_id, completed.len(), model, conversation).unwrap(); + ControllerWork::Narrative(NarrativeCheckpoint::InterpreterInFlight { + command_id, + turn: turn.clone(), + interpreter_prompt: interpreter_prompt.into(), + opportunity: opportunity.clone(), + speak_affordance: opportunity.affordance_ids[0], + completed, + invocation: fixture_prepared(request).unwrap(), + }) + } + + struct RecordingWorkStore { + persisted: Arc, + work: Mutex>, + } + + #[async_trait] + impl ControllerWorkStore for RecordingWorkStore { + async fn lookup( + &self, + command_id: CommandId, + ) -> Result { + Ok(self + .work + .lock() + .unwrap() + .get(&command_id) + .cloned() + .map(ControllerWorkLookup::Confirmed) + .unwrap_or(ControllerWorkLookup::Missing)) + } + + async fn persist( + &self, + work: &ControllerWork, + ) -> Result { + if !work.integrity_is_valid() { + return Err(ControllerWorkStoreError::new("invalid controller work")); + } + let command_id = work.command_id(); + let mut stored = self.work.lock().unwrap(); + if let Some(existing) = stored.get(&command_id) { + if existing == work { + return Ok(ControllerWorkWrite::AlreadyPresent); + } + if existing.mode() != work.mode() { + return Err(ControllerWorkStoreError::CommandModeConflict); + } + if !valid_controller_work_progression(existing, work) { + return Err(ControllerWorkStoreError::new( + "controller checkpoint progression conflict", + )); + } + } else if !work.is_initial() { + return Err(ControllerWorkStoreError::new( + "controller work skipped its durable pre-inference boundary", + )); + } + stored.insert(command_id, work.clone()); + self.persisted.store(true, Ordering::SeqCst); + Ok(ControllerWorkWrite::Applied) + } + + async fn custody_probe(&self) -> Result { + let stored = self.work.lock().unwrap(); + Ok(ControllerWorkCustody::Owned { + narrative_commands: stored + .values() + .filter(|work| work.mode() == ControllerMode::NarrativePersona) + .count(), + operational_commands: stored + .values() + .filter(|work| work.mode() == ControllerMode::OperationalAgent) + .count(), + }) + } + } + + async fn active_mailbox( + controller: NewController, + ) -> ( + tempfile::TempDir, + WorldMailbox, + tokio::task::JoinHandle<()>, + SubjectSnapshot, + ) { + let directory = tempfile::tempdir().unwrap(); + let (mailbox, task) = WorldMailbox::open(directory.path().join("world.cc")).unwrap(); + let owner = PrincipalId::new("owner"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation = mailbox + .create_fixture( + CreateWorld { + id: CommandId::new(), + owner: owner.clone(), + title: "Controller Fixture".into(), + subjects: vec![NewDecisionSubject { + handle: DraftSubjectHandle::new("subject"), + label: "Subject".into(), + kind: SubjectKind::Person, + controller, + affordances: BTreeSet::from([AffordanceKind::Speak]), + }], + }, + &authenticated, + ) + .await + .unwrap(); + let mut snapshot = mailbox.snapshot().await.unwrap(); + for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] { + mailbox + .submit_fixture( + CommandEnvelope { + id: CommandId::new(), + world_id: creation.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(owner.clone()), + body, + }, + &authenticated, + ) + .await + .unwrap(); + snapshot = mailbox.snapshot().await.unwrap(); + } + assert_eq!(snapshot.phase, WorldPhase::Active); + let subject = snapshot.subjects[0].clone(); + (directory, mailbox, task, subject) + } + + fn output( + events: Vec, + receipt: &str, + ) -> Result { + Ok(InferenceOutput { + events, + receipt_digest: format!("sha256:{receipt}"), + }) + } + + fn models() -> ControllerModels { + ControllerModels { + projector: "projector".into(), + persona: "persona".into(), + interpreter: "interpreter".into(), + operational_agent: "operator".into(), + } + } + + #[tokio::test] + async fn narrative_turn_is_persisted_before_total_interpretation_and_shared_submit() { + let (_directory, mailbox, task, _subject) = + active_mailbox(NewController::NarrativePersona).await; + let persisted = Arc::new(AtomicBool::new(false)); + let source = "I say, \"The rain has teeth tonight.\""; + let speech = "The rain has teeth tonight."; + let start = source.find(speech).unwrap(); + let port = Arc::new(RecordingPort { + outputs: Mutex::new(vec![ + output( + vec![InferenceEvent::Text("Cold rain needles the bridge.".into())], + "projector", + ), + output(vec![InferenceEvent::Text(source.into())], "persona"), + output( + vec![ + InferenceEvent::ToolCall { + call_id: "call_bad_span".into(), + name: SPEAK_TOOL.into(), + arguments: json!({ + "source_start_byte":source.len() + 10, + "source_end_byte":source.len() + 20 + }) + .to_string(), + }, + InferenceEvent::ToolCall { + call_id: "call_speak".into(), + name: SPEAK_TOOL.into(), + arguments: json!({ + "source_start_byte":start, + "source_end_byte":start + speech.len() + }) + .to_string(), + }, + InferenceEvent::ToolCall { + call_id: "call_finish".into(), + name: FINISH_INTERPRETATION_TOOL.into(), + arguments: "{}".into(), + }, + ], + "interpreter", + ), + ]), + persisted_before_interpreter: persisted.clone(), + }); + let store = Arc::new(RecordingWorkStore { + persisted, + work: Mutex::new(BTreeMap::new()), + }); + let runner = ControllerRunner::with_test_ports(mailbox.clone(), port, store, models()); + let opportunity = mailbox.snapshot().await.unwrap().opportunities[0].clone(); + let command_id = CommandId::new(); + let run = runner + .run_narrative(command_id, &opportunity) + .await + .unwrap(); + let NarrativeRun::Completed(decision) = run else { + panic!("turn remained pending") + }; + assert_eq!( + decision.capture.proposal, + Some(SourceRange { + start_byte: start, + end_byte: start + speech.len(), + }) + ); + assert_eq!(decision.capture.gaps.len(), 1); + assert_eq!(decision.turn.source_prose(), source); + assert!(matches!( + decision.submission, + SubmissionDisposition::Completed(_) + )); + let later_opportunity = mailbox.snapshot().await.unwrap().opportunities[0].clone(); + assert!(matches!( + runner.run_narrative(command_id, &later_opportunity).await, + Err(ControllerError::OpportunityMismatch) + )); + let NarrativeRun::Completed(replayed) = runner + .run_narrative(command_id, &opportunity) + .await + .unwrap() + else { + panic!("terminal narrative work was not lookup-first") + }; + assert!(matches!( + replayed.submission, + SubmissionDisposition::PreviouslyConfirmed(_) + )); + assert_eq!(mailbox.snapshot().await.unwrap().events.len(), 1); + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + #[tokio::test] + async fn operational_agent_uses_the_same_world_submission_without_exposed_authority() { + let (_directory, mailbox, task, _subject) = + active_mailbox(NewController::OperationalAgent).await; + let persisted = Arc::new(AtomicBool::new(false)); + let port = Arc::new(RecordingPort { + outputs: Mutex::new(vec![output( + vec![ + InferenceEvent::ToolCall { + call_id: "need".into(), + name: RECORD_NEED_TOOL.into(), + arguments: json!({"detail":"No wind reading is available."}).to_string(), + }, + InferenceEvent::ToolCall { + call_id: "speak".into(), + name: SPEAK_TOOL.into(), + arguments: json!({"text":"Close the western span."}).to_string(), + }, + ], + "operational", + )]), + persisted_before_interpreter: persisted.clone(), + }); + let store = Arc::new(RecordingWorkStore { + persisted, + work: Mutex::new(BTreeMap::new()), + }); + let runner = ControllerRunner::with_test_ports(mailbox.clone(), port, store, models()); + let opportunity = mailbox.snapshot().await.unwrap().opportunities[0].clone(); + let command_id = CommandId::new(); + let run = runner + .run_operational(command_id, &opportunity) + .await + .unwrap(); + let OperationalRun::Completed(decision) = run else { + panic!("operational work remained pending") + }; + assert_eq!(decision.capture.needs.len(), 1); + assert!(matches!( + decision.submission, + SubmissionDisposition::Completed(_) + )); + let OperationalRun::Completed(replayed) = runner + .run_operational(command_id, &opportunity) + .await + .unwrap() + else { + panic!("terminal operational work was not lookup-first") + }; + assert!(matches!( + replayed.submission, + SubmissionDisposition::PreviouslyConfirmed(_) + )); + assert_eq!(mailbox.snapshot().await.unwrap().events.len(), 1); + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + #[tokio::test] + async fn narrative_no_proposal_commits_an_exact_world_decline_and_replays() { + let (_directory, mailbox, task, _subject) = + active_mailbox(NewController::NarrativePersona).await; + let persisted = Arc::new(AtomicBool::new(false)); + let source = "I listen to the rain and let the question pass."; + let port = Arc::new(RecordingPort { + outputs: Mutex::new(vec![ + output( + vec![InferenceEvent::Text( + "Rain ticks against the bridge rail.".into(), + )], + "decline-projector", + ), + output(vec![InferenceEvent::Text(source.into())], "decline-persona"), + output( + vec![ + InferenceEvent::ToolCall { + call_id: "gap".into(), + name: RECORD_GAP_TOOL.into(), + arguments: json!({ + "kind":"unresolved", + "source_start_byte":0, + "source_end_byte":source.len(), + "detail":"The prose expresses no supported world action." + }) + .to_string(), + }, + InferenceEvent::ToolCall { + call_id: "finish".into(), + name: FINISH_INTERPRETATION_TOOL.into(), + arguments: "{}".into(), + }, + ], + "decline-interpreter", + ), + ]), + persisted_before_interpreter: persisted.clone(), + }); + let store = Arc::new(RecordingWorkStore { + persisted, + work: Mutex::new(BTreeMap::new()), + }); + let runner = ControllerRunner::with_test_ports(mailbox.clone(), port, store, models()); + let opportunity = mailbox.snapshot().await.unwrap().opportunities[0].clone(); + let command_id = CommandId::new(); + let NarrativeRun::Completed(decision) = runner + .run_narrative(command_id, &opportunity) + .await + .unwrap() + else { + panic!("narrative decline remained pending") + }; + assert!(decision.capture.proposal.is_none()); + assert_eq!(decision.capture.gaps.len(), 1); + let applied = match decision.submission { + SubmissionDisposition::NoProposal(SubmitReceipt::Applied(receipt)) => receipt, + other => panic!("narrative decline was not canonically applied: {other:?}"), + }; + assert_eq!(applied.resulting_revision, opportunity.revision + 1); + let after = mailbox.snapshot().await.unwrap(); + assert_eq!(after.revision, opportunity.revision + 1); + assert!(after.events.is_empty()); + let refreshed = after.opportunities[0].clone(); + assert_ne!(refreshed, opportunity); + assert!(matches!( + runner.run_narrative(CommandId::new(), &opportunity).await, + Err(ControllerError::NoOpportunity { + expected: ControllerMode::NarrativePersona + }) + )); + assert!(matches!( + runner.run_narrative(command_id, &refreshed).await, + Err(ControllerError::OpportunityMismatch) + )); + + let NarrativeRun::Completed(replayed) = runner + .run_narrative(command_id, &opportunity) + .await + .unwrap() + else { + panic!("persisted narrative decline did not replay") + }; + assert!(matches!( + replayed.submission, + SubmissionDisposition::NoProposal(SubmitReceipt::AlreadyApplied(ref receipt)) + if receipt == &applied + )); + assert_eq!(mailbox.snapshot().await.unwrap(), after); + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + #[tokio::test] + async fn operational_no_proposal_commits_an_exact_world_decline_and_replays() { + let (_directory, mailbox, task, _subject) = + active_mailbox(NewController::OperationalAgent).await; + let persisted = Arc::new(AtomicBool::new(false)); + let port = Arc::new(RecordingPort { + outputs: Mutex::new(vec![output( + vec![ + InferenceEvent::ToolCall { + call_id: "need".into(), + name: RECORD_NEED_TOOL.into(), + arguments: json!({"detail":"No current intervention is warranted."}) + .to_string(), + }, + InferenceEvent::ToolCall { + call_id: "finish".into(), + name: FINISH_WITHOUT_PROPOSAL_TOOL.into(), + arguments: "{}".into(), + }, + ], + "decline-operational", + )]), + persisted_before_interpreter: persisted.clone(), + }); + let store = Arc::new(RecordingWorkStore { + persisted, + work: Mutex::new(BTreeMap::new()), + }); + let runner = ControllerRunner::with_test_ports(mailbox.clone(), port, store, models()); + let opportunity = mailbox.snapshot().await.unwrap().opportunities[0].clone(); + let command_id = CommandId::new(); + let OperationalRun::Completed(decision) = runner + .run_operational(command_id, &opportunity) + .await + .unwrap() + else { + panic!("operational decline remained pending") + }; + assert!(decision.capture.proposal.is_none()); + assert_eq!(decision.capture.needs.len(), 1); + let applied = match decision.submission { + SubmissionDisposition::NoProposal(SubmitReceipt::Applied(receipt)) => receipt, + other => panic!("operational decline was not canonically applied: {other:?}"), + }; + assert_eq!(applied.resulting_revision, opportunity.revision + 1); + let after = mailbox.snapshot().await.unwrap(); + assert_eq!(after.revision, opportunity.revision + 1); + assert!(after.events.is_empty()); + + let OperationalRun::Completed(replayed) = runner + .run_operational(command_id, &opportunity) + .await + .unwrap() + else { + panic!("persisted operational decline did not replay") + }; + assert!(matches!( + replayed.submission, + SubmissionDisposition::NoProposal(SubmitReceipt::AlreadyApplied(ref receipt)) + if receipt == &applied + )); + assert_eq!(mailbox.snapshot().await.unwrap(), after); + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + #[tokio::test] + async fn controller_work_reopens_and_replays_the_exact_connector_invocation() { + let (directory, mailbox, task, _subject) = + active_mailbox(NewController::NarrativePersona).await; + let path = directory.path().join("controller-work.cc"); + let store = Arc::new(CultCacheControllerWorkStore::open(&path).unwrap()); + let source = "I say, \"The rain has teeth tonight.\""; + let speech = "The rain has teeth tonight."; + let start = source.find(speech).unwrap(); + let persisted = Arc::new(AtomicBool::new(true)); + let runner = ControllerRunner::with_test_ports( + mailbox.clone(), + Arc::new(RecordingPort { + outputs: Mutex::new(vec![ + output( + vec![InferenceEvent::Text("Cold rain needles the bridge.".into())], + "reopen-projector", + ), + output(vec![InferenceEvent::Text(source.into())], "reopen-persona"), + Err(InferenceFault::retryable("connector transport interrupted")), + ]), + persisted_before_interpreter: persisted.clone(), + }), + store.clone(), + models(), + ); + let opportunity = mailbox.snapshot().await.unwrap().opportunities[0].clone(); + let command_id = CommandId::new(); + let NarrativeRun::Pending(first_pending) = runner + .run_narrative(command_id, &opportunity) + .await + .unwrap() + else { + panic!("interrupted Interpreter unexpectedly completed") + }; + assert_eq!( + first_pending.reason(), + ControllerPendingReason::InferenceRetryable + ); + assert_eq!(first_pending.mode(), ControllerMode::NarrativePersona); + assert_eq!(first_pending.persona_prose(), Some(source)); + let pending = first_pending.work; + let NarrativeCheckpoint::InterpreterInFlight { + invocation: exact_invocation, + .. + } = &pending + else { + panic!("interrupted Interpreter lost its persisted Persona turn") + }; + let exact_invocation = exact_invocation.clone(); + assert!(pending.integrity_is_valid()); + + drop(runner); + drop(store); + let reopened = Arc::new(CultCacheControllerWorkStore::open(&path).unwrap()); + let ControllerWorkLookup::Confirmed(ControllerWork::Narrative(reopened_pending)) = + reopened.lookup(command_id).await.unwrap() + else { + panic!("exact command was not recovered") + }; + assert_eq!(reopened_pending, pending); + let NarrativeCheckpoint::InterpreterInFlight { + invocation: reopened_invocation, + .. + } = &reopened_pending + else { + panic!("reopened command changed checkpoint") + }; + assert_eq!(reopened_invocation, &exact_invocation); + + let replay_port = Arc::new(ExactReplayPort { + expected: exact_invocation, + output: Mutex::new(Some(output( + vec![ + InferenceEvent::ToolCall { + call_id: "bad-span".into(), + name: SPEAK_TOOL.into(), + arguments: json!({ + "source_start_byte": source.len() + 1, + "source_end_byte": source.len() + 2 + }) + .to_string(), + }, + InferenceEvent::ToolCall { + call_id: "exact-span".into(), + name: SPEAK_TOOL.into(), + arguments: json!({ + "source_start_byte": start, + "source_end_byte": start + speech.len() + }) + .to_string(), + }, + InferenceEvent::ToolCall { + call_id: "finish".into(), + name: FINISH_INTERPRETATION_TOOL.into(), + arguments: "{}".into(), + }, + ], + "replayed-interpreter", + ))), + seen: AtomicBool::new(false), + }); + let recovery_runner = ControllerRunner::with_test_ports( + mailbox.clone(), + replay_port.clone(), + reopened.clone(), + models(), + ); + let NarrativeRun::Completed(decision) = recovery_runner + .run_narrative(command_id, &opportunity) + .await + .unwrap() + else { + panic!("completed connector replay did not continue") + }; + assert!(replay_port.seen.load(Ordering::SeqCst)); + assert_eq!(decision.turn.source_prose(), source); + assert_eq!( + decision.capture.proposal, + Some(SourceRange { + start_byte: start, + end_byte: start + speech.len(), + }) + ); + assert_eq!(decision.capture.gaps.len(), 1); + assert!(matches!( + decision.submission, + SubmissionDisposition::Completed(_) + )); + let captured = decision.capture.clone(); + + drop(recovery_runner); + drop(reopened); + let reopened_terminal = CultCacheControllerWorkStore::open(&path).unwrap(); + let ControllerWorkLookup::Confirmed(ControllerWork::Narrative(terminal)) = + reopened_terminal.lookup(command_id).await.unwrap() + else { + panic!("terminal command was not recovered") + }; + let NarrativeCheckpoint::ReadyToSubmit { + turn, + interpreter_prompt, + completed, + .. + } = &terminal + else { + panic!("terminal command changed checkpoint") + }; + assert_eq!( + derive_narrative_capture(turn, interpreter_prompt, completed).unwrap(), + captured + ); + let snapshot = mailbox.snapshot().await.unwrap(); + assert_eq!(snapshot.events.len(), 1); + assert_eq!( + snapshot.events[0].invocation.action, + DecisionAction::Speak { + text: speech.into() + } + ); + + drop(reopened_terminal); + drop(mailbox); + task.await.unwrap(); + } + + #[tokio::test] + #[ignore = "requires the Idunn-sealed production CodexConnector"] + async fn real_codex_connector_cognition_modes_commit_speech() { + let connector_endpoint: SocketAddr = std::env::var("GHOSTLIGHT_CONTROLLER_CONNECTOR") + .expect("GHOSTLIGHT_CONTROLLER_CONNECTOR is required") + .parse() + .expect("GHOSTLIGHT_CONTROLLER_CONNECTOR must be a socket address"); + let connector_credential = std::env::var_os("GHOSTLIGHT_CONTROLLER_CREDENTIAL") + .expect("GHOSTLIGHT_CONTROLLER_CREDENTIAL is required"); + let runtime_id = + std::env::var("GHOSTLIGHT_RUNTIME_ID").expect("GHOSTLIGHT_RUNTIME_ID is required"); + let models = ControllerModels { + projector: std::env::var("GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL") + .expect("GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL is required"), + persona: std::env::var("GHOSTLIGHT_CONTROLLER_PERSONA_MODEL") + .expect("GHOSTLIGHT_CONTROLLER_PERSONA_MODEL is required"), + interpreter: std::env::var("GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL") + .expect("GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL is required"), + operational_agent: std::env::var("GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL") + .expect("GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL is required"), + }; + let persona_log = std::env::var_os("GHOSTLIGHT_ACCEPTANCE_PERSONA_PROSE_LOG") + .expect("GHOSTLIGHT_ACCEPTANCE_PERSONA_PROSE_LOG is required"); + + let directory = tempfile::tempdir().unwrap(); + let (mailbox, task) = WorldMailbox::open(directory.path().join("world.cc")).unwrap(); + let owner = PrincipalId::new("acceptance-owner"); + let human = PrincipalId::new("acceptance-roll-caller"); + let owner_caller = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let human_caller = AuthenticatedCaller::fixture(CallerId::Principal(human.clone())); + let creation = mailbox + .create_fixture( + CreateWorld { + id: CommandId::new(), + owner: owner.clone(), + title: "Midnight Roll Call".into(), + subjects: vec![ + NewDecisionSubject { + handle: DraftSubjectHandle::new("roll-caller"), + label: "Iris, the midnight roll caller".into(), + kind: SubjectKind::Person, + controller: NewController::Human { + principal: human.clone(), + }, + affordances: BTreeSet::from([AffordanceKind::Speak]), + }, + NewDecisionSubject { + handle: DraftSubjectHandle::new("watch-officer"), + label: "Mara, a watch officer who answers direct roll calls aloud in one short sentence".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([AffordanceKind::Speak]), + }, + NewDecisionSubject { + handle: DraftSubjectHandle::new("signal-council"), + label: "The Signal Council, which answers direct roll calls aloud with one short operational sentence".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([AffordanceKind::Speak]), + }, + ], + }, + &owner_caller, + ) + .await + .unwrap(); + + let mut snapshot = mailbox.snapshot().await.unwrap(); + mailbox + .submit_fixture( + CommandEnvelope { + id: CommandId::new(), + world_id: creation.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(owner.clone()), + body: CommandBody::ApproveDraft, + }, + &owner_caller, + ) + .await + .unwrap(); + snapshot = mailbox.snapshot().await.unwrap(); + mailbox + .submit_fixture( + CommandEnvelope { + id: CommandId::new(), + world_id: creation.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(human.clone()), + body: CommandBody::ApproveDraft, + }, + &human_caller, + ) + .await + .unwrap(); + snapshot = mailbox.snapshot().await.unwrap(); + mailbox + .submit_fixture( + CommandEnvelope { + id: CommandId::new(), + world_id: creation.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(owner.clone()), + body: CommandBody::ActivateWorld, + }, + &owner_caller, + ) + .await + .unwrap(); + + snapshot = mailbox.snapshot().await.unwrap(); + assert!(snapshot.phase == WorldPhase::Active); + let human_subject = snapshot + .subjects + .iter() + .find(|subject| subject.human_controller.as_ref() == Some(&human)) + .cloned() + .unwrap(); + let human_opportunity = snapshot + .opportunities + .iter() + .find(|opportunity| opportunity.controller_id == human_subject.controller_id) + .cloned() + .unwrap(); + let human_speak = *human_subject + .affordances + .get(&AffordanceKind::Speak) + .unwrap(); + let seed = "Mara and the Signal Council, answer the midnight roll call aloud now. Each of you, say in one short sentence that you hear me."; + let seed_command = CommandId::new(); + let seed_receipt = mailbox + .submit_fixture( + CommandEnvelope { + id: seed_command, + world_id: creation.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(human.clone()), + body: CommandBody::ExerciseDecision { + opportunity: human_opportunity, + invocation: DecisionInvocation { + affordance_id: human_speak, + action: DecisionAction::Speak { text: seed.into() }, + }, + }, + }, + &human_caller, + ) + .await + .unwrap(); + assert!(matches!(seed_receipt, SubmitReceipt::Applied(_))); + + let runner = ControllerRunner::open( + mailbox.clone(), + connector_endpoint, + connector_credential, + runtime_id, + directory.path().join("controller-work.cc"), + models, + ) + .unwrap(); + + snapshot = mailbox.snapshot().await.unwrap(); + assert!(snapshot.events.len() == 1); + let DecisionAction::Speak { text: seeded_text } = &snapshot.events[0].invocation.action; + assert!(seeded_text.as_bytes() == seed.as_bytes()); + let narrative_subject = snapshot + .subjects + .iter() + .find(|subject| subject.controller_mode == ControllerMode::NarrativePersona) + .cloned() + .unwrap(); + let narrative_opportunity = snapshot + .opportunities + .iter() + .find(|opportunity| opportunity.controller_id == narrative_subject.controller_id) + .cloned() + .unwrap(); + let narrative_command = CommandId::new(); + let narrative_run = match runner + .run_narrative(narrative_command, &narrative_opportunity) + .await + { + Ok(run) => run, + Err(_) => panic!("NarrativePersona acceptance returned an error"), + }; + let NarrativeRun::Completed(narrative_decision) = narrative_run else { + panic!("NarrativePersona acceptance did not complete") + }; + let narrative_receipt = match narrative_decision.submission() { + SubmissionDisposition::Completed(SubmitReceipt::Applied(receipt)) => receipt, + _ => panic!("NarrativePersona acceptance did not apply one world command"), + }; + assert!(narrative_receipt.command_id == narrative_command); + assert!(narrative_decision.persona_turn().receipt_is_valid()); + assert!( + !narrative_decision + .persona_turn() + .binding() + .projector_receipt_digest + .is_empty() + ); + assert!( + !narrative_decision + .persona_turn() + .binding() + .persona_inference_receipt_digest + .is_empty() + ); + assert!( + narrative_decision + .persona_turn() + .binding() + .opportunity_digest + == narrative_opportunity.digest().unwrap() + ); + assert!( + narrative_decision.persona_turn().binding().world_revision + == narrative_opportunity.revision + ); + assert!( + narrative_decision.persona_turn().binding().state_digest + == narrative_opportunity.state_digest + ); + let persona_prose = narrative_decision.persona_turn().source_prose().to_owned(); + assert!(!persona_prose.trim().is_empty()); + assert!(persona_prose.len() <= 65_536); + assert!(!narrative_decision.capture().inference_receipts.is_empty()); + let narrative_span = narrative_decision.capture().proposal.unwrap(); + let narrative_speech = persona_prose + .get(narrative_span.start_byte..narrative_span.end_byte) + .unwrap() + .to_owned(); + assert!(!narrative_speech.trim().is_empty()); + let ControllerWorkLookup::Confirmed(ControllerWork::Narrative( + NarrativeCheckpoint::ReadyToSubmit { + completed: persisted_interpreter_outputs, + .. + }, + )) = runner.work.lookup(narrative_command).await.unwrap() + else { + panic!("NarrativePersona acceptance evidence was not durable") + }; + let interpreter_speak = persisted_interpreter_outputs + .iter() + .flat_map(|output| output.events.iter()) + .filter_map(|event| match event { + InferenceEvent::ToolCall { + name, arguments, .. + } if name == SPEAK_TOOL => { + serde_json::from_str::(arguments).ok() + } + InferenceEvent::Text(_) | InferenceEvent::ToolCall { .. } => None, + }) + .find(|call| { + call.source_start_byte == narrative_span.start_byte + && call.source_end_byte == narrative_span.end_byte + }) + .unwrap(); + assert!(interpreter_speak.source_start_byte == narrative_span.start_byte); + assert!(interpreter_speak.source_end_byte == narrative_span.end_byte); + + snapshot = mailbox.snapshot().await.unwrap(); + assert!(snapshot.events.len() == 2); + assert!(snapshot.revision == narrative_opportunity.revision + 1); + let narrative_event = snapshot + .events + .iter() + .find(|event| event.controller_id == narrative_subject.controller_id) + .unwrap(); + let DecisionAction::Speak { + text: committed_narrative_speech, + } = &narrative_event.invocation.action; + assert!(committed_narrative_speech.as_bytes() == narrative_speech.as_bytes()); + + let operational_subject = snapshot + .subjects + .iter() + .find(|subject| subject.controller_mode == ControllerMode::OperationalAgent) + .cloned() + .unwrap(); + let operational_opportunity = snapshot + .opportunities + .iter() + .find(|opportunity| opportunity.controller_id == operational_subject.controller_id) + .cloned() + .unwrap(); + let operational_command = CommandId::new(); + let operational_run = match runner + .run_operational(operational_command, &operational_opportunity) + .await + { + Ok(run) => run, + Err(_) => panic!("OperationalAgent acceptance returned an error"), + }; + let OperationalRun::Completed(operational_decision) = operational_run else { + panic!("OperationalAgent acceptance did not complete") + }; + let operational_receipt = match operational_decision.submission() { + SubmissionDisposition::Completed(SubmitReceipt::Applied(receipt)) => receipt, + _ => panic!("OperationalAgent acceptance did not apply one world command"), + }; + assert!(operational_receipt.command_id == operational_command); + assert!(!operational_decision.capture().inference_receipts.is_empty()); + let operational_speech = operational_decision + .capture() + .proposal + .as_ref() + .unwrap() + .to_owned(); + assert!(!operational_speech.trim().is_empty()); + let ControllerWorkLookup::Confirmed(ControllerWork::Operational( + OperationalCheckpoint::ReadyToSubmit { + completed: persisted_agent_outputs, + .. + }, + )) = runner.work.lookup(operational_command).await.unwrap() + else { + panic!("OperationalAgent acceptance evidence was not durable") + }; + let operational_speak = persisted_agent_outputs + .iter() + .flat_map(|output| output.events.iter()) + .find_map(|event| match event { + InferenceEvent::ToolCall { + name, arguments, .. + } if name == SPEAK_TOOL => { + serde_json::from_str::(arguments).ok() + } + InferenceEvent::Text(_) | InferenceEvent::ToolCall { .. } => None, + }) + .unwrap(); + assert!(operational_speak.text.as_bytes() == operational_speech.as_bytes()); + + snapshot = mailbox.snapshot().await.unwrap(); + assert!(snapshot.events.len() == 3); + assert!(snapshot.revision == operational_opportunity.revision + 1); + let operational_event = snapshot + .events + .iter() + .find(|event| event.controller_id == operational_subject.controller_id) + .unwrap(); + let DecisionAction::Speak { + text: committed_operational_speech, + } = &operational_event.invocation.action; + assert!(committed_operational_speech.as_bytes() == operational_speech.as_bytes()); + + drop(runner); + drop(mailbox); + task.await.unwrap(); + + let mut persona_file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(persona_log) + .unwrap(); + std::io::Write::write_all(&mut persona_file, persona_prose.as_bytes()).unwrap(); + persona_file.sync_all().unwrap(); + } +} diff --git a/crates/ghostlight-dungeon/src/world/journal.rs b/crates/ghostlight-dungeon/src/world/journal.rs index e6bdcf1..0910100 100644 --- a/crates/ghostlight-dungeon/src/world/journal.rs +++ b/crates/ghostlight-dungeon/src/world/journal.rs @@ -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 { + pub(super) fn open_owner(path: &Path) -> Result { 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(¤t, 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, ) -> 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( }) } -fn decode(row: &CultCacheEnvelope) -> Result { - rmp_serde::from_slice(&row.payload).map_err(|error| { +fn decode(row: &CultCacheEnvelope) -> Result { + 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::(&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(_)) + )); } } diff --git a/crates/ghostlight-dungeon/src/world/mailbox.rs b/crates/ghostlight-dungeon/src/world/mailbox.rs index aae8557..e81e895 100644 --- a/crates/ghostlight-dungeon/src/world/mailbox.rs +++ b/crates/ghostlight-dungeon/src/world/mailbox.rs @@ -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, } +enum OwnedWorld { + Empty(journal::EmptyWorldJournal), + Live(WorldKernel), +} + enum Request { + Create { + input: CreateWorld, + authenticated: AuthenticatedCaller, + reply: oneshot::Sender>, + }, Submit { command: CommandEnvelope, authenticated: AuthenticatedCaller, @@ -22,6 +37,17 @@ enum Request { Snapshot { reply: oneshot::Sender>, }, + ControllerReceipt { + command_id: CommandId, + opportunity: super::DecisionOpportunity, + invocation: super::DecisionInvocation, + reply: oneshot::Sender, KernelError>>, + }, + ControllerDeclineReceipt { + command_id: CommandId, + opportunity: super::DecisionOpportunity, + reply: oneshot::Sender, 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) -> 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 { - let command_id = command.id; + input: CreateWorldIntent, + principal: &VerifiedPrincipalEvidence, + ) -> Result { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + self.create_authenticated(input, authenticated.clone()) + .await + } + + #[cfg(test)] + pub(super) async fn submit_fixture( + &self, + command: CommandEnvelope, + authenticated: &AuthenticatedCaller, + ) -> Result { + self.submit_authenticated(command, authenticated.clone()) + .await } pub(crate) async fn snapshot(&self) -> Result { @@ -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, 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, 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) { + 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))); diff --git a/crates/ghostlight-dungeon/src/world/mod.rs b/crates/ghostlight-dungeon/src/world/mod.rs index 7a22597..8571d74 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -5,21 +5,29 @@ //! Controllers may use models, but models never own lifecycle, scope, affordances, //! opportunities, reduction, or persistence. +mod controllers; mod journal; mod mailbox; +pub(crate) use controllers::{ + ControllerError, ControllerModels, ControllerOpenError, ControllerPendingReason, + ControllerRunner, ControllerWorkCustody, NarrativeCapture, NarrativeDecision, NarrativePending, + NarrativeRun, OperationalCapture, OperationalDecision, OperationalPending, OperationalRun, + SourceRange, SubmissionDisposition, TranslationGapSummary, +}; +pub(crate) use mailbox::{MailboxError, WorldMailbox}; + use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use std::{ - collections::{BTreeMap, BTreeSet}, - path::Path, -}; +use std::collections::{BTreeMap, BTreeSet}; +#[cfg(test)] +use std::path::Path; use thiserror::Error; use uuid::Uuid; const STATE_SCHEMA: &str = "ghostlight.world_state.foundation.v0"; -const COMMIT_SCHEMA: &str = "ghostlight.world_commit.foundation.v0"; +const COMMIT_SCHEMA: &str = "ghostlight.world_commit.foundation.v1"; macro_rules! opaque_uuid { ($name:ident) => { @@ -47,6 +55,12 @@ impl CommandId { Self::issue() } + pub(crate) fn parse_uuid(value: &str) -> Result { + Uuid::parse_str(value) + .map(Self) + .map_err(|_| KernelError::InvalidCommandId) + } + fn key(self) -> String { self.0.to_string() } @@ -98,10 +112,10 @@ impl PrincipalId { #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] #[serde(transparent)] -pub(crate) struct DraftSubjectHandle(String); +struct DraftSubjectHandle(String); impl DraftSubjectHandle { - pub(crate) fn new(value: impl Into) -> Self { + fn new(value: impl Into) -> Self { Self(value.into()) } } @@ -137,44 +151,65 @@ pub(crate) enum AffordanceKind { #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", rename_all = "snake_case")] -pub(crate) enum NewController { +enum NewController { Human { principal: PrincipalId }, NarrativePersona, OperationalAgent, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -pub(crate) struct NewDecisionSubject { - pub(crate) handle: DraftSubjectHandle, - pub(crate) label: String, - pub(crate) kind: SubjectKind, - pub(crate) controller: NewController, - pub(crate) affordances: BTreeSet, +struct NewDecisionSubject { + handle: DraftSubjectHandle, + label: String, + kind: SubjectKind, + controller: NewController, + affordances: BTreeSet, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -pub(crate) struct CreateWorld { +struct CreateWorld { + id: CommandId, + owner: PrincipalId, + title: String, + subjects: Vec, +} + +/// Unattributed creation intent. World ingress derives ownership, controller +/// identity, handles, kinds, and affordances from verified principal evidence. +#[derive(Clone, Debug)] +pub(crate) struct CreateWorldIntent { pub(crate) id: CommandId, - pub(crate) owner: PrincipalId, pub(crate) title: String, - pub(crate) subjects: Vec, + pub(crate) human_subject_label: String, + pub(crate) narrative_persona_label: Option, + pub(crate) operational_agent_label: Option, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", content = "id", rename_all = "snake_case")] -pub(crate) enum CallerId { +enum CallerId { Principal(PrincipalId), Controller(ControllerId), } -/// Sealed identity evidence. Production construction belongs to the app-session -/// identity owner when runtime ingress moves onto this boundary. #[derive(Clone, Debug)] -pub(crate) struct AuthenticatedCaller { +struct AuthenticatedCaller { caller: CallerId, } impl AuthenticatedCaller { + fn verified_principal(principal: PrincipalId) -> Self { + Self { + caller: CallerId::Principal(principal), + } + } + + fn verified_controller(controller: ControllerId) -> Self { + Self { + caller: CallerId::Controller(controller), + } + } + #[cfg(test)] fn fixture(caller: CallerId) -> Self { Self { caller } @@ -182,11 +217,13 @@ impl AuthenticatedCaller { } #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] pub(crate) struct DecisionScope { pub(crate) subject_id: SubjectId, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] pub(crate) struct DecisionOpportunity { pub(crate) world_id: WorldId, pub(crate) revision: u64, @@ -197,6 +234,12 @@ pub(crate) struct DecisionOpportunity { pub(crate) affordance_ids: Vec, } +impl DecisionOpportunity { + pub(crate) fn digest(&self) -> Result { + digest(self) + } +} + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", rename_all = "snake_case")] pub(crate) enum DecisionAction { @@ -212,32 +255,43 @@ impl DecisionAction { } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] pub(crate) struct DecisionInvocation { pub(crate) affordance_id: AffordanceId, pub(crate) action: DecisionAction, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -pub(crate) struct CommandEnvelope { +struct CommandEnvelope { + id: CommandId, + world_id: WorldId, + expected_revision: u64, + caller: CallerId, + body: CommandBody, +} + +/// Unattributed human command intent. The mailbox derives the caller from +/// live app-session evidence before the reducer sees an envelope. +#[derive(Clone, Debug)] +pub(crate) struct PrincipalCommandIntent { pub(crate) id: CommandId, pub(crate) world_id: WorldId, pub(crate) expected_revision: u64, - pub(crate) caller: CallerId, pub(crate) body: CommandBody, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", rename_all = "snake_case")] pub(crate) enum CommandBody { - SetTitle { - title: String, - }, ApproveDraft, ActivateWorld, ExerciseDecision { opportunity: DecisionOpportunity, invocation: DecisionInvocation, }, + DeclineDecision { + opportunity: DecisionOpportunity, + }, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -344,10 +398,6 @@ enum WorldEffect { title: String, bindings: Vec, }, - TitleChanged { - previous_title: String, - resulting_title: String, - }, DraftApproved { principal: PrincipalId, }, @@ -356,20 +406,48 @@ enum WorldEffect { opportunity: DecisionOpportunity, event: DecisionEvent, }, + DecisionDeclined { + opportunity: DecisionOpportunity, + }, +} + +/// The exact raw command admitted by the world owner. This is the sole +/// persistent command authority: IDs, callers, retry identity, and effects are +/// derived from this value rather than copied into independently forgeable +/// commit fields. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", content = "command", rename_all = "snake_case")] +enum CommittedCommand { + CreateWorld(CreateWorld), + WorldCommand(CommandEnvelope), +} + +impl CommittedCommand { + fn id(&self) -> CommandId { + match self { + Self::CreateWorld(command) => command.id, + Self::WorldCommand(command) => command.id, + } + } + + fn caller(&self) -> CallerId { + match self { + Self::CreateWorld(command) => CallerId::Principal(command.owner.clone()), + Self::WorldCommand(command) => command.caller.clone(), + } + } } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] struct WorldCommit { schema: String, world_id: WorldId, - command_id: CommandId, - command_digest: String, + command: CommittedCommand, previous_revision: Option, resulting_revision: u64, previous_state_digest: Option, resulting_state_digest: String, previous_commit_digest: Option, - caller: CallerId, effect: WorldEffect, committed_at: DateTime, digest: String, @@ -402,14 +480,6 @@ pub(crate) struct WorldSnapshot { pub(crate) last_commit_digest: Option, } -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct CreatedSubject { - pub(crate) handle: DraftSubjectHandle, - pub(crate) subject_id: SubjectId, - pub(crate) controller_id: ControllerId, - pub(crate) affordances: BTreeMap, -} - #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct CommitReceipt { pub(crate) command_id: CommandId, @@ -422,35 +492,25 @@ pub(crate) struct CommitReceipt { pub(crate) struct CreationReceipt { pub(crate) command_id: CommandId, pub(crate) world_id: WorldId, - pub(crate) subjects: Vec, pub(crate) resulting_state_digest: String, pub(crate) commit_digest: String, } impl CreationReceipt { fn from_commit(commit: &WorldCommit) -> Result { - let WorldEffect::WorldCreated { bindings, .. } = &commit.effect else { + let CommittedCommand::CreateWorld(command) = &commit.command else { + return Err(KernelError::Invariant( + "world genesis receipt does not point to a creation command".into(), + )); + }; + let WorldEffect::WorldCreated { .. } = &commit.effect else { return Err(KernelError::Invariant( "world genesis receipt does not point to genesis".into(), )); }; - let subjects = bindings - .iter() - .map(|binding| CreatedSubject { - handle: binding.handle.clone(), - subject_id: binding.subject_id, - controller_id: binding.controller.id(), - affordances: binding - .affordances - .iter() - .map(|(affordance_id, grant)| (grant.kind, *affordance_id)) - .collect(), - }) - .collect(); Ok(Self { - command_id: commit.command_id, + command_id: command.id, world_id: commit.world_id, - subjects, resulting_state_digest: commit.resulting_state_digest.clone(), commit_digest: commit.digest.clone(), }) @@ -460,7 +520,7 @@ impl CreationReceipt { impl From<&WorldCommit> for CommitReceipt { fn from(commit: &WorldCommit) -> Self { Self { - command_id: commit.command_id, + command_id: commit.command.id(), resulting_revision: commit.resulting_revision, resulting_state_digest: commit.resulting_state_digest.clone(), commit_digest: commit.digest.clone(), @@ -472,11 +532,12 @@ impl From<&WorldCommit> for CommitReceipt { pub(crate) enum SubmitReceipt { Applied(CommitReceipt), AlreadyApplied(CommitReceipt), - NoEffect(WorldSnapshot), } #[derive(Debug, Error)] pub(crate) enum KernelError { + #[error("command ID must be a UUID")] + InvalidCommandId, #[error("world title must not be empty")] EmptyTitle, #[error("world owner or human controller principal must be canonical and nonempty")] @@ -504,10 +565,10 @@ pub(crate) enum KernelError { expected: WorldPhase, actual: WorldPhase, }, - #[error("draft title is locked after the first approval")] - DraftLocked, #[error("caller is not a required draft approver")] NotDraftApprover, + #[error("caller has already approved this draft")] + DraftAlreadyApproved, #[error("draft is missing required approvals: {0:?}")] MissingApprovals(Vec), #[error("decision opportunity is stale or does not exactly derive from current state")] @@ -526,6 +587,8 @@ pub(crate) enum KernelError { CreationConflict, #[error("world creation target already contains another world")] CreationTargetOccupied, + #[error("world has not been created")] + WorldNotCreated, #[error("opened store contains another world")] OpenedWorldMismatch, #[error("world ownership is uncertain after command {command_id:?}; drop and reopen")] @@ -542,12 +605,23 @@ pub(crate) enum KernelError { Invariant(String), } +impl KernelError { + fn requires_owner_restart(&self) -> bool { + matches!( + self, + Self::RecoveryRequired { .. } + | Self::OwnershipLost + | Self::Store(_) + | Self::CorruptJournal(_) + | Self::Invariant(_) + ) + } +} + impl From for KernelError { fn from(error: journal::JournalError) -> Self { match error { - journal::JournalError::NotEmpty => Self::CreationTargetOccupied, journal::JournalError::WorldMismatch => Self::OpenedWorldMismatch, - journal::JournalError::CreationConflict => Self::CreationConflict, journal::JournalError::RecoveryRequired { command_id } => { Self::RecoveryRequired { command_id } } @@ -563,61 +637,93 @@ struct WorldKernel { journal: journal::WorldJournal, } +struct PreparedCreation { + command: CreateWorld, + owner: PrincipalId, + title: String, + subjects: Vec, +} + +fn prepare_creation( + input: CreateWorld, + authenticated: &AuthenticatedCaller, +) -> Result { + let CallerId::Principal(authenticated_principal) = &authenticated.caller else { + return Err(KernelError::AuthenticationMismatch); + }; + validate_principal(&input.owner)?; + if &input.owner != authenticated_principal { + return Err(KernelError::AuthenticationMismatch); + } + let subjects = canonicalize_subjects(&input.subjects)?; + let title = normalize_title(&input.title)?; + Ok(PreparedCreation { + owner: input.owner.clone(), + title, + subjects, + command: input, + }) +} + impl WorldKernel { + fn initialize( + empty: journal::EmptyWorldJournal, + prepared: PreparedCreation, + ) -> Result<(Self, CreationReceipt), KernelError> { + let world_id = WorldId::issue(); + let effect = issue_genesis(prepared.owner, prepared.title, prepared.subjects); + let mut state = WorldState::genesis(world_id, &prepared.command, &effect)?; + let mut genesis = WorldCommit { + schema: COMMIT_SCHEMA.into(), + world_id, + command: CommittedCommand::CreateWorld(prepared.command), + previous_revision: None, + resulting_revision: 0, + previous_state_digest: None, + resulting_state_digest: state.state_digest.clone(), + previous_commit_digest: None, + effect, + committed_at: Utc::now(), + digest: String::new(), + }; + genesis.digest = commit_digest(&genesis)?; + state.last_commit_digest = Some(genesis.digest.clone()); + let receipt = CreationReceipt::from_commit(&genesis)?; + let journal = empty.initialize(&state, &genesis)?; + Ok((Self { state, journal }, receipt)) + } + + fn retry_creation(&self, prepared: &PreparedCreation) -> Result { + self.journal.ensure_healthy()?; + let Some(commit) = self.journal.commit_for(prepared.command.id) else { + return Err(KernelError::CreationTargetOccupied); + }; + if commit.command != CommittedCommand::CreateWorld(prepared.command.clone()) + || !matches!(&commit.effect, WorldEffect::WorldCreated { .. }) + { + return Err(KernelError::CreationConflict); + } + CreationReceipt::from_commit(commit) + } + + #[cfg(test)] fn create( path: impl AsRef, input: CreateWorld, authenticated: &AuthenticatedCaller, ) -> Result<(Self, CreationReceipt), KernelError> { - let CallerId::Principal(authenticated_principal) = &authenticated.caller else { - return Err(KernelError::AuthenticationMismatch); - }; - validate_principal(&input.owner)?; - if &input.owner != authenticated_principal { - return Err(KernelError::AuthenticationMismatch); - } - let canonical_subjects = canonicalize_subjects(&input.subjects)?; - let title = normalize_title(&input.title)?; - let creation_digest = digest(&input)?; - let (journal, state) = match journal::WorldJournal::open_for_creation( - path.as_ref(), - input.id, - &creation_digest, - )? { - journal::CreationOpen::Existing { journal, state } => (journal, state), - journal::CreationOpen::Empty(empty) => { - let world_id = WorldId::issue(); - let caller = CallerId::Principal(input.owner.clone()); - let effect = issue_genesis(input.owner, title, canonical_subjects); - let mut state = WorldState::genesis(world_id, &caller, &effect)?; - let mut genesis = WorldCommit { - schema: COMMIT_SCHEMA.into(), - world_id, - command_id: input.id, - command_digest: creation_digest, - previous_revision: None, - resulting_revision: 0, - previous_state_digest: None, - resulting_state_digest: state.state_digest.clone(), - previous_commit_digest: None, - caller, - effect, - committed_at: Utc::now(), - digest: String::new(), - }; - genesis.digest = commit_digest(&genesis)?; - state.last_commit_digest = Some(genesis.digest.clone()); - let journal = empty.initialize(&state, &genesis)?; - (journal, state) + let prepared = prepare_creation(input, authenticated)?; + match journal::WorldJournal::open_owner(path.as_ref())? { + journal::JournalOpen::Empty(empty) => Self::initialize(empty, prepared), + journal::JournalOpen::Live { journal, state } => { + let kernel = Self { state, journal }; + let receipt = kernel.retry_creation(&prepared)?; + Ok((kernel, receipt)) } - }; - let receipt = journal - .commit_for(input.id) - .ok_or_else(|| KernelError::Invariant("world genesis receipt is missing".into())) - .and_then(CreationReceipt::from_commit)?; - Ok((Self { state, journal }, receipt)) + } } + #[cfg(test)] fn open(path: impl AsRef, expected_world_id: WorldId) -> Result { let (journal, state) = journal::WorldJournal::open(path.as_ref(), expected_world_id)?; Ok(Self { state, journal }) @@ -641,9 +747,8 @@ impl WorldKernel { if command.caller != authenticated.caller { return Err(KernelError::AuthenticationMismatch); } - let command_digest = digest(&command)?; if let Some(commit) = self.committed_command(command.id) { - return if commit.command_digest == command_digest { + return if commit.command == CommittedCommand::WorldCommand(command.clone()) { Ok(SubmitReceipt::AlreadyApplied(CommitReceipt::from(commit))) } else { Err(KernelError::CommandIdConflict) @@ -656,9 +761,7 @@ impl WorldKernel { }); } - let Reduction::Apply(effect) = reduce(&self.state, &command)? else { - return Ok(SubmitReceipt::NoEffect(snapshot(&self.state)?)); - }; + let effect = reduce(&self.state, &command)?; let mut candidate = self.state.clone(); apply_effect(&mut candidate, &command.caller, &effect)?; candidate.revision = candidate @@ -670,14 +773,12 @@ impl WorldKernel { let mut commit = WorldCommit { schema: COMMIT_SCHEMA.into(), world_id: self.state.world_id, - command_id: command.id, - command_digest, + command: CommittedCommand::WorldCommand(command), previous_revision: Some(self.state.revision), resulting_revision: candidate.revision, previous_state_digest: Some(self.state.state_digest.clone()), resulting_state_digest: candidate.state_digest.clone(), previous_commit_digest: self.state.last_commit_digest.clone(), - caller: command.caller, effect, committed_at, digest: String::new(), @@ -693,30 +794,62 @@ impl WorldKernel { fn committed_command(&self, command_id: CommandId) -> Option<&WorldCommit> { self.journal.commit_for(command_id) } -} -enum Reduction { - NoEffect, - Apply(WorldEffect), -} - -fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result { - match &command.body { - CommandBody::SetTitle { title } => { - require_owner(state, &command.caller)?; - require_phase(state, WorldPhase::Draft)?; - let title = normalize_title(title)?; - if title == state.title { - return Ok(Reduction::NoEffect); - } - if !state.draft_approvals.is_empty() { - return Err(KernelError::DraftLocked); - } - Ok(Reduction::Apply(WorldEffect::TitleChanged { - previous_title: state.title.clone(), - resulting_title: title, - })) + fn controller_receipt( + &self, + command_id: CommandId, + opportunity: &DecisionOpportunity, + invocation: &DecisionInvocation, + ) -> Result, KernelError> { + self.journal.ensure_healthy()?; + let Some(commit) = self.committed_command(command_id) else { + return Ok(None); + }; + let CommittedCommand::WorldCommand(CommandEnvelope { + body: + CommandBody::ExerciseDecision { + opportunity: committed_opportunity, + invocation: committed_invocation, + }, + .. + }) = &commit.command + else { + return Err(KernelError::CommandIdConflict); + }; + if committed_opportunity != opportunity || committed_invocation != invocation { + return Err(KernelError::CommandIdConflict); } + Ok(Some(CommitReceipt::from(commit))) + } + + fn controller_decline_receipt( + &self, + command_id: CommandId, + opportunity: &DecisionOpportunity, + ) -> Result, KernelError> { + self.journal.ensure_healthy()?; + let Some(commit) = self.committed_command(command_id) else { + return Ok(None); + }; + let CommittedCommand::WorldCommand(CommandEnvelope { + body: + CommandBody::DeclineDecision { + opportunity: committed_opportunity, + }, + .. + }) = &commit.command + else { + return Err(KernelError::CommandIdConflict); + }; + if committed_opportunity != opportunity { + return Err(KernelError::CommandIdConflict); + } + Ok(Some(CommitReceipt::from(commit))) + } +} + +fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result { + match &command.body { CommandBody::ApproveDraft => { require_phase(state, WorldPhase::Draft)?; let CallerId::Principal(principal) = &command.caller else { @@ -726,11 +859,11 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result { require_owner(state, &command.caller)?; @@ -742,7 +875,7 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result Result Result { + require_phase(state, WorldPhase::Active)?; + let current = exact_opportunity(state, opportunity)?; + let assignment = state + .controller_assignments + .get(¤t.scope) + .ok_or(KernelError::OpportunityMismatch)?; + if assignment.expected_caller() != command.caller { + return Err(KernelError::ControllerMismatch); + } + Ok(WorldEffect::DecisionDeclined { + opportunity: current, + }) } } } @@ -791,7 +938,7 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result Result { let WorldEffect::WorldCreated { @@ -804,20 +951,17 @@ impl WorldState { "genesis state requires a world-created effect".into(), )); }; - if caller != &CallerId::Principal(owner.clone()) { + validate_principal(&command.owner)?; + let expected_title = normalize_title(&command.title)?; + let expected_subjects = canonicalize_subjects(&command.subjects)?; + if owner != &command.owner + || title != &expected_title + || bindings.len() != expected_subjects.len() + { return Err(KernelError::Invariant( - "genesis creator does not match owner".into(), + "genesis effect does not match the admitted creation command".into(), )); } - validate_principal(owner)?; - if normalize_title(title)? != *title { - return Err(KernelError::Invariant( - "genesis title is not canonical".into(), - )); - } - if bindings.is_empty() { - return Err(KernelError::NoSubjects); - } let mut handles = BTreeSet::new(); let mut subjects = BTreeMap::new(); @@ -825,7 +969,23 @@ impl WorldState { let mut controller_ids = BTreeSet::new(); let mut grants = BTreeMap::new(); let mut scope_kinds = BTreeSet::new(); - for binding in bindings { + for (binding, expected) in bindings.iter().zip(&expected_subjects) { + let affordance_kinds: BTreeSet<_> = binding + .affordances + .values() + .map(|grant| grant.kind) + .collect(); + if binding.handle != expected.handle + || binding.subject.label != expected.label + || binding.subject.kind != expected.kind + || !assignment_matches_new(&binding.controller, &expected.controller) + || binding.affordances.len() != expected.affordances.len() + || affordance_kinds != expected.affordances + { + return Err(KernelError::Invariant( + "genesis binding does not derive from its creation subject".into(), + )); + } validate_handle(&binding.handle)?; if !handles.insert(binding.handle.clone()) { return Err(KernelError::DuplicateSubjectHandle); @@ -1113,20 +1273,12 @@ fn normalize_label(value: &str) -> Result { } } -fn normalize_speech(value: &str) -> Result { - let value = value.trim(); - if value.is_empty() { - Err(KernelError::EmptySpeech) - } else { - Ok(value.to_owned()) - } -} - -fn canonical_invocation(value: &DecisionInvocation) -> Result { +fn validated_invocation(value: &DecisionInvocation) -> Result { let action = match &value.action { - DecisionAction::Speak { text } => DecisionAction::Speak { - text: normalize_speech(text)?, - }, + DecisionAction::Speak { text } if text.trim().is_empty() => { + return Err(KernelError::EmptySpeech); + } + DecisionAction::Speak { text } => DecisionAction::Speak { text: text.clone() }, }; Ok(DecisionInvocation { affordance_id: value.affordance_id, @@ -1157,6 +1309,20 @@ fn validate_assignment(value: &ControllerAssignment) -> Result<(), KernelError> Ok(()) } +fn assignment_matches_new(assignment: &ControllerAssignment, expected: &NewController) -> bool { + match (assignment, expected) { + ( + ControllerAssignment::Human { principal, .. }, + NewController::Human { + principal: expected, + }, + ) => principal == expected, + (ControllerAssignment::NarrativePersona { .. }, NewController::NarrativePersona) + | (ControllerAssignment::OperationalAgent { .. }, NewController::OperationalAgent) => true, + _ => false, + } +} + fn apply_effect( state: &mut WorldState, caller: &CallerId, @@ -1168,23 +1334,6 @@ fn apply_effect( "world genesis cannot be applied as a mutable effect".into(), )); } - WorldEffect::TitleChanged { - previous_title, - resulting_title, - } => { - if caller != &CallerId::Principal(state.owner.clone()) - || state.phase != WorldPhase::Draft - || !state.draft_approvals.is_empty() - || &state.title != previous_title - || previous_title == resulting_title - || normalize_title(resulting_title)? != *resulting_title - { - return Err(KernelError::Invariant( - "title-change effect does not match canonical prior state".into(), - )); - } - state.title = resulting_title.clone(); - } WorldEffect::DraftApproved { principal } => { if state.phase != WorldPhase::Draft || caller != &CallerId::Principal(principal.clone()) @@ -1233,7 +1382,7 @@ fn apply_effect( .contains(&event.invocation.affordance_id) || grant.scope != current.scope || grant.kind != event.invocation.action.kind() - || canonical_invocation(&event.invocation)? != event.invocation + || validated_invocation(&event.invocation)? != event.invocation { return Err(KernelError::Invariant( "decision effect does not match exact opportunity authority".into(), @@ -1241,6 +1390,20 @@ fn apply_effect( } state.events.push(event.clone()); } + WorldEffect::DecisionDeclined { opportunity } => { + let current = exact_opportunity(state, opportunity)?; + let assignment = state + .controller_assignments + .get(¤t.scope) + .ok_or_else(|| { + KernelError::Invariant("decision scope lost its controller".into()) + })?; + if state.phase != WorldPhase::Active || caller != &assignment.expected_caller() { + return Err(KernelError::Invariant( + "decline effect does not match exact opportunity authority".into(), + )); + } + } } Ok(()) } @@ -1394,11 +1557,33 @@ mod tests { } } + #[test] + fn external_opportunities_reject_nested_authority_claims() { + let opportunity = DecisionOpportunity { + world_id: WorldId::issue(), + revision: 4, + state_digest: "sha256:fixture".into(), + scope: DecisionScope { + subject_id: SubjectId::issue(), + }, + controller_id: ControllerId::issue(), + controller_mode: ControllerMode::NarrativePersona, + affordance_ids: vec![AffordanceId::issue()], + }; + let mut nested = serde_json::to_value(&opportunity).unwrap(); + nested["scope"]["caller"] = serde_json::json!("legacy-owner"); + assert!(serde_json::from_value::(nested).is_err()); + + let mut outer = serde_json::to_value(&opportunity).unwrap(); + outer["callerId"] = serde_json::json!("legacy-controller"); + assert!(serde_json::from_value::(outer).is_err()); + } + #[test] fn draft_activation_player_and_autonomous_actions_share_one_reducer() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); - let (mut kernel, receipt) = WorldKernel::create( + let (mut kernel, _) = WorldKernel::create( &path, creation(CommandId::new(), " Delvehold "), &auth_principal(owner()), @@ -1407,7 +1592,6 @@ mod tests { let genesis = kernel.snapshot().unwrap(); assert_eq!(genesis.title, "Delvehold"); assert_eq!(genesis.phase, WorldPhase::Draft); - assert_eq!(receipt.subjects.len(), 3); assert!(genesis.opportunities.is_empty()); let active = activate(&mut kernel); @@ -1434,7 +1618,7 @@ mod tests { assert_eq!( after_player.events[0].invocation.action, DecisionAction::Speak { - text: "I open the door.".into() + text: " I open the door. ".into() } ); @@ -1497,9 +1681,7 @@ mod tests { &owner_approved, CommandId::new(), CallerId::Principal(player()), - CommandBody::SetTitle { - title: "Stolen".into() - }, + CommandBody::ActivateWorld, ), &auth_principal(player()) ), @@ -1511,13 +1693,11 @@ mod tests { &owner_approved, CommandId::new(), CallerId::Principal(owner()), - CommandBody::SetTitle { - title: "Late".into() - }, + CommandBody::ApproveDraft, ), &auth_principal(owner()) ), - Err(KernelError::DraftLocked) + Err(KernelError::DraftAlreadyApproved) )); assert_eq!(kernel.journal.commit_count(), 2); @@ -1686,7 +1866,167 @@ mod tests { } #[test] - fn no_effect_invalid_and_stale_commands_do_not_commit() { + fn controller_receipt_is_bound_to_the_exact_opportunity_and_invocation() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Receipt Scope"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let decision = opportunity(&active, ControllerMode::OperationalAgent); + let other = opportunity(&active, ControllerMode::NarrativePersona); + let command_id = CommandId::new(); + let caller = CallerId::Controller(decision.controller_id); + let invocation = speak(&decision, "The record is exact."); + kernel + .submit( + command( + &active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + invocation: invocation.clone(), + opportunity: decision.clone(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + let receipt = kernel + .controller_receipt(command_id, &decision, &invocation) + .unwrap() + .expect("committed controller command has a receipt"); + assert_eq!(receipt.command_id, command_id); + assert!( + kernel + .controller_receipt(CommandId::new(), &decision, &invocation) + .unwrap() + .is_none() + ); + assert!(matches!( + kernel.controller_receipt(command_id, &other, &invocation), + Err(KernelError::CommandIdConflict) + )); + let altered_invocation = speak(&decision, "A different proposal."); + assert!(matches!( + kernel.controller_receipt(command_id, &decision, &altered_invocation), + Err(KernelError::CommandIdConflict) + )); + } + + #[test] + fn controller_decline_consumes_only_its_exact_opportunity() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Decline Scope"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let decision = opportunity(&active, ControllerMode::OperationalAgent); + let other = opportunity(&active, ControllerMode::NarrativePersona); + let caller = CallerId::Controller(decision.controller_id); + + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Controller(other.controller_id), + CommandBody::DeclineDecision { + opportunity: decision.clone(), + }, + ), + &AuthenticatedCaller::fixture(CallerId::Controller(other.controller_id)), + ), + Err(KernelError::ControllerMismatch) + )); + assert_eq!(kernel.snapshot().unwrap(), active); + + let command_id = CommandId::new(); + let decline = command( + &active, + command_id, + caller.clone(), + CommandBody::DeclineDecision { + opportunity: decision.clone(), + }, + ); + let SubmitReceipt::Applied(receipt) = kernel + .submit( + decline.clone(), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap() + else { + panic!("exact decline was not applied") + }; + let after = kernel.snapshot().unwrap(); + assert_eq!(after.revision, active.revision + 1); + assert!(after.events.is_empty()); + let refreshed = opportunity(&after, ControllerMode::OperationalAgent); + assert_ne!(refreshed, decision); + assert_eq!( + kernel + .controller_decline_receipt(command_id, &decision) + .unwrap(), + Some(receipt.clone()) + ); + assert!(matches!( + kernel.controller_decline_receipt(command_id, &other), + Err(KernelError::CommandIdConflict) + )); + assert!(matches!( + kernel.controller_receipt( + command_id, + &decision, + &speak(&decision, "A decline is not speech."), + ), + Err(KernelError::CommandIdConflict) + )); + assert_eq!( + kernel + .submit(decline, &AuthenticatedCaller::fixture(caller.clone())) + .unwrap(), + SubmitReceipt::AlreadyApplied(receipt.clone()) + ); + assert!(matches!( + kernel.submit( + command( + &after, + CommandId::new(), + caller.clone(), + CommandBody::DeclineDecision { + opportunity: decision, + }, + ), + &AuthenticatedCaller::fixture(caller), + ), + Err(KernelError::OpportunityMismatch) + )); + assert_eq!(kernel.snapshot().unwrap(), after); + drop(kernel); + let reopened = WorldKernel::open(&path, after.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), after); + assert_eq!( + reopened + .controller_decline_receipt( + command_id, + &opportunity(&active, ControllerMode::OperationalAgent), + ) + .unwrap(), + Some(receipt) + ); + } + + #[test] + fn duplicate_and_stale_commands_do_not_commit() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( @@ -1697,45 +2037,27 @@ mod tests { .unwrap(); let genesis = kernel.snapshot().unwrap(); assert!(matches!( - submit_owner( - &mut kernel, - &genesis, - CommandBody::SetTitle { - title: " Still ".into() - } - ), - SubmitReceipt::NoEffect(_) + submit_owner(&mut kernel, &genesis, CommandBody::ApproveDraft), + SubmitReceipt::Applied(_) )); + let after = kernel.snapshot().unwrap(); assert!(matches!( kernel.submit( command( - &genesis, + &after, CommandId::new(), CallerId::Principal(owner()), - CommandBody::SetTitle { title: " ".into() }, + CommandBody::ApproveDraft, ), &auth_principal(owner()) ), - Err(KernelError::EmptyTitle) + Err(KernelError::DraftAlreadyApproved) )); - assert_eq!(kernel.snapshot().unwrap(), genesis); - assert_eq!(kernel.journal.commit_count(), 1); - - submit_owner( - &mut kernel, - &genesis, - CommandBody::SetTitle { - title: "Changed".into(), - }, - ); - let after = kernel.snapshot().unwrap(); let stale = command( &genesis, CommandId::new(), CallerId::Principal(owner()), - CommandBody::SetTitle { - title: "Stale".into(), - }, + CommandBody::ApproveDraft, ); assert!(matches!( kernel.submit(stale, &auth_principal(owner())), @@ -1761,17 +2083,23 @@ mod tests { &genesis, id, CallerId::Principal(owner()), - CommandBody::SetTitle { title: "B".into() }, + CommandBody::ApproveDraft, ); let first_receipt = kernel .submit(first.clone(), &auth_principal(owner())) .unwrap(); let second_snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &second_snapshot, - CommandBody::SetTitle { title: "C".into() }, - ); + kernel + .submit( + command( + &second_snapshot, + CommandId::new(), + CallerId::Principal(player()), + CommandBody::ApproveDraft, + ), + &auth_principal(player()), + ) + .unwrap(); let after_second = kernel.snapshot().unwrap(); assert_eq!( kernel.submit(first, &auth_principal(owner())).unwrap(), @@ -1784,9 +2112,7 @@ mod tests { &genesis, id, CallerId::Principal(owner()), - CommandBody::SetTitle { - title: "Different".into(), - }, + CommandBody::ActivateWorld, ); assert!(matches!( kernel.submit(conflict, &auth_principal(owner())), @@ -1795,6 +2121,30 @@ mod tests { assert_eq!(kernel.snapshot().unwrap(), after_second); } + #[test] + fn creation_retry_is_bound_to_the_exact_raw_command() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let id = CommandId::new(); + let raw = creation(id, " Canonical Result "); + let (kernel, first) = + WorldKernel::create(&path, raw.clone(), &auth_principal(owner())).unwrap(); + assert_eq!(kernel.snapshot().unwrap().title, "Canonical Result"); + drop(kernel); + + let (kernel, retry) = + WorldKernel::create(&path, raw.clone(), &auth_principal(owner())).unwrap(); + assert_eq!(retry, first); + drop(kernel); + + let mut merely_equivalent = raw; + merely_equivalent.title = "Canonical Result".into(); + assert!(matches!( + WorldKernel::create(&path, merely_equivalent, &auth_principal(owner())), + Err(KernelError::CreationConflict) + )); + } + #[test] fn invalid_seed_never_allocates_a_world() { let dir = tempfile::tempdir().unwrap(); @@ -1856,9 +2206,7 @@ mod tests { &genesis, uncertain, CallerId::Principal(owner()), - CommandBody::SetTitle { - title: "Durably changed".into(), - }, + CommandBody::ApproveDraft, ); kernel.journal.fail_after_durable_commit_for_test(); assert!(matches!( @@ -1874,7 +2222,7 @@ mod tests { let mut reopened = WorldKernel::open(&path, genesis.world_id).unwrap(); let durable = reopened.snapshot().unwrap(); assert_eq!(durable.revision, 1); - assert_eq!(durable.title, "Durably changed"); + assert_eq!(durable.draft_approvals, BTreeSet::from([owner()])); assert!(matches!( reopened .submit(attempted, &auth_principal(owner())) @@ -1883,6 +2231,33 @@ mod tests { )); } + #[test] + fn lost_genesis_ack_reopens_as_the_same_world_and_exact_receipt() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let command_id = CommandId::new(); + let input = creation(command_id, "Durable Genesis"); + let authenticated = auth_principal(owner()); + let mut empty = match journal::WorldJournal::open_owner(&path).unwrap() { + journal::JournalOpen::Empty(empty) => empty, + journal::JournalOpen::Live { .. } => panic!("fixture store must be empty"), + }; + empty.fail_after_durable_initialize_for_test(); + let prepared = prepare_creation(input.clone(), &authenticated).unwrap(); + assert!(matches!( + WorldKernel::initialize(empty, prepared), + Err(KernelError::RecoveryRequired { command_id: uncertain }) + if uncertain == command_id + )); + + let (reopened, receipt) = WorldKernel::create(&path, input, &authenticated).unwrap(); + let snapshot = reopened.snapshot().unwrap(); + assert_eq!(receipt.command_id, command_id); + assert_eq!(receipt.world_id, snapshot.world_id); + assert_eq!(snapshot.revision, 0); + assert_eq!(snapshot.title, "Durable Genesis"); + } + #[test] fn replacing_the_store_path_revokes_the_live_owner() { let dir = tempfile::tempdir().unwrap(); @@ -1904,9 +2279,7 @@ mod tests { &snapshot, CommandId::new(), CallerId::Principal(owner()), - CommandBody::SetTitle { - title: "Detached".into() - }, + CommandBody::ApproveDraft, ), &auth_principal(owner()) ), @@ -1935,9 +2308,7 @@ mod tests { &snapshot, CommandId::new(), CallerId::Principal(player()), - CommandBody::SetTitle { - title: "Stolen".into(), - }, + CommandBody::ApproveDraft, ); assert!(matches!( kernel.submit(forged, &auth_principal(owner())), diff --git a/crates/ghostlight-persona-projection/src/lib.rs b/crates/ghostlight-persona-projection/src/lib.rs index 9073705..eff769a 100644 --- a/crates/ghostlight-persona-projection/src/lib.rs +++ b/crates/ghostlight-persona-projection/src/lib.rs @@ -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!( - "\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(deserializer: D) -> Result + 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) -> 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, + source_digest: impl Into, + receipt_digest: impl Into, + ) -> Result { + 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 InterpretationAccumulator { } } -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("