Compare commits

..
Author SHA1 Message Date
Meta Vens
06b37618ce Publish Ghostlight provider respect to Odin 2026-06-23 23:31:04 +01:00
Meta Vens
96b8edfc49 Add Ghostlight provider advertisement witness 2026-06-03 03:46:23 +01:00
Meta Vens
c163b4ca80 Map Ghostlight Verse service surface 2026-06-02 18:49:47 +01:00
Meta Vens
a1ec7ace5d Adopt shared PersonaState contract 2026-05-29 16:09:25 +01:00
Meta Vens
c48dac69a6 Bridge Ghostlight scene initiative to Epiphany heartbeat 2026-05-06 14:33:58 +01:00
463 changed files with 55319 additions and 134010 deletions

18
.gitignore vendored
View file

@ -1,14 +1,6 @@
__pycache__/
*.pyc
.venv/
node_modules/ node_modules/
sidecar/claude-sdk/dist/ state/scratch-compaction-*.md
target/ experiments/images/
# Disposable local scaffolding. These accumulated to ~87MB of untracked debris
# once; the workspace must stay re-enterable, so they never come back.
.tmp-*
/tmp/
--help
--help.lock
/acceptance-run*
# Claude Code agent worktrees (Hands/Soul isolation); never source
.claude/worktrees/

3
.gitmodules vendored Normal file
View file

@ -0,0 +1,3 @@
[submodule "vendor/cultcache-py"]
path = vendor/cultcache-py
url = https://github.com/GameCult/cultcache-py.git

273
AGENTS.md
View file

@ -2,106 +2,201 @@
## Project Purpose ## Project Purpose
Ghostlight is a Rust world kernel and the play daemon built on it. Models Ghostlight is a research and implementation home for socially persistent
propose; the kernel admits or refuses. The same kernel is meant to run the generative agents. The core problem is not "make an LLM sound like a person."
simulation behind Aetheria's public story, a persistent cast and storylets, as The core problem is building an architecture where personality, culture,
well as Ghostlight Dungeon, the single-player DM-led client (parked at memory, masks, perception, and incentives can actually survive contact with
tag `parked/ghostlight-eve-surface`). `README.md` says time, relationships, routine, tonal variation, and pressure.
what exists today and what does not.
## Where State Lives This repo exists so those organs can live somewhere cleaner than a side chamber
inside another project.
- Campaign state (targets, rulings, cut specs, reports, verdicts, findings, ## Canonical State
follow-ups) lives in the Eureka mind, not in this repo. The current campaign
is `ghostlight-verse`; query it through the `eureka-state` tools.
- `notes/ghostlight-verse-target.md` and `notes/ghostlight-verse-map.md` are the
campaign's prose target and map. Read the map for probed body facts.
- This repo has no state directory, no state CLI, and no evidence ledger. Do not
create one. History belongs in git; durable decisions belong in the mind.
- `notes/fresh-workspace-handoff.md` is a pointer: what runs, how it deploys,
where open work is queried.
- Dated cut documents and postmortems (`docs/architecture/*-cut.md`,
`*-postmortem.md`) are history. Do not edit them, including their old paths.
## Invariants - Treat `state/ghostlight-state.cultcache.jsonl` as the CultCache-backed
persistence spine for machine-managed state records that have migrated.
- Treat `state/map.yaml` as the canonical human-readable project map.
- Treat `state/scratch.md` as disposable working memory for one bounded
subgoal.
- Treat `state/evidence.jsonl` and `state/branches.json` as readable export
surfaces during the persistence migration, not as the long-term direct-write
API.
- Treat `state/evidence.jsonl` as the distilled durable ledger of what was
learned, verified, rejected, or accepted.
- Treat `notes/ghostlight-implementation-plan.md` as the current implementation
plan for the larger organs.
- Update `state/map.yaml` when project understanding changes.
- Add evidence after meaningful research, implementation, verification, or
rejected paths, but keep it distilled. Routine "I just did this" proof
belongs in git history, commits, smoke artifacts, or targeted logs unless it
changes what the next session should believe.
- Do not turn notes, map, handoff, and evidence into four versions of the same
brain. Distinct jobs or bust.
- **The kernel decides.** The kernel owns world state through its closed ## Important Paths
operation set. Models, tools, controllers, and consumers produce proposals
only. No code outside the kernel commits world state, and no compatibility
writer exists.
- **The library is sealed.** `crates/ghostlight` exposes create/open,
immutable snapshots, command submission, typed receipts, and the runner and
port entry points. Do not publish mutable world types, an ID issuer, a reducer
entry, or a journal handle for the convenience of tests or adapters. The seal
is proven by the `compile_fail` doc-tests in `crates/ghostlight/src/lib.rs`
and by `crates/ghostlight/tests/external_admission.rs`; keep both passing and
extend them when the public surface changes.
- **Every commit is a command.** Everything enters through the mailbox
(`crates/ghostlight/src/mailbox.rs`) as a command. Do not append a commit when
reduction produces no canonical mutation.
- **A Persona never sees structured state.** Persona turns are prose; an
Interpreter lowers them to typed proposals, and anything it cannot lower
becomes a recorded gap, not invented state.
- **Typed state.** Runtime documents are CultCache `.cc`. JSON is for schema
publication and boundaries with other systems.
- **Credentials.** Ghostlight never reads, copies, forwards, or logs a model
credential. A consumer never restates a foreign owner's document shape as its
own strict struct; read the owner's published contract and test against the
real counterpart.
- **Canon flows one way.** Simulation output never writes back into AetheriaLore
or Aetheria's catalog without operator review.
## Where Things Are - Project root: `E:\Projects\Ghostlight`
- Canonical map: `E:\Projects\Ghostlight\state\map.yaml`
- Scratch surface: `E:\Projects\Ghostlight\state\scratch.md`
- Distilled evidence ledger: `E:\Projects\Ghostlight\state\evidence.jsonl`
- Branch ledger: `E:\Projects\Ghostlight\state\branches.json`
- Handoff summary: `E:\Projects\Ghostlight\notes\fresh-workspace-handoff.md`
- System map: `E:\Projects\Ghostlight\notes\ghostlight-current-system-map.md`
- Implementation plan: `E:\Projects\Ghostlight\notes\ghostlight-implementation-plan.md`
- Architecture rationale: `E:\Projects\Ghostlight\notes\architecture-rationale.md`
- State CLI: `E:\Projects\Ghostlight\tools\ghostlight_state.py`
- CultCache state seam: `E:\Projects\Ghostlight\tools\ghostlight_state_store.py`
- CultCache-Py submodule: `E:\Projects\Ghostlight\vendor\cultcache-py`
- CultCache state store: `E:\Projects\Ghostlight\state\ghostlight-state.cultcache.jsonl`
- Pre-compaction helper: `E:\Projects\Ghostlight\tools\ghostlight_prepare_compaction.py`
- Kernel: `crates/ghostlight/src/`. Its vocabulary and current mechanism: ## Useful Commands
`docs/architecture/ghostlight-world-ontology.md`. The consumer contract:
`docs/architecture/ghostlight-world-consumer-api.md`.
- Parked Dungeon (daemon, play table, Eve surface, browser host, Idunn recipe):
tag `parked/ghostlight-eve-surface`; not on main.
- Persona membrane: `crates/ghostlight-persona-projection/src/lib.rs`.
- Claude SDK sidecar: `sidecar/claude-sdk/`.
- Architecture rationale (the parked Dungeon's): `docs/architecture/ghostlight-dungeon-mvp.md`.
`notes/ghostlight-implementation-plan.md` is the historical plan of the 2026-09
rebuild, not the current plan.
## Build, Verify, Deploy Use the bundled Python runtime if `python` is not on PATH:
Nothing deploys from this repo: the Idunn target `ghostlight` is braked and stopped (deployment and ```powershell
lifecycle brakes engaged, unit stopped; retirement waits on npm run state:status
`ghostlight-verse:follow_up:idunn-v2-target-retirement`) and no recipe exists on main. Kernel and verse tests run on Linux on Yggdrasil (the npm run state:prepare-compaction
`ygg-verify` stopgap), not on the workstation; a Windows compile is not evidence & 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' add-evidence --type research --status ok --note '...'
about Linux, so say which host you used. Do not run `idunn up ghostlight`. & 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' add-branch --id branch-id --hypothesis '...'
```
For infrastructure, SSH, Idunn, Odin, or Heimdall work, consult ## Session Bootstrap And Re-entry Protocol
`F:\Projects\gamecult-ops` before acting.
On fresh session load, do this before wandering off into implementation:
1. read:
- `state/map.yaml`
- `notes/fresh-workspace-handoff.md`
- `notes/ghostlight-current-system-map.md`
- `notes/ghostlight-implementation-plan.md`
2. run:
- `npm run state:status`
3. restate the current next action from the persisted state before starting
edits
4. if the user only asked to rehydrate or reorient, stop after orientation and
wait for an explicit continue instruction instead of treating the persisted
next action as permission to start coding
After compaction, resume, or suspicious continuity loss:
1. rerun `npm run state:status`
2. reread `state/map.yaml` and `notes/fresh-workspace-handoff.md`
3. treat the persisted next action as authoritative unless fresh repo evidence
contradicts it
When context pressure is clearly rising:
1. stop broad exploration
2. narrow the active move to one bounded organ
3. persist map or handoff updates, plus distilled evidence only when the lesson
changes future belief, before the blackout lands
When the user says to prepare for imminent compaction:
1. immediately write hot live context from memory into a new
`state/scratch-compaction-<guid>.md` file before reading files, running
status checks, or doing tidy persistence work
2. run `tools/ghostlight_prepare_compaction.py` before editing persistence
surfaces
3. use its warnings as the checklist for map, handoff, scratch, evidence, and
git hygiene
4. update only the state that actually needs to change
5. after hot context has been folded into canonical persisted state, delete the
`state/scratch-compaction-<guid>.md` file so stale emergency memory does not
linger
6. run `tools/ghostlight_prepare_compaction.py` again after edits and scratch
cleanup
7. fix errors, address warnings, and commit the completed persistence pass
unless the work is deliberately mid-surgery
## Operating Discipline ## Operating Discipline
- Restate the current mechanism and intended change before substantial edits. - Steward persistent state as part of the work. If a lesson changes future
Prefer one clear hypothesis per iteration. behavior, update the smallest correct memory surface before moving on; if a
- Verify with checks that reflect the real goal, not proxy success. Revert memory surface is stale, duplicated, or making re-entry slower, cut or
changes that do not clearly improve the target. consolidate it.
- If the diff grows while understanding shrinks, stop and diagnose. - Before substantial edits, restate the current mechanism and intended change.
- Delete obsolete authority before adding a new path. Do not keep an old writer - Prefer one clear hypothesis per iteration.
alive behind a shim. - Verify with checks that reflect the real goal, not just proxy success.
- Commit completed work and push it. Merge, confirm the tip by SHA, then delete - Revert or discard changes that do not clearly improve the target.
the branch; push only after reading the test result line. - If the diff grows while understanding shrinks, stop implementation and switch
- In documentation, describe the live system and the current rule directly. No to diagnosis.
claim of capability without a file that implements it. Keep rejected history - Keep maps and prose together; do not replace useful maps with prose-only
short and decision-relevant, or leave it in git. explanations.
- Commit completed work before it rots in the worktree unless the task is
deliberately mid-surgery or the user asked to leave changes uncommitted.
- Push after major completed passes when a remote exists, unless the user asked
not to or there is a concrete reason to keep the commit local for a moment.
- Before handoff, compaction, or phase boundaries, sync `state/map.yaml`, add
distilled evidence when the lesson changes future belief, refresh
`notes/fresh-workspace-handoff.md`, and make the next action explicit.
- Treat `state/map.yaml` as a working memory map, not an archive. Preserve
current mission, live seams, boundaries, and next action; let git history,
evidence, and artifact files carry chronology.
- In documentation, describe the live system and current rule directly. Do not
write victory laps, scar tours, clever autopsies, or contrastive little
boasts about what the project no longer does. If a sentence congratulates the
design for not being a previous wrong design, cut it or rewrite it as a plain
current rule. If rejected history matters, keep it short, explicit, and
decision-relevant; otherwise cut it. The docs are not a trophy case for
yesterday's wrong machine.
## Aetheria Grounding ## Aetheria Grounding Doctrine
- Before writing or generating Aetheria material, check AetheriaLore for the - Before writing or generating Aetheria scenes, check AetheriaLore for the
factions, institutions, species or body types, location, and time period factions, movements, institutions, species or body types, location, and time
involved. Ground detail in the source's material facts: habitat, law, money, period involved.
route access, surveillance, communication channels, and local failure costs. - Before drafting story prose, choose an intentional tonal mode or blend for the
- If the source is too vague for a concrete detail, do not bluff. Mark the gap scene. Aetheria should support wit-with-stakes, warmth, absurdity, domestic
and propose a narrow elaboration for AetheriaLore, subject to operator review. texture, ritual quiet, wonder, horror, noir, dour poetry, and dry systems
- Choose a tonal mode on purpose. Aetheria supports wit with stakes, warmth, prose as needed. Do not default to constant crisis or procedural severity.
absurdity, domestic texture, ritual quiet, wonder, horror, noir, and dry - Use Adams/Pratchett-style comic precision and humane levity as a useful
systems prose; do not default to constant crisis. Comic precision in the default touchstone when no stronger scene-specific style is called for:
Adams/Pratchett manner is a good default, where jokes reveal stakes instead of jokes and absurdity should reveal stakes, not dissolve them.
dissolving them. - Establish ordinary life before interruption when the fixture calls for it:
- Establish ordinary life before interruption: routines, work, relationships, routines, work texture, relationships, private jokes, rituals, small desires,
small desires, and local accommodations are worldbuilding, not filler. and local accommodations are part of worldbuilding, not filler.
- For illustrated Ink fixtures, segment prose into click-through visual
sections. Distinct places, focal areas, object closeups, arrivals, alarms,
pivotal one-sentence beats, and aftermath states need stable visual scene ids
and imagegen-ready prompts.
- Treat visual artifacts as illustrated replay and website collateral, not core
social-model training signal. Visual review judges the playable Ink
experience plus the visual plan, not clean-run prose receipts.
- Write visual prompts for a general image model, not a lore expert. Explain
fictional objects and body affordances in visible terms: geometry, materials,
lighting, stance, interfaces, tools, supports, cables, fluids, screens, and
crowd positions.
- Do the same for environments. A location label like "manifold line," "cavity
yard," "supervisor glass," or "anchor rail" is not a drawable scene until the
prompt describes its visible geometry, materials, interfaces, lights, and
scale.
- If a fixture has a target visual style, store that style cue once in the
sidecar and include it in every assembled image prompt. Do not rely on memory
or unstated website context to carry the look.
- Do not treat a character name as a visual description. Illustrated fixtures
need stable character visual refs for every recurring named character, and
scene prompts should either include those refs during prompt assembly or carry
enough appearance detail to stand alone.
- Include visual character refs only for characters actually visible in the
rendered frame. Do not feed imagegen refs for absent, off-frame, merely
mentioned, or object-represented characters.
- Treat visual continuity notes as tool/reviewer constraints, not prompt text.
If imagegen needs the fact, rewrite it as concrete visible description in the
base prompt, character ref, or branch/state modifier.
- Treat generated environment images as concept and material reference, not
spatial truth. Multi-angle or branch-consistent illustrated IF needs a durable
scene-set source such as a hand-built blockout, procedural scene file, layout
asset, or camera map. Imagegen can paint over camera-specific visual input;
it should not be asked to preserve room topology from a prior generated
image or text memory.
- Ground scene writing in the source's material details: habitat form,
infrastructure, law, class pressure, money, route access, surveillance,
communication channels, body affordances, and local failure costs.
- If the source is too vague for a concrete scene detail, do not bluff. Mark
the lore gap, patch the AetheriaLore source with a narrow elaboration, then
regenerate or revise the Ghostlight artifact from that patched source.
- Treat this as part of data generation. Ghostlight is expected to stress-test
Aetheria at room scale, find missing granularity, and push useful
elaborations back into the lore vault.

View file

@ -1,3 +0,0 @@
Repository doctrine for this project lives in AGENTS.md, shared with Codex.
@AGENTS.md

2779
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,41 +0,0 @@
[workspace]
members = [
"crates/ghostlight",
"crates/ghostlight-dungeon",
"crates/ghostlight-persona-projection",
"crates/ghostlight-verse",
]
resolver = "2"
[workspace.package]
edition = "2024"
license = "MIT"
version = "0.1.0"
[workspace.dependencies]
anyhow = "1"
aes-gcm = "0.10"
async-trait = "0.1"
async-stream = "0.3"
axum = { version = "0.8", features = ["macros"] }
chrono = { version = "0.4", features = ["serde"] }
base64 = "0.22"
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5" }
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" }
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultnet-rs" }
cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultmesh-rs" }
jsonwebtoken = "9"
hmac = "0.12"
rand = "0.9"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }
rmp-serde = "1.3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
thiserror = "2"
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
unicode-segmentation = "1"
uuid = { version = "1", features = ["v4", "serde"] }
zeroize = "1.8"

226
README.md
View file

@ -1,121 +1,151 @@
# Ghostlight # Ghostlight
**Ghostlight is a world kernel: typed world state that a language model can Ghostlight is a research and implementation home for socially persistent
propose changes to and can never write.** The valuable part is generative agents.
`crates/ghostlight`. The Dungeon game, one client of it, is parked (below).
**The thesis.** World state is typed documents. Every change to it, and every The project is about characters and simulated people who remain coherent across
narrative dependency on it, is an operation in a closed, predefined algebra. time, routine, pressure, memory, culture, misreading, masks, incentives, and
Models propose operations; the kernel checks each against the state (references, changing relationships. The aim is not to make a language model sound charming
preconditions, authority, conservation, who knows what) and admits it or refuses for one scene. The aim is to build machinery that can track who someone is,
it with the complete list of mismatches. Narration describes only what was what they believe, what they hide, how they see other people, how they live when
committed. A model-as-game-master holds the world in a context window and nothing is exploding, and how their behavior changes when the world leans on
drifts; here the world is a digest-chained journal that survives restarts and them.
cannot be talked into contradicting itself.
**Use it as a structured state backend.** Do not judge it by the parked Dungeon's In practical terms, Ghostlight is building the state and projection layer for
prose. The kernel is a library; prose comes from whichever model you plug into character-driven generation:
its ports.
- `crates/ghostlight`: the sealed library. A consumer gets create/open - durable canonical character state
(`WorldMailbox::open`, `create`), immutable snapshots (`snapshot`), command - observer-specific perceived state
submission through role-scoped ports (`PlayPort`, `ConsumerPort`, - directional relationship stance
`ControllerPort`, `SeedPort`), typed receipts, and the runner and inference-port - cultural and institutional pressure
entry points (`ControllerRunner`, `ElaborationRunner`, `SeedRunner`, - memory and goal selection
`InferencePort`). Mutable state, ID issuers, the reducer and the journal - speaker-local prompt projection
writer are not public. `compile_fail` doc-tests in `crates/ghostlight/src/lib.rs` - evaluation targets for emergent verbal behavior
and `crates/ghostlight/tests/external_admission.rs` prove the seal. - a future path for training smaller specialist projection models
- `docs/architecture/ghostlight-world-ontology.md`: the vocabulary (subjects,
places, routes, holdings, knowledge, commitments, pressures), the operation
algebra, and what the reducer checks.
- `docs/architecture/ghostlight-world-consumer-api.md`: the contract for a
program that reads a world and proposes changes to the characters it controls
(`POST /cultnet/world-patch`; no process on main serves that door, a host serves
`ghostlight::admit_document`).
Start with those two documents, then `cargo doc -p ghostlight --open`. The first concrete consumer is Aetheria authoring support, especially Call of
the Void content generation, dialogue scaffolding, and procedural drama for
narrated stories in the Aetheria timeline.
**Populate the algebra first.** The kernel owns the component operations; a world owns its ## Core Idea
affordance catalog, the verbs its actors can attempt. A fresh world knows one: the built-in
Speak, which records an utterance and changes nothing. Until your world declares affordances
(at genesis, by patch, or through elaborators) for moving, trading, taking, deciding and so on,
every intent a model voices lowers to speech or to a recorded gap, and the prose built on that
will be thin no matter how good the model is. The Aetheria verse genesis
(`crates/ghostlight/src/verse/genesis.rs`) declares its grammar's verbs, and today they still
only record the act; their effects are the next phase.
## Elaborators Ghostlight separates three things that are easy to blur together:
An elaborator is a model session, confined to one jurisdiction of the world, that 1. **Canonical state**
adds structure where the world is thin: it answers a derived causal boundary What is true about a character, relationship, event, memory, or scene.
(a destination nobody has described yet) or a scale deficit with typed
declarations, and the kernel verifies the result like any other patch. Sessions
are resumable and checkpointed against committed history. Eight stock lenses
(`crates/ghostlight/src/lens.rs`: patina, charter, ledger, hearth, tangle, veil,
ember, numen) give each session a role-specific emphasis, for example customs and
local jokes, or money and ledgers. A lens changes the prompt only, never what the
kernel admits. Because boundaries are derived from state, elaborators can be
dispatched as the player approaches a place or a social structure, instead of
authoring the world up front.
## Direction (planned, not built) 2. **Perceived state**
What a particular observer thinks is true, including misreadings,
attribution bias, suspicion, trust, projection, and partial knowledge.
Use the kernel to simulate a whole world with many kinds of actor: Aetheria's 3. **Prompt projection**
factions and a persistent cast whose members keep identity, memory and A temporary speaker-local prompt surface for one scene or turn.
commitments across sessions. Newspaper-staff simulations before the 2026-08
teardown are the earlier proof of the idea; that code is in git history, not in
the tree. Running this at scale is gated by inference cost, not by the design.
`crates/ghostlight-verse` is the first slice: `ghostlight-verse genesis` creates
an Aetheria verse world from the Aetheria catalog and `ghostlight-verse run`
advances it a number of ticks under a token cap, reporting per tick what each
faction did and what it cost. Nothing loads AetheriaLore prose, models
storylets, or produces episodes yet. Targets: `notes/ghostlight-verse-target.md`.
## Ghostlight Dungeon (parked) The prompt is not the character. The prompt is a rendered slice of state.
The single-player, DM-led client and its daemon, Eve play surface and browser That distinction matters because believable dialogue should come from character
host are parked at tag `parked/ghostlight-eve-surface`. Nothing is deployed and circumstance, not vibes. Sometimes that circumstance is acute pressure. Often it
nothing on main serves HTTP. The Dungeon returns when Thing 2 gives it a UI is habit, boredom, affection, work rhythm, class embarrassment, ritual memory,
(follow-up `dungeon-ui-on-thing2`); the rebuild starts from the tag. professional competence, petty irritation, or ordinary warmth trying to survive
inside a bleak system. Cat being sarcastic should fall out of shame sensitivity,
distance seeking, suspicion, relationship tension, scene stakes, and voice.
Oz withholding information should fall out of mask rigidity, privacy pressure,
relationship fear, and the need to stay useful. A quiet joke, a domestic aside,
or a moment of tenderness should be just as explainable in state terms as a
threat. The system should be able to show its work without making every scene
sound like Greg Egan having a panic attack in a server closet.
## Repo map ## Current Status
| Path | What it is | Ghostlight is early architecture plus executable schema seams.
|---|---|
| `crates/ghostlight/` | The sealed kernel library. |
| `crates/ghostlight-persona-projection/` | Membrane between structured state and a prose-only Persona. |
| `crates/ghostlight-verse/` | The `ghostlight-verse` operator command line (`genesis`, `run`). |
| `sidecar/claude-sdk/` | Node process serving `claude`-prefixed models to the kernel; a stopgap for a direct Messages API port. |
| `AGENTS.md` | Invariants and where things are. |
| `docs/architecture/ghostlight-dungeon-mvp.md` | The parked Dungeon's authority architecture (design record). |
| `notes/` | The verse campaign's target and map, the handoff pointer, local smoke notes. |
`docs/public-architecture/`, `docs/articles/` and `docs/product/` are design Currently present:
essays and proposals from before the rebuild. They describe organs (campaigns,
co-op, Nemesis, newspapers) that are not in `crates/`; they do not describe the
running machine. Pages ending in `-cut.md` or `-postmortem.md` are dated history.
## Build and test - v0 canonical agent-state schema
- required variable lists for state families and relationship stance
- Call of the Void-flavored Cat/Oz fixture
- dependency-free fixture validator
- prompt projection contract
- projection distillation plan for teacher/student projector training
- persistence surfaces for re-entry, evidence, planning, and compaction hygiene
Nothing deploys from this repo. Linux verification runs on Yggdrasil, not on a Not present yet:
workstation:
```sh - runtime prompt renderer
cargo build --locked --workspace - projection training dataset
cargo test --locked -p ghostlight-persona-projection - student projection model
cargo test --locked -p ghostlight - event/classifier pipeline
cargo test --locked -p ghostlight-verse - simulation loop
- relationship update engine
- culture prior engine
## How Projection Is Supposed To Work
For one speaker in one scene, Ghostlight should gather speaker-local state:
- what the speaker knows
- what they believe
- what they want
- what they are protecting
- what memories are active
- how they read the listener
- what the relationship currently feels like
- what circumstance the scene creates: routine, desire, scarcity, humor,
tenderness, danger, institutional friction, or open crisis
- what voice surface is active
The projection layer turns that into compact character-local prose and prompt
sections. The dialogue model then writes from the active circumstance and tonal
mode, not from a universal crisis register.
Longer term, a frontier model can act as a teacher projector that generates
reviewed projection artifacts. Those artifacts can train a smaller student
projector once the projection schema, deterministic input slicer, and evaluator
are stable.
## Repo Tour
- `AGENTS.md`: operating discipline for humans and agents
- `state/map.yaml`: canonical project map and current next action
- `state/scratch.md`: disposable working memory for one bounded subgoal
- `state/evidence.jsonl`: distilled belief-changing evidence
- `notes/fresh-workspace-handoff.md`: compact re-entry packet
- `notes/ghostlight-current-system-map.md`: current repo machinery
- `notes/ghostlight-implementation-plan.md`: larger implementation sequence
- `notes/architecture-rationale.md`: why the persistence and state split exists
- `docs/research/`: research backlog and modeling notes
- `docs/aetheria/`: Aetheria source material used by Ghostlight
- `docs/architecture/`: state, projection, and authoring architecture
- `docs/architecture/verse-service-contract.md`: GameCult Verse service contract
for Ghostlight's missing Eve GUI/TUI state and authoring surface
- `schemas/`: JSON schema contracts and required field lists
- `examples/`: schema fixtures and future projection examples
- `tools/ghostlight_state.py`: state inspection and evidence helper
- `tools/ghostlight_prepare_compaction.py`: pre-compaction audit helper
- `tools/validate_agent_state.py`: focused fixture validator
## Useful Commands
```powershell
npm run state:status
npm run state:prepare-compaction
npm run schema:validate
``` ```
The kernel alone needs only `cargo test -p ghostlight`. The sidecar has To add distilled evidence:
`npm run sdk:build` and `npm run sdk:test`. The acceptance test
`controllers::tests::real_local_model_cognition_modes_commit_speech` is ignored
by default and needs a real model.
Inference is routed by model name: `local/` goes to an OpenAI-compatible ```powershell
loopback endpoint, `claude` to the SDK sidecar, and the verse runner's `hosted/` & 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' add-evidence --type design --status accepted --note '...'
to an https endpoint. Ghostlight never reads, stores or forwards a model ```
credential beyond a key file named at run time.
Runtime documents are MessagePack-backed CultCache. JSON appears only at schema ## Best Starting Points
publication, model-provider and diagnostic boundaries.
- `docs/architecture/canonical-agent-state-schema.md`
- `docs/architecture/cultnet-shared-agent-state-contract.md`
- `docs/architecture/agent-state-variable-glossary.md`
- `docs/architecture/prompt-projection-contract.md`
- `docs/architecture/projection-distillation-plan.md`
- `examples/agent-state.call-of-the-void.json`
For Codex-driven work, read `AGENTS.md` before changing the repo. It contains
the working rules that keep the project state coherent between sessions.

View file

@ -1,46 +0,0 @@
[package]
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
aes-gcm.workspace = true
async-trait.workspace = true
async-stream.workspace = true
axum.workspace = true
chrono.workspace = true
base64.workspace = true
cultcache-rs.workspace = true
model-connector.workspace = true
cultnet-rs.workspace = true
cultmesh-rs.workspace = true
jsonwebtoken.workspace = true
libc = "0.2"
hmac.workspace = true
ghostlight = { path = "../ghostlight" }
ghostlight-persona-projection = { path = "../ghostlight-persona-projection" }
rand.workspace = true
reqwest.workspace = true
rmp-serde.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
thiserror.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
uuid.workspace = true
zeroize.workspace = true
[dev-dependencies]
ghostlight = { path = "../ghostlight", features = ["test-support"] }
tempfile = "3"
tokio = { workspace = true, features = ["test-util"] }
tower = { version = "0.5", features = ["util"] }

View file

@ -1,65 +0,0 @@
use std::{env, path::Path, process::Command};
fn main() {
println!("cargo:rerun-if-env-changed=GHOSTLIGHT_BUILD_COMMIT");
let manifest_dir =
env::var("CARGO_MANIFEST_DIR").expect("Cargo must supply CARGO_MANIFEST_DIR");
let repo_root = Path::new(&manifest_dir).join("../..");
emit_git_rerun_paths(&repo_root);
// Release tooling injects the clean-tree commit. Git discovery is only a
// convenience for local builds. The exact ref and reflog dependencies above
// keep that convenience from silently publishing stale provenance.
let commit = env::var("GHOSTLIGHT_BUILD_COMMIT")
.ok()
.filter(|value| is_commit(value))
.or_else(|| git_commit(&repo_root))
.expect("GhostlightDungeon builds require an exact 40-hex source commit");
println!("cargo:rustc-env=GHOSTLIGHT_BUILD_COMMIT={commit}");
}
fn emit_git_rerun_paths(repo_root: &Path) {
for git_path in ["HEAD", "logs/HEAD", "packed-refs"] {
if let Some(path) = git_output(repo_root, &["rev-parse", "--git-path", git_path]) {
emit_rerun_path(repo_root, &path);
}
}
if let Some(reference) = git_output(repo_root, &["symbolic-ref", "-q", "HEAD"])
&& let Some(path) = git_output(repo_root, &["rev-parse", "--git-path", &reference])
{
emit_rerun_path(repo_root, &path);
}
}
fn emit_rerun_path(repo_root: &Path, git_path: &str) {
let path = Path::new(git_path);
let resolved = if path.is_absolute() {
path.to_path_buf()
} else {
repo_root.join(path)
};
println!("cargo:rerun-if-changed={}", resolved.display());
}
fn git_commit(repo_root: &Path) -> Option<String> {
git_output(repo_root, &["rev-parse", "HEAD"]).filter(|value| is_commit(value))
}
fn git_output(repo_root: &Path, args: &[&str]) -> Option<String> {
let output = Command::new("git")
.args(args)
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
}
fn is_commit(value: &str) -> bool {
value.len() == 40 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
}

View file

@ -1,25 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark light">
<meta name="referrer" content="no-referrer">
<title>Ghostlight Dungeon</title>
<link rel="stylesheet" href="page.css">
</head>
<body>
<header class="bar">
<button id="home" class="brand" type="button" aria-label="Your worlds">Ghostlight</button>
<div class="tools">
<button id="smaller" class="tool" type="button" aria-label="Smaller text">A&minus;</button>
<button id="larger" class="tool" type="button" aria-label="Larger text">A+</button>
<button id="theme" class="tool" type="button" aria-label="Switch light or dark theme">&#9680;</button>
<button id="signout" aria-label="Sign out" class="tool" type="button" hidden>Exit</button>
</div>
</header>
<main id="view" aria-live="polite"><p class="note">Loading&hellip;</p></main>
<noscript><p class="note">This page needs JavaScript to play.</p></noscript>
<script src="page.js"></script>
</body>
</html>

View file

@ -1,73 +0,0 @@
/* Presentation only. Text size and theme are the two variables below. */
:root {
--fs: 1.125rem;
--bg: #07111a; --panel: #16212c; --line: #263646; --muted: #8fa1b5;
--text: #eef5ff; --accent: #ff8a2a; --link: #59b7ff;
--bad: #ff6b5e; --badbg: #2a1614; --ok: #6fd08c; --focus: #59b7ff;
--head: Montserrat, "Segoe UI", system-ui, sans-serif;
--body: Georgia, "Iowan Old Style", "Palatino Linotype", serif;
}
:root[data-theme="light"] {
--bg: #f7f4ee; --panel: #ffffff; --line: #d8d2c4; --muted: #5d6a78;
--text: #17202a; --accent: #b4510a; --link: #0b5fa8;
--bad: #a3231a; --badbg: #fdeceb; --ok: #1d7a3c; --focus: #0b5fa8;
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body { margin: 0; background: var(--bg); color: var(--text); font: var(--fs)/1.65 var(--body); overflow-wrap: anywhere; }
.bar { position: sticky; top: 0; z-index: 5; display: flex; justify-content: space-between; align-items: center; gap: .5rem;
padding: .4rem max(.75rem, env(safe-area-inset-left)); background: var(--bg); border-bottom: 1px solid var(--line); }
.brand { white-space: nowrap; background: none; border: 0; color: var(--accent); font: 600 1.05rem var(--head); letter-spacing: .06em; text-transform: uppercase; min-height: 44px; padding: 0 .25rem; cursor: pointer; }
.tools { display: flex; gap: .2rem; justify-content: flex-end; }
.tool { background: none; border: 1px solid var(--line); color: var(--muted); font: 500 .8rem var(--head); border-radius: .5rem; min-height: 44px; min-width: 44px; padding: 0 .5rem; cursor: pointer; }
main { max-width: 44rem; margin: 0 auto; padding: .75rem max(.75rem, env(safe-area-inset-left)) 10rem; }
h1, h2 { font-family: var(--head); font-weight: 300; line-height: 1.2; margin: .5rem 0 .75rem; }
h1 { font-size: 1.6rem; } h2 { font-size: 1.25rem; }
.note, .small { color: var(--muted); font-size: .9rem; line-height: 1.5; }
a { color: var(--link); }
button, input, textarea { font: inherit; color: inherit; }
:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
.card { background: var(--panel); border: 1px solid var(--line); border-radius: .75rem; padding: .9rem 1rem; margin: .75rem 0; }
.row { display: flex; gap: .6rem; flex-wrap: wrap; align-items: center; }
.btn { background: var(--accent); color: #07111a; border: 0; border-radius: .6rem; min-height: 48px; padding: 0 1.1rem; font: 600 1rem var(--head); cursor: pointer; }
.btn.alt { background: none; color: var(--text); border: 1px solid var(--line); }
.btn[disabled] { opacity: .5; cursor: default; }
.btn.wide { width: 100%; }
label { display: block; font: 600 .85rem var(--head); letter-spacing: .04em; margin: 1rem 0 .3rem; color: var(--muted); text-transform: uppercase; }
input[type=text], textarea { width: 100%; background: var(--bg); border: 1px solid var(--line); border-radius: .6rem; padding: .7rem .8rem; min-height: 48px; }
textarea { resize: vertical; line-height: 1.5; }
.choice { display: flex; gap: .7rem; align-items: center; min-height: 48px; padding: .4rem .6rem; border: 1px solid var(--line); border-radius: .6rem; margin: .4rem 0; cursor: pointer; background: var(--bg); }
.choice input { width: 1.4rem; height: 1.4rem; accent-color: var(--accent); flex: none; }
.chip { font: 600 .72rem var(--head); text-transform: uppercase; letter-spacing: .06em; padding: .15rem .5rem; border-radius: 1rem; border: 1px solid var(--line); color: var(--muted); }
.chip.ready { color: var(--ok); border-color: var(--ok); } .chip.seeding { color: var(--accent); border-color: var(--accent); } .chip.failed { color: var(--bad); border-color: var(--bad); }
.tl { display: block; width: 100%; text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: .75rem; padding: .8rem 1rem; margin: .5rem 0; min-height: 56px; cursor: pointer; }
.tl.current { border-color: var(--accent); }
.tl .t { font: 600 1.05rem var(--head); display: block; }
.line { border-left: 4px solid var(--bad); background: var(--badbg); border-radius: .4rem; padding: .6rem .8rem; margin: .75rem 0; }
.line.info { border-color: var(--accent); background: var(--panel); }
.turn { margin: 1.4rem 0; }
.you { color: var(--muted); font-style: italic; border-left: 3px solid var(--line); padding-left: .8rem; margin: .8rem 0; white-space: pre-wrap; }
.story { white-space: pre-wrap; margin: 0; }
.ask { border: 1px solid var(--accent); border-radius: .6rem; padding: .6rem .8rem; margin: .8rem 0; }
.status { color: var(--muted); font: 500 .85rem var(--head); }
.pulse::after { content: ""; display: inline-block; width: .5rem; height: .5rem; margin-left: .5rem; border-radius: 50%; background: var(--accent); animation: p 1.2s ease-in-out infinite; }
@keyframes p { 50% { opacity: .2; } }
@media (prefers-reduced-motion: reduce) { .pulse::after { animation: none; } }
.bar2 { height: .4rem; background: var(--line); border-radius: .3rem; overflow: hidden; margin: .6rem 0; }
.bar2 i { display: block; height: 100%; width: 40%; background: var(--accent); animation: s 1.6s ease-in-out infinite alternate; }
@keyframes s { to { margin-left: 60%; } }
@media (prefers-reduced-motion: reduce) { .bar2 i { animation: none; width: 100%; } }
.compose { position: fixed; left: 0; right: 0; bottom: 0; background: var(--bg); border-top: 1px solid var(--line); padding: .5rem max(.75rem, env(safe-area-inset-left)) max(.5rem, env(safe-area-inset-bottom)); }
.compose .in { max-width: 44rem; margin: 0 auto; }
.compose textarea { min-height: 2.8rem; max-height: 30vh; }
.compose .row { margin-top: .4rem; }
.compose .btn { flex: 1 1 8rem; }
@media (min-width: 700px) { :root { --fs: 1.2rem; } main { padding-top: 1.25rem; } }
.blk { display: block; } .bad { color: var(--bad); } .gap { margin-top: .6rem; margin-bottom: .2rem; }
label.choice { text-transform: none; letter-spacing: 0; font: inherit; color: var(--text); margin: .4rem 0; }
.older { text-align: center; }
.older .btn { margin: .4rem 0; }
.lens { display: flex; gap: .5rem; align-items: center; padding: .35rem 0; border-bottom: 1px solid var(--line); }
.lens .what { flex: 1 1 auto; min-width: 0; }
.lens .n { min-width: 1.5rem; text-align: center; font: 600 1.05rem var(--head); }
.step { background: none; border: 1px solid var(--line); color: var(--text); border-radius: .5rem; min-width: 44px; min-height: 44px; font: 600 1.2rem var(--head); cursor: pointer; flex: none; }

View file

@ -1,410 +0,0 @@
// Presentation only. The daemon owns every command and every fact; this page
// shows what the API returns and sends what the player types. The only state it
// keeps on the device is the unsent draft, the text size and the theme. The
// scrollback is the server's turn log, loaded on open and paged on scroll-up,
// so a reload or another device shows the same story.
"use strict";
const $view = document.getElementById("view");
const LS = {
get(k) { try { return localStorage.getItem(k); } catch { return null; } },
set(k, v) { try { if (v === null || v === "") localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* storage may be blocked */ } },
};
const uuid = () => (crypto.randomUUID ? crypto.randomUUID()
: "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)));
function el(tag, attrs, ...kids) {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(attrs || {})) {
if (k === "class") node.className = v;
else if (k.startsWith("on")) node.addEventListener(k.slice(2), v);
else if (v === true) node.setAttribute(k, "");
else if (v !== false && v != null) node.setAttribute(k, v);
}
for (const kid of kids.flat()) if (kid != null) node.append(kid);
return node;
}
async function api(path, options) {
let response;
try {
response = await fetch("api/" + path, { credentials: "same-origin", ...options,
headers: options && options.body ? { "content-type": "application/json" } : undefined });
} catch {
return { status: 0, body: { error: "The server could not be reached." } };
}
let body = null;
try { body = await response.json(); } catch { body = null; }
return { status: response.status, body: body || {} };
}
const post = (path, body) => api(path, { method: "POST", body: JSON.stringify(body) });
// ---- text size and theme -------------------------------------------------
const root = document.documentElement;
function applySize(rem) { root.style.setProperty("--fs", rem + "rem"); LS.set("fs", String(rem)); }
const savedSize = parseFloat(LS.get("fs"));
if (savedSize >= 0.9 && savedSize <= 1.9) root.style.setProperty("--fs", savedSize + "rem");
function currentSize() { return parseFloat(getComputedStyle(root).getPropertyValue("--fs")) || 1.125; }
document.getElementById("smaller").onclick = () => applySize(Math.max(0.9, +(currentSize() - 0.1).toFixed(2)));
document.getElementById("larger").onclick = () => applySize(Math.min(1.9, +(currentSize() + 0.1).toFixed(2)));
function applyTheme(name) {
if (name === "light" || name === "dark") root.dataset.theme = name; else delete root.dataset.theme;
}
applyTheme(LS.get("theme"));
document.getElementById("theme").onclick = () => {
const next = root.dataset.theme === "light" ? "dark" : "light";
applyTheme(next); LS.set("theme", next);
};
// ---- state ---------------------------------------------------------------
const S = { me: null, timeline: null, history: [], older: null, live: null, echo: null, keyed: null, tailTried: null, stream: null, poll: null, signIn: null };
function stopLive() {
if (S.stream) { S.stream.close(); S.stream = null; }
if (S.poll) { clearTimeout(S.poll); S.poll = null; }
}
function show(...nodes) { document.querySelector(".compose")?.remove(); $view.replaceChildren(...nodes.flat()); window.scrollTo(0, 0); }
function inviteFromHash() {
const m = /(?:^#|&)invite=([A-Za-z0-9_\-]{8,200})/.exec(location.hash);
return m ? m[1] : "";
}
async function boot() {
stopLive();
const { status, body } = await api("me");
if (status !== 200) return show(el("h1", {}, "Ghostlight"), errorLine(body.error || "The server answered with an error (" + status + ")."), retryButton(boot));
S.me = body;
document.getElementById("signout").hidden = !body.signedIn;
if (!body.signedIn) return signInView();
if (body.currentTimeline) return openTimeline(body.currentTimeline);
return listView();
}
function errorLine(text) { return el("p", { class: "line", role: "alert" }, text); }
function retryButton(fn) { return el("button", { class: "btn", type: "button", onclick: fn }, "Try again"); }
// ---- sign in -------------------------------------------------------------
function signInView(message) {
stopLive();
const providers = (S.me && S.me.providers) || [];
const invite = el("input", { type: "text", id: "invite", autocomplete: "off", autocapitalize: "off", spellcheck: "false", value: inviteFromHash() });
const out = el("div", {});
if (message) out.append(errorLine(message));
const buttons = providers.map((name) => el("button", { class: "btn wide gap", type: "button", onclick: () => beginSignIn(name, invite.value.trim(), out) },
"Sign in with " + name[0].toUpperCase() + name.slice(1)));
show(el("h1", {}, "Sign in"),
el("p", { class: "note" }, "Only people on the allowlist can play. A first sign-in needs the invite you were given; after that, signing in is enough."),
el("div", { class: "card" },
el("label", { for: "invite" }, "Invite (first time only)"), invite,
el("p", { class: "small" }, "A link that ends in #invite=… fills this in."),
providers.length ? buttons : el("p", { class: "line" }, "This server offers no sign-in provider.")),
out);
if (S.signIn && S.signIn.until > Date.now()) resumeSignIn(out, invite);
}
async function beginSignIn(provider, invite, out) {
out.replaceChildren(el("p", { class: "note pulse" }, "Asking " + provider + " for a sign-in"));
const { status, body } = await post("auth/begin", invite ? { key: uuid(), provider, invite } : { key: uuid(), provider });
if (status !== 200) return out.replaceChildren(errorLine(body.error || "Sign-in could not begin (" + status + ")."));
let target = null;
try {
const url = new URL(body.url, location.href);
if ((body.allowedOrigins || []).includes(url.origin) && url.protocol === "https:") target = url.href;
} catch { target = null; }
if (!target) return out.replaceChildren(errorLine("The sign-in address was not one this page will open."));
S.signIn = { handle: body.handle, target, until: Date.now() + 9 * 60 * 1000 };
window.open(target, "_blank", "noopener");
resumeSignIn(out);
}
async function resumeSignIn(out) {
const attempt = S.signIn;
out.replaceChildren(
el("p", { class: "note pulse" }, "Waiting for you to finish signing in on the other tab."),
el("p", {}, el("a", { href: attempt.target, target: "_blank", rel: "noopener noreferrer" }, "Open the sign-in page again")));
while (S.signIn === attempt && Date.now() < attempt.until) {
await new Promise((r) => setTimeout(r, 2500));
if (S.signIn !== attempt) return;
const { status, body } = await post("auth/complete", { handle: attempt.handle, key: uuid() });
if (status === 202) continue;
S.signIn = null;
if (status === 200 && body.status === "authenticated") { history.replaceState(null, "", location.pathname); return boot(); }
if (status === 429) return out.replaceChildren(errorLine(body.error || "Too many attempts; wait a minute."));
return out.replaceChildren(errorLine(body.error || "Sign-in was refused (" + status + ")."));
}
if (S.signIn === attempt) { S.signIn = null; out.replaceChildren(errorLine("The sign-in expired. Start again.")); }
}
document.getElementById("signout").onclick = async () => {
stopLive();
const { status, body } = await post("auth/logout", {});
if (status !== 200) return show(errorLine(body.error || "Sign-out was not confirmed."), retryButton(boot));
S.history = []; S.timeline = null;
boot();
};
document.getElementById("home").onclick = () => { if (S.me && S.me.signedIn) listView(); };
// ---- timelines -----------------------------------------------------------
async function listView() {
stopLive();
S.timeline = null;
const { status, body } = await api("timelines");
if (status === 401) return boot();
if (status !== 200) return show(el("h1", {}, "Your worlds"), errorLine(body.error || "Could not list your worlds."), retryButton(listView));
const rows = body.timelines || [];
const seeding = rows.some((r) => r.status === "seeding");
show(el("h1", {}, "Your worlds"),
el("button", { class: "btn wide", type: "button", onclick: beginView }, "Begin a new world"),
rows.length ? rows.map(timelineRow) : el("p", { class: "note" }, "No worlds yet."),
el("p", { class: "small" }, "Each fork of a world is its own timeline. Older timelines stay."));
if (seeding) S.poll = setTimeout(listView, 4000);
}
function timelineRow(row) {
const when = row.createdAt ? new Date(row.createdAt).toLocaleString() : "";
return el("button", { class: "tl" + (row.current ? " current" : ""), type: "button", onclick: () => openTimeline(row.timeline) },
el("span", { class: "t" }, row.title || "Untitled"),
el("span", { class: "chip " + row.status }, row.status), " ",
row.parent ? el("span", { class: "small" }, " fork") : "",
el("span", { class: "small blk" }, (row.current ? "Current. " : "") + when),
row.status === "failed" ? el("span", { class: "small blk bad" }, row.reason || "Seeding failed.") : "");
}
// ---- begin ---------------------------------------------------------------
let beginKey = null;
async function beginView() {
stopLive();
beginKey = beginKey || uuid();
const { status, body } = await api("vaults");
if (status === 401) return boot();
const vaults = status === 200 ? body.vaults || [] : [];
const msg = el("div", {});
if (status !== 200) msg.append(errorLine(body.error || "The lore list could not be read."));
const lenses = status === 200 ? body.lenses || [] : [];
let vault = vaults.length ? vaults[0].name : "";
let era = null;
// The era picker follows the vault choice; a vault with one era offers none.
const eraBox = el("div", {});
const drawEras = () => {
const chosen = vaults.find((v) => v.name === vault);
era = chosen ? chosen.default_era : null;
eraBox.replaceChildren(...(chosen && chosen.eras.length > 1 ? [el("label", {}, "Era"),
...chosen.eras.map((e) => el("label", { class: "choice" },
el("input", { type: "radio", name: "era", value: e.id, checked: e.id === era, onchange: () => { era = e.id; } }),
el("span", {}, e.label, el("span", { class: "small blk" }, e.description))))] : []));
};
const choices = vaults.map((v, i) => el("label", { class: "choice" },
el("input", { type: "radio", name: "vault", value: v.name, checked: i === 0, onchange: () => { vault = v.name; drawEras(); } }), v.name));
drawEras();
// Each lens weighs what the world reaches for: 0 never, 5 most.
const weights = Object.fromEntries(lenses.map((l) => [l.id, 1]));
const lensRows = lenses.map((l) => {
const shown = el("span", { class: "n", "aria-live": "polite" }, "1");
const step = (by) => { weights[l.id] = Math.max(0, Math.min(5, weights[l.id] + by)); shown.textContent = String(weights[l.id]); };
return el("div", { class: "lens" },
el("span", { class: "what" }, el("b", {}, l.name), el("span", { class: "small blk" }, l.reaches_for)),
el("button", { class: "step", type: "button", "aria-label": "Less " + l.name, onclick: () => step(-1) }, "−"), shown,
el("button", { class: "step", type: "button", "aria-label": "More " + l.name, onclick: () => step(1) }, "+"));
});
const title = el("input", { type: "text", id: "title", autocomplete: "off", value: LS.get("begin-title") || "" });
const name = el("input", { type: "text", id: "name", autocomplete: "off", value: LS.get("begin-name") || "" });
const brief = el("textarea", { id: "brief", rows: "3" });
const go = el("button", { class: "btn wide gap", type: "button" }, "Begin");
go.onclick = async () => {
if (!title.value.trim() || !name.value.trim()) return msg.replaceChildren(errorLine("A world needs a title and your name in it."));
go.disabled = true; msg.replaceChildren(el("p", { class: "note pulse" }, "Starting the world"));
const { status: s, body: b } = await post("begin", { key: beginKey, title: title.value.trim(), name: name.value.trim(), brief: brief.value.trim() || null, vault: vault || null, era: vault ? era : null, lenses: lenses.length ? weights : null });
go.disabled = false;
if (s === 200) { beginKey = null; LS.set("begin-title", title.value.trim()); LS.set("begin-name", name.value.trim()); return openTimeline(b.timeline); }
const unknown = b.outcome === "unknown" || s === 0;
msg.replaceChildren(errorLine((b.error || "The world could not begin (" + s + ").") + (b.step ? " (step: " + b.step + ")" : "")
+ (unknown ? " The outcome is unknown: check Your worlds before beginning again. Pressing Begin again is safe; it carries the same request key." : "")));
};
show(el("h1", {}, "Begin a world"),
el("label", {}, "1. Lore"),
vaults.length ? choices : el("p", { class: "line info" }, "No vault has been imported on this server, so a world would start with no lore. Ask the host to import one."),
eraBox,
el("label", { for: "title" }, "2. Name the world"), title,
el("label", { for: "name" }, "3. What you are called in it"), name,
el("label", { for: "brief" }, "4. Anything the storyteller should know (optional)"), brief,
lenses.length ? [el("label", {}, "5. What the world reaches for"), ...lensRows] : "",
go, msg,
el("p", { class: "small" }, "A world seeded from lore takes a few minutes. You can leave this page; it carries on."));
}
// ---- play ----------------------------------------------------------------
// The scrollback is the server's turn log: S.history holds the entries fetched
// so far (oldest first), S.live the open turn's view from the stream. Nothing
// here is kept on the device but the unsent draft.
async function openTimeline(id) {
stopLive();
S.timeline = id; S.history = []; S.older = null; S.live = null; S.echo = null; S.keyed = null; S.tailTried = null;
const { status, body } = await api("timelines");
if (status !== 200) return show(errorLine(body.error || "Could not open that world."), retryButton(() => openTimeline(id)));
const row = (body.timelines || []).find((r) => r.timeline === id);
if (!row) return listView();
if (row.status === "seeding") {
show(el("h1", {}, row.title), el("p", { class: "status pulse" }, "Seeding the world from the lore"),
el("div", { class: "bar2" }, el("i", {})),
el("p", { class: "note" }, "Elaborators are writing the people and places. You can leave and come back; this updates by itself."));
S.poll = setTimeout(() => openTimeline(id), 4000);
return;
}
if (row.status === "failed") {
return show(el("h1", {}, row.title), errorLine("Seeding failed: " + (row.reason || "no reason was recorded.")),
el("button", { class: "btn", type: "button", onclick: beginView }, "Begin another world"));
}
playView(row);
}
let $log, $status, $text, $send, $retryRow, $older;
async function playView(row) {
const id = S.timeline;
$older = el("div", { class: "older small" });
$log = el("div", { id: "log" });
$status = el("p", { class: "status", role: "status" });
$retryRow = el("div", { class: "row" });
show(el("h1", {}, row.title), $older, $log, $status, $retryRow);
$text = el("textarea", { id: "say", rows: "2", "aria-label": "What do you do?", placeholder: "What do you do? (Empty Send carries on an unfinished turn.)" });
$text.value = LS.get("draft:" + id) || "";
$text.addEventListener("input", () => LS.set("draft:" + id, $text.value));
$send = el("button", { class: "btn", type: "button", onclick: () => send($text.value) }, "Send");
document.body.append(el("div", { class: "compose" }, el("div", { class: "in" }, $text, el("div", { class: "row" }, $send,
el("button", { class: "btn alt", type: "button", title: "Carry on an unfinished turn", onclick: () => send("") }, "Continue"))
)));
const ok = await loadHistory(null);
if (S.timeline !== id) return;
if (ok) window.scrollTo(0, document.documentElement.scrollHeight);
connect();
}
// Reads one page of the log. `before` null reads the newest page and merges it
// into what is held; a number reads the page older than that entry.
async function loadHistory(before) {
const id = S.timeline;
const { status, body } = await api("history/" + encodeURIComponent(id) + (before ? "?before=" + before : ""));
if (S.timeline !== id) return false;
if (status !== 200) {
$older.replaceChildren(errorLine(body.error || "The earlier turns could not be loaded."), retryButton(() => loadHistory(before)));
return false;
}
const first = !S.history.length;
const have = new Map(S.history.map((e) => [e.seq, e]));
for (const entry of body.entries || []) have.set(entry.seq, entry);
S.history = [...have.values()].sort((a, b) => a.seq - b.seq);
// Only a read at the old edge moves the edge; a refresh of the newest page leaves it.
if (before || first) S.older = body.older;
render();
return true;
}
let loadingOlder = false;
window.addEventListener("scroll", async () => {
if (!S.timeline || !$log || !S.older || loadingOlder || window.scrollY > 160) return;
loadingOlder = true;
const height = document.documentElement.scrollHeight;
if (await loadHistory(S.older)) window.scrollTo(0, window.scrollY + document.documentElement.scrollHeight - height);
loadingOlder = false;
}, { passive: true });
function connect() {
const id = S.timeline;
if (S.stream) S.stream.close();
const stream = new EventSource("api/turn/" + encodeURIComponent(id) + "/stream");
S.stream = stream;
stream.addEventListener("turn", (event) => { if (S.timeline === id) { try { onTurn(JSON.parse(event.data)); } catch { /* ignore a torn event */ } } });
stream.onerror = () => { if (S.timeline === id && $status) $status.textContent = "Reconnecting…"; };
}
document.addEventListener("visibilitychange", async () => {
if (document.hidden || !S.timeline || !$log) return;
const { status, body } = await api("turn/" + encodeURIComponent(S.timeline));
if (status === 200 && body.timeline === S.timeline) onTurn(body);
if (S.stream && S.stream.readyState === 2) connect();
});
// Whether the log already holds what the open turn shows.
function logged(turn) {
return S.history.some((e) => e.turn_id === turn.id &&
(turn.state === "awaiting_player" ? e.status === "asked" && turn.question && e.question === turn.question.text : e.status !== "asked"));
}
async function onTurn(view) {
const turn = view.turn;
S.live = turn;
if (S.echo && (!turn || turn.revision !== S.echo.revision)) S.echo = null;
render();
if (turn && turn.state !== "running" && !logged(turn)) {
const mark = turn.id + ":" + turn.revision;
if (S.tailTried !== mark) { S.tailTried = mark; await loadHistory(null); }
}
}
function render() {
const nearBottom = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 240;
const turn = S.live;
$older.replaceChildren(S.older ? el("button", { class: "btn alt", type: "button", onclick: () => loadHistory(S.older) }, "Load earlier turns") : "");
const nodes = S.history.map(entryNode);
const running = turn && turn.state === "running";
if (running || S.echo) {
const text = running ? turn.text : S.echo.text;
nodes.push(el("section", { class: "turn" }, text ? el("p", { class: "you" }, text) : ""));
}
if (!nodes.length) nodes.push(el("p", { class: "note" }, "The world is ready. Say what you do."));
$log.replaceChildren(...nodes);
$retryRow.replaceChildren();
$status.className = "status";
$status.textContent = "";
if (running) {
if (turn.resolving) { $status.className = "status pulse"; $status.textContent = "The storyteller is resolving your turn"; }
else $status.textContent = turn.continue_hint || "This turn is unfinished.";
} else if (S.echo) {
$status.className = "status pulse"; $status.textContent = "Sent";
} else if (turn && turn.state === "awaiting_player") {
$status.textContent = "The storyteller is waiting for your answer.";
}
const last = S.history[S.history.length - 1];
if (last && !running && !S.echo && turn && logged(turn)) {
if (last.status === "faulted" && !last.superseded_by) {
$retryRow.append(
el("button", { class: "btn", type: "button", onclick: () => send(last.text, last.seq) }, "Retry"),
el("button", { class: "btn alt", type: "button", onclick: () => editAgain(last.text) }, "Edit and resend"));
} else if (last.status === "refused") {
$retryRow.append(el("button", { class: "btn alt", type: "button", onclick: () => editAgain(last.text) }, "Edit and resend"));
}
}
if (nearBottom) window.scrollTo(0, document.documentElement.scrollHeight);
}
function entryNode(entry) {
const parts = [];
if (entry.text) parts.push(el("p", { class: "you" }, entry.text));
if (entry.narration) parts.push(el("p", { class: "story" }, entry.narration));
if (entry.refusal) parts.push(el("p", { class: "line", role: "alert" }, entry.refusal));
if (entry.fault) parts.push(el("p", { class: "line", role: "alert" }, entry.fault));
if (entry.superseded_by) parts.push(el("p", { class: "small" }, "Sent again below."));
if (entry.question) parts.push(el("div", { class: "ask" }, el("strong", {}, "The storyteller asks"), el("p", { class: "story" }, entry.question)));
return el("section", { class: "turn" }, parts);
}
function editAgain(text) { $text.value = text; LS.set("draft:" + S.timeline, text); $text.focus(); }
async function send(text, retryOf) {
if (!S.timeline) return;
const turn = S.live;
const answers = turn && turn.state === "awaiting_player" && turn.question ? turn.question.token : null;
// The same text resent after a lost reply reuses its key, so it cannot play twice.
if (!S.keyed || S.keyed.text !== text || retryOf) S.keyed = { text, key: uuid() };
$send.disabled = true;
// The echo is placed before the request: the stream can deliver the new turn before the reply returns.
if (text) { S.echo = { text, revision: turn ? turn.revision : null }; render(); }
const { status, body } = await post("play", { timeline: S.timeline, key: S.keyed.key, text, answers, retry_of: retryOf || null });
$send.disabled = false;
if (status === 202 || status === 200) {
S.keyed = null;
$text.value = ""; LS.set("draft:" + S.timeline, "");
if (!text) { $status.className = "status pulse"; $status.textContent = "Sent"; }
return;
}
S.echo = null; render();
$retryRow.replaceChildren(errorLine(status === 0 ? "The server could not be reached. Your text is kept; Send resends it safely." : (body.error || "The turn was refused (" + status + ").")));
}
boot();

View file

@ -1,79 +0,0 @@
{
"turns_per_character": 12,
"wall_minutes": 240,
"turn_timeout_minutes": 15,
"character_model": "claude-sonnet-5-5",
"critic_model": "claude-opus-5-5",
"prices": {
"opus": { "input": 4.0, "output": 20.0, "cache_read": 0.2 },
"sonnet": { "input": 2.0, "output": 10.0, "cache_read": 0.1 },
"haiku": { "input": 0.1, "output": 0.5 }
},
"temperaments": {
"diplomat": {
"goal": "Make allies and brokered deals; leave every room better disposed toward you than you found it.",
"manner": "Talks first and listens closely. Offers trades, introductions and face-saving ways out. Never draws a weapon unless cornered.",
"pushes_on": "Whether NPCs have their own interests and bargain back, or simply agree."
},
"murderhobo": {
"goal": "Take what you want and answer slights with steel.",
"manner": "Quick to anger, blunt, armed. Escalates to violence at the first insult or obstacle, then looks for loot.",
"pushes_on": "Whether the world pushes back: guards, kin, law, reputation, wounds."
},
"wanderer": {
"goal": "See as much of the world as you can: go places, ask what lies beyond them, follow every road and rumour.",
"manner": "Curious and restless. Moves on whenever somewhere is explored. Asks locals about the next place and about their own history.",
"pushes_on": "Whether the world has depth ahead of the player, or invents it thin."
},
"schemer": {
"goal": "Gain power by playing factions against one another.",
"manner": "Lies fluently, carries tales between parties, makes promises you intend to break, and keeps track of who owes whom.",
"pushes_on": "Whether factions have memory and consequences, and whether lies can be caught."
},
"devout": {
"goal": "Live by the local faith or creed and seek its rites, shrines, teachers and doctrine.",
"manner": "Earnest and respectful. Asks what is believed, what is forbidden, what is owed to the powers. Takes part in observances.",
"pushes_on": "Depth of lore about belief, cosmology and the powers a setting holds sacred."
},
"grifter": {
"goal": "Come out ahead through theft, cheating and unpaid debts.",
"manner": "Charming and shifty. Picks pockets, short-changes, forges, runs cons, skips out on what is owed.",
"pushes_on": "Whether ledgers, debts, law and watchfulness exist and bite."
},
"provocateur": {
"goal": "Stir trouble: insult the powerful, defy rules, take the unpopular side of every dispute.",
"manner": "Loud, contrarian, theatrical. Says what nobody wants said and refuses to back down.",
"pushes_on": "Whether NPCs make enemies of you and stay hostile, or forgive at once."
},
"charmer": {
"goal": "Win hearts: flirt, seduce, court and be courted.",
"manner": "Warm, flattering, bold about desire. Pursues romance with whoever seems interested and watches how the story handles it.",
"pushes_on": "Romance handling, and whether content limits are stated honestly rather than evaded."
}
},
"worlds": [
{ "id": "delvehold-diplomat", "vault": "delvehold", "era": "present", "name": "Ilsa Brandt", "temperament": "diplomat" },
{ "id": "delvehold-murderhobo", "vault": "delvehold", "era": "present", "name": "Korr Skullsplitter", "temperament": "murderhobo" },
{ "id": "delvehold-grifter", "vault": "delvehold", "era": "present", "name": "Pip Tallowcandle", "temperament": "grifter" },
{
"id": "aetheria-pre-schemer", "vault": "aetheria", "era": "pre-elysium", "name": "Vesper Quill", "temperament": "schemer",
"lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 }
},
{
"id": "aetheria-pre-devout", "vault": "aetheria", "era": "pre-elysium", "name": "Sister Anwen Roe", "temperament": "devout",
"lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 }
},
{
"id": "aetheria-pre-provocateur", "vault": "aetheria", "era": "pre-elysium", "name": "Dax Marlowe", "temperament": "provocateur",
"lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 }
},
{
"id": "aetheria-post-wanderer", "vault": "aetheria", "era": "post-elysium", "name": "Tamsin Ode", "temperament": "wanderer",
"lenses": { "weighted": { "numen": 3, "veil": 3, "tangle": 3 }, "rest": 1 }
},
{
"id": "aetheria-post-charmer", "vault": "aetheria", "era": "post-elysium", "name": "Lucan Vey", "temperament": "charmer",
"lenses": { "weighted": { "numen": 3, "veil": 3, "tangle": 3 }, "rest": 1 }
}
]
}

File diff suppressed because it is too large Load diff

View file

@ -1,954 +0,0 @@
//! 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 ghostlight::VerifiedPrincipalEvidence;
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 cultcache_rs::{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";
/// `pub(crate)` so the recipe-drift test in `idunn_health.rs` can check the
/// `app-sessions` state slot's schema against this constant.
pub(crate) 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)]
#[serde(deny_unknown_fields)]
struct AppSessionState {
schema: String,
sessions: BTreeMap<String, AppSession>,
}
#[derive(Clone, Serialize, Deserialize)]
#[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<String>,
access_expires_at: DateTime<Utc>,
refresh_expires_at: DateTime<Utc>,
encrypted_refresh_claim: String,
created_at: DateTime<Utc>,
last_refresh_at: DateTime<Utc>,
revoked_at: Option<DateTime<Utc>>,
}
/// The clause by which the local commit refuses a refresh Heimdall executed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub(crate) enum RefreshRefusal {
#[error("local session was revoked during refresh")]
Revoked,
#[error("local session moved to another revision since the refresh candidate was taken")]
MovedSinceCandidate,
#[error("refresh receipt revision went backwards")]
RevisionWentBackwards,
#[error("refresh receipt names a different Heimdall session")]
SessionId,
#[error("refresh receipt names a different account")]
Account,
}
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,
}
pub(crate) struct AppSessionOwner {
store: OwnedRedbMessagePackBackingStore,
row: CultCacheEnvelope,
state: AppSessionState,
wrapping_key: [u8; 32],
healthy: bool,
}
impl AppSessionOwner {
pub(crate) fn open(
store_path: impl AsRef<Path>,
wrapping_key_path: impl AsRef<Path>,
) -> anyhow::Result<Self> {
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: STORE_SCHEMA.into(),
sessions: BTreeMap::new(),
};
let row = envelope(&state)?;
if !store.compare_and_swap_batch(&[], vec![row.clone()])? {
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,
healthy: true,
})
}
pub(crate) fn create_session(
&mut self,
input: VerifiedSessionAdmission,
) -> anyhow::Result<String> {
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 now = Utc::now();
let session = AppSession {
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().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(),
)?,
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);
self.commit(next)?;
Ok(raw_cookie)
}
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<Utc>,
) -> anyhow::Result<Option<VerifiedPrincipalEvidence>> {
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(|| {
VerifiedPrincipalEvidence::new(
session.account_subject_hash.clone(),
session.access_expires_at,
)
}))
}
pub(crate) fn revoke_cookie(&mut self, raw_cookie: &str) -> anyhow::Result<bool> {
self.ensure_owned()?;
let cookie_hash = secret_hash(raw_cookie);
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(crate) fn revoke_cookie_hash(&mut self, cookie_hash: &str) -> anyhow::Result<bool> {
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(crate) fn session_for_logout(
&mut self,
raw_cookie: &str,
) -> anyhow::Result<Option<RefreshCandidate>> {
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<Utc>,
refresh_before: chrono::Duration,
) -> anyhow::Result<Vec<RefreshCandidate>> {
self.ensure_owned()?;
let candidates = self
.state
.sessions
.values()
.filter(|session| {
session.revoked_at.is_none()
&& session.refresh_expires_at > now
&& session.access_expires_at <= now + refresh_before
})
.map(|session| self.refresh_candidate(session))
.collect::<anyhow::Result<Vec<_>>>();
match candidates {
Ok(candidates) => Ok(candidates),
Err(error) => self.poison(error),
}
}
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");
}
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() {
return Err(RefreshRefusal::Revoked.into());
}
if session.access_revision != expected_access_revision {
return Err(RefreshRefusal::MovedSinceCandidate.into());
}
// Heimdall's access_revision is a revocation epoch: refresh rotates
// the token at the same revision, so equal is the normal receipt and
// only a lower one is a refusal.
if input.access_revision() < expected_access_revision {
return Err(RefreshRefusal::RevisionWentBackwards.into());
}
if session.heimdall_session_id != input.heimdall_session_id() {
return Err(RefreshRefusal::SessionId.into());
}
if session.account_subject_hash
!= secret_hash(&format!("heimdall-account:{}", input.account_id()))
{
return Err(RefreshRefusal::Account.into());
}
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<RefreshCandidate> {
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,
)?,
})
}
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), vec![next_row.clone()]);
if !matches!(swapped, Ok(true)) {
return self.poison(anyhow::anyhow!(
"app-session commit outcome is uncertain; sole ownership was lost"
));
}
if self.store.validate_path_identity().is_err() {
return self.poison(anyhow::anyhow!(
"app-session store path changed after durable commit"
));
}
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<T>(&mut self, error: anyhow::Error) -> anyhow::Result<T> {
self.healthy = false;
Err(error)
}
}
/// The idempotency key of the refresh that spends `refresh_claim`: a retry of
/// that refresh derives the same key, the next refresh (a new claim) a new one,
/// and the claim itself never leaves the process in it.
pub(crate) fn refresh_idempotency_key(refresh_claim: &str) -> String {
format!(
"refresh:{}",
secret_hash(&format!("heimdall-refresh-key:{refresh_claim}"))
)
}
pub(crate) fn secret_hash(value: &str) -> String {
format!("sha256:{:x}", Sha256::digest(value.as_bytes()))
}
fn envelope(state: &AppSessionState) -> anyhow::Result<CultCacheEnvelope> {
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<Utc>) {
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::<Vec<_>>();
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 session wrapping key {}", path.display()))?;
let decoded = if source.len() == 32 {
source
} else {
URL_SAFE_NO_PAD
.decode(std::str::from_utf8(&source)?.trim())
.context("session wrapping key must be 32 raw bytes or base64url")?
};
decoded
.try_into()
.map_err(|_| anyhow::anyhow!("session wrapping key must be exactly 32 bytes"))
}
fn wrap_refresh(
key: &[u8; 32],
account_hash: &str,
session_id: &str,
claim: &str,
) -> anyhow::Result<String> {
let mut iv = [0_u8; 12];
rand::rng().fill_bytes(&mut iv);
let aad = format!("ghostlight.app_session.refresh.v2\n{account_hash}\n{session_id}");
let ciphertext = Aes256Gcm::new_from_slice(key)?
.encrypt(
(&iv).into(),
aes_gcm::aead::Payload {
msg: claim.as_bytes(),
aad: aad.as_bytes(),
},
)
.map_err(|_| anyhow::anyhow!("failed to wrap Heimdall refresh claim"))?;
Ok(format!(
"{}.{}",
URL_SAFE_NO_PAD.encode(iv),
URL_SAFE_NO_PAD.encode(ciphertext)
))
}
fn unwrap_refresh(
key: &[u8; 32],
account_hash: &str,
session_id: &str,
wrapped: &str,
) -> anyhow::Result<String> {
let (iv, ciphertext) = wrapped
.split_once('.')
.context("wrapped refresh claim is malformed")?;
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.v2\n{account_hash}\n{session_id}");
let plaintext = Aes256Gcm::new_from_slice(key)?
.decrypt(
(&iv).into(),
aes_gcm::aead::Payload {
msg: &ciphertext,
aad: aad.as_bytes(),
},
)
.map_err(|_| anyhow::anyhow!("failed to unwrap Heimdall refresh claim"))?;
String::from_utf8(plaintext).context("Heimdall refresh claim is not UTF-8")
}
#[cfg(test)]
mod tests {
use super::*;
/// Every `.rs` file under `src`, subdirectories included, with everything
/// a `#[cfg(test)]` attribute guards removed — whatever that item is, and
/// whatever a test module is called.
///
/// The item's extent is read from the layout: an attribute at indent `N`
/// guards lines until the first later line at indent `N` that closes a
/// block, or, for an item with no body, until the first line at indent `N`
/// that ends in `;` or `,`. This is a claim about rustfmt's output, not
/// about Rust's grammar, and it is the reason the scan does not try to
/// balance braces: braces inside string and character literals are not
/// block structure, and a scanner that counts them reads the end of a test
/// module in the wrong place.
fn production_sources() -> Vec<(std::path::PathBuf, String)> {
fn indent(line: &str) -> usize {
line.len() - line.trim_start().len()
}
fn strip_cfg_test(text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let mut kept: Vec<&str> = Vec::new();
let mut index = 0;
while index < lines.len() {
let line = lines[index];
if line.trim() != "#[cfg(test)]" {
kept.push(line);
index += 1;
continue;
}
let guard = indent(line);
index += 1;
// A body opens on the attribute's own item; without one, the
// item ends at its first terminator.
let mut opened = lines
.get(index)
.is_some_and(|next| next.trim_end().ends_with('{'));
while index < lines.len() {
let body = lines[index];
index += 1;
let trimmed = body.trim();
if trimmed.is_empty() {
continue;
}
if opened {
if indent(body) == guard
&& (trimmed == "}" || trimmed == "};" || trimmed == "},")
{
break;
}
} else if indent(body) == guard
&& (trimmed.ends_with(';') || trimmed.ends_with(','))
{
break;
} else if indent(body) == guard && trimmed.ends_with('{') {
opened = true;
}
}
}
kept.join("\n")
}
let mut sources = Vec::new();
let mut pending = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
while let Some(directory) = pending.pop() {
for entry in std::fs::read_dir(&directory).expect("the source tree reads") {
let path = entry.expect("a readable entry").path();
if path.is_dir() {
pending.push(path);
continue;
}
if path.extension().and_then(|value| value.to_str()) != Some("rs") {
continue;
}
let text = std::fs::read_to_string(&path)
.expect("the source reads")
.replace("\r\n", "\n");
sources.push((path, strip_cfg_test(&text)));
}
}
sources
}
/// True when the text immediately following the type's name calls its
/// `new`. Written as a scan rather than one literal so the qualified
/// `<Type>::new(` form and any whitespace the formatter may introduce
/// count the same as the plain path.
fn calls_new(tail: &str) -> bool {
let tail = tail.trim_start();
let tail = tail.strip_prefix('>').unwrap_or(tail).trim_start();
let Some(tail) = tail.strip_prefix("::") else {
return false;
};
let Some(tail) = tail.trim_start().strip_prefix("new") else {
return false;
};
tail.trim_start().starts_with('(')
}
/// The library owns `VerifiedPrincipalEvidence` and gives it a public
/// constructor, so the single-minter rule its private fields used to
/// enforce is this one: production mints it in `account_for_cookie` and
/// nowhere else, from a live cookie this owner holds custody of. A second
/// minter anywhere in Dungeon's production source is a second authority
/// over who the kernel believes is speaking.
///
/// The type is followed by name, so production may not give it a second
/// name: an `as` import or a type alias is refused outright rather than
/// counted, because a renamed minter is one this test cannot follow. What
/// it still cannot see is a call that never spells the type — a macro
/// expansion, or a generic instantiated elsewhere.
#[test]
fn soul_exactly_one_production_site_mints_verified_principal_evidence() {
// Assembled from halves so this test's own source is never a match,
// whatever the scan above decides about this module's extent.
let name = format!("VerifiedPrincipal{}", "Evidence");
let mut sites = Vec::new();
for (path, production) in production_sources() {
for (at, _) in production.match_indices(name.as_str()) {
let tail = &production[at + name.len()..];
assert!(
!tail.trim_start().starts_with("as "),
"{} renames {name} on import",
path.display()
);
if calls_new(tail) {
sites.push(path.clone());
}
}
for line in production.lines() {
assert!(
!(line.trim_start().starts_with("type ") && line.contains(name.as_str())),
"{} aliases {name} to another name: {line}",
path.display()
);
}
}
assert_eq!(
sites.len(),
1,
"production mints {name} in exactly one place: {sites:?}"
);
assert!(
sites[0].ends_with("app_session.rs"),
"the one minter is not this owner: {:?}",
sites[0]
);
}
#[test]
fn a_cookie_authenticates_until_the_instant_its_access_expires() {
let directory = tempfile::tempdir().unwrap();
let key = directory.path().join("session.key");
std::fs::write(&key, [23_u8; 32]).unwrap();
let mut owner = AppSessionOwner::open(directory.path().join("app-sessions-v2.cc"), &key).unwrap();
let now = Utc::now();
let (access, refresh) = (now + chrono::Duration::minutes(5), now + chrono::Duration::days(7));
let cookie = owner
.create_session(VerifiedSessionAdmission::fixture("a", "s1", 1, access, refresh, "c1"))
.unwrap();
assert!(owner.account_for_cookie(&cookie, access - chrono::Duration::seconds(1)).unwrap().is_some());
assert!(owner.account_for_cookie(&cookie, access).unwrap().is_none(), "dead at the instant");
assert!(owner.account_for_cookie("not-a-cookie", now).unwrap().is_none());
}
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 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(&[], vec![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-v2.cc");
let mut owner = AppSessionOwner::open(&store, &key).unwrap();
let cookie = owner
.create_session(session("private-refresh-claim"))
.unwrap();
let account = owner
.account_for_cookie(&cookie, Utc::now())
.unwrap()
.unwrap();
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
.account_for_cookie(&second, Utc::now())
.unwrap()
.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(&[], vec![foreign]).unwrap());
assert!(AppSessionOwner::open(&store_path, &key).is_err());
}
#[test]
fn a_refresh_for_a_session_that_moved_is_refused_by_name() {
let directory = tempfile::tempdir().unwrap();
let key = directory.path().join("session.key");
std::fs::write(&key, [5_u8; 32]).unwrap();
let mut owner =
AppSessionOwner::open(directory.path().join("sessions.cc"), &key).unwrap();
let cookie = owner
.create_session(VerifiedSessionAdmission::fixture(
"account",
"session",
1,
Utc::now() + chrono::Duration::minutes(1),
Utc::now() + chrono::Duration::days(1),
"claim-0",
))
.unwrap();
let receipt = VerifiedSessionRefresh::fixture(
"account",
"session",
1,
Utc::now() + chrono::Duration::minutes(1),
Utc::now() + chrono::Duration::days(1),
"claim-1",
);
let error = owner
.apply_refresh(&secret_hash(&cookie), 0, receipt)
.unwrap_err();
assert_eq!(
error.downcast_ref::<RefreshRefusal>(),
Some(&RefreshRefusal::MovedSinceCandidate)
);
}
#[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("needle-private-refresh".len())
.any(|window| window == b"needle-private-refresh")
);
}
#[test]
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, [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(session("private-refresh-claim"))
.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!(
reopened
.account_for_cookie(&cookie, Utc::now())
.unwrap()
.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, vec![corrupt]).unwrap());
drop(store);
assert!(AppSessionOwner::open(&path, &key).is_err());
}
}

View file

@ -1,218 +0,0 @@
//! What stands between the unauthenticated sign-in routes and the open internet.
//!
//! Browser binding. A Heimdall attempt handle is redeemable by whoever holds
//! it, so `begin` also mints a random secret, returns it to the beginning
//! browser as an HttpOnly cookie, and keeps only its hash against the handle.
//! `complete` must present that cookie, once, before the attempt expires: a
//! handle begun in one browser cannot be completed from another. This is the
//! OAuth `state` pattern (RFC 6749 section 10.12, CSRF on the redirect) and
//! the same binding PKCE (RFC 7636) gives a code: the party that starts the
//! flow holds a secret the interceptor never sees.
//!
//! Throttle. A fixed-window per-client counter on the same routes. Clients are
//! keyed by what the caller passes, which behind the reverse proxy is the
//! `X-Real-IP` value nginx sets.
use crate::app_session::secret_hash;
use chrono::{DateTime, Utc};
use rand::RngCore;
use std::{collections::HashMap, sync::Mutex};
pub(crate) const BEGIN_COOKIE: &str = "ghostlight_auth";
/// How long a begun sign-in may stay open, whatever Heimdall allows.
pub(crate) const BEGIN_TTL_SECONDS: i64 = 600;
const MAX_PENDING: usize = 4096;
const WINDOW_SECONDS: i64 = 60;
const MAX_PER_WINDOW: u32 = 30;
const MAX_CLIENTS: usize = 8192;
struct Pending {
secret_hash: String,
expires_at: DateTime<Utc>,
/// The invite the browser presented at begin, held in memory only and for
/// no longer than the attempt lives. Spent by `catalog.sign_in` at complete.
invite: Option<String>,
}
#[derive(Default)]
pub(crate) struct AuthGuard {
pending: Mutex<HashMap<String, Pending>>,
windows: Mutex<HashMap<String, (i64, u32)>>,
}
impl AuthGuard {
/// Opens a binding for `handle` and returns the secret for the browser's
/// cookie, or `None` when too many sign-ins are already open.
pub(crate) fn start(
&self,
handle: &str,
invite: Option<String>,
expires_at: DateTime<Utc>,
now: DateTime<Utc>,
) -> Option<String> {
let mut pending = self.pending.lock().expect("auth guard");
pending.retain(|_, attempt| attempt.expires_at > now);
if pending.len() >= MAX_PENDING {
return None;
}
let mut bytes = [0_u8; 32];
rand::rng().fill_bytes(&mut bytes);
let secret: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
pending.insert(
handle.to_owned(),
Pending {
secret_hash: secret_hash(&secret),
expires_at,
invite,
},
);
Some(secret)
}
/// Whether `secret` is the live binding for `handle`; spends nothing.
pub(crate) fn matches(&self, handle: &str, secret: &str, now: DateTime<Utc>) -> bool {
self.pending
.lock()
.expect("auth guard")
.get(handle)
.is_some_and(|attempt| attempt.expires_at > now && attempt.secret_hash == secret_hash(secret))
}
/// Spends the binding: `Some` exactly once for a live, matching secret,
/// carrying the invite bound at begin; `None` when this is not that
/// browser's attempt.
pub(crate) fn consume(&self, handle: &str, secret: &str, now: DateTime<Utc>) -> Option<Option<String>> {
let mut pending = self.pending.lock().expect("auth guard");
if !pending
.get(handle)
.is_some_and(|attempt| attempt.expires_at > now && attempt.secret_hash == secret_hash(secret))
{
return None;
}
pending.remove(handle).map(|attempt| attempt.invite)
}
/// Counts one request from `client`; false once it has used its window.
pub(crate) fn allow(&self, client: &str, now: DateTime<Utc>) -> bool {
let window = now.timestamp().div_euclid(WINDOW_SECONDS);
let mut windows = self.windows.lock().expect("auth guard");
if windows.len() >= MAX_CLIENTS {
windows.retain(|_, (started, _)| *started == window);
if windows.len() >= MAX_CLIENTS && !windows.contains_key(client) {
return false;
}
}
let entry = windows.entry(client.to_owned()).or_insert((window, 0));
if entry.0 != window {
*entry = (window, 0);
}
entry.1 += 1;
entry.1 <= MAX_PER_WINDOW
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Duration;
#[test]
fn a_binding_is_spent_once_and_only_by_its_own_secret_and_handle() {
let guard = AuthGuard::default();
let now = Utc::now();
let secret = guard.start("handle-a", None, now + Duration::minutes(5), now).unwrap();
let other = guard.start("handle-b", None, now + Duration::minutes(5), now).unwrap();
assert_ne!(secret, other);
assert_eq!(secret.len(), 64);
assert!(guard.matches("handle-a", &secret, now));
assert!(!guard.matches("handle-a", &other, now), "another begin's secret");
assert!(!guard.matches("handle-a", "", now));
assert!(!guard.matches("handle-unknown", &secret, now));
assert!(guard.consume("handle-a", &other, now).is_none());
assert!(guard.matches("handle-a", &secret, now), "a refused spend keeps the binding");
assert!(guard.consume("handle-a", &secret, now).is_some());
assert!(guard.consume("handle-a", &secret, now).is_none(), "single use");
assert!(!guard.matches("handle-a", &secret, now));
assert!(guard.consume("handle-b", &other, now).is_some(), "the other binding is untouched");
}
#[test]
fn the_invite_bound_at_begin_comes_back_once_to_the_beginning_browser_alone() {
let guard = AuthGuard::default();
let now = Utc::now();
let soon = now + Duration::minutes(5);
let secret = guard.start("h", Some("tok".into()), soon, now).unwrap();
let other = guard.start("g", None, soon, now).unwrap();
assert_eq!(guard.consume("h", &other, now), None, "another browser gets nothing and spends nothing");
assert_eq!(guard.consume("h", &secret, now), Some(Some("tok".into())));
assert_eq!(guard.consume("h", &secret, now), None);
assert_eq!(guard.consume("g", &other, now), Some(None), "no invite bound is still this browser's");
}
#[test]
fn a_binding_expires() {
let guard = AuthGuard::default();
let now = Utc::now();
let expiry = now + Duration::minutes(5);
let secret = guard.start("h", None, expiry, now).unwrap();
assert!(guard.matches("h", &secret, expiry - Duration::seconds(1)));
assert!(!guard.matches("h", &secret, expiry));
assert!(guard.consume("h", &secret, expiry).is_none());
assert!(guard.consume("h", &secret, expiry + Duration::hours(1)).is_none());
}
#[test]
fn expired_bindings_are_dropped_and_the_open_set_is_bounded() {
let guard = AuthGuard::default();
let now = Utc::now();
for index in 0..MAX_PENDING {
assert!(guard.start(&format!("h{index}"), None, now + Duration::minutes(1), now).is_some());
}
assert!(guard.start("one-too-many", None, now + Duration::minutes(1), now).is_none());
let later = now + Duration::minutes(2);
assert!(guard.start("after-expiry", None, later + Duration::minutes(1), later).is_some());
assert_eq!(guard.pending.lock().unwrap().len(), 1);
}
#[test]
fn a_client_gets_a_fixed_window_and_clients_are_counted_apart() {
let guard = AuthGuard::default();
let start = DateTime::<Utc>::from_timestamp(1_000_020, 0).unwrap();
assert_eq!(start.timestamp() % WINDOW_SECONDS, 0);
for _ in 0..MAX_PER_WINDOW {
assert!(guard.allow("203.0.113.9", start));
}
assert!(!guard.allow("203.0.113.9", start + Duration::seconds(59)));
assert!(guard.allow("203.0.113.10", start + Duration::seconds(59)), "another client");
assert!(guard.allow("203.0.113.9", start + Duration::seconds(60)), "the next window");
}
#[test]
fn a_full_client_table_forgets_old_windows_and_refuses_strangers_not_counts() {
let guard = AuthGuard::default();
let start = DateTime::<Utc>::from_timestamp(1_000_020, 0).unwrap();
for index in 0..MAX_CLIENTS {
guard.allow(&format!("old{index}"), start);
}
let later = start + Duration::seconds(WINDOW_SECONDS);
for _ in 0..MAX_PER_WINDOW {
assert!(guard.allow("busy", later));
}
for index in 0..MAX_CLIENTS {
guard.allow(&format!("fresh{index}"), later);
}
assert!(!guard.allow("busy", later), "pruning keeps the current window's counts");
assert!(guard.windows.lock().unwrap().len() <= MAX_CLIENTS);
assert!(!guard.allow("brand-new", later), "a full table refuses a stranger rather than forget everyone");
}
#[test]
fn a_binding_is_dead_at_its_expiry_instant_and_dropped_by_the_next_start() {
let guard = AuthGuard::default();
let now = Utc::now();
guard.start("old", None, now + Duration::minutes(1), now).unwrap();
let at_expiry = now + Duration::minutes(1);
guard.start("new", None, at_expiry + Duration::minutes(1), at_expiry).unwrap();
assert_eq!(guard.pending.lock().unwrap().len(), 1, "expiry is exclusive");
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,699 +0,0 @@
//! The catalog: which worlds exist, which timelines belong to them, and where
//! each player is standing.
//!
//! The kernel owns world state and `PlayTable` owns turns; this store owns only
//! the rows that say which store belongs to whom. One row holds all three
//! tables, written by compare-and-swap, so a world record and its root
//! timeline can never be seen apart.
use anyhow::{Context, bail, ensure};
use chrono::{DateTime, Utc};
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, path::Path};
use uuid::Uuid;
pub(crate) const STORE_TYPE: &str = "ghostlight.dungeon_catalog.v1";
const STORE_KEY: &str = "primary";
/// A world and who may play it. `snapshot_id` is the vault snapshot the world
/// was seeded from, `None` for a world that began unseeded.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct WorldRecord {
pub(crate) world_id: String,
pub(crate) title: String,
pub(crate) owner: String,
pub(crate) snapshot_id: Option<String>,
pub(crate) created_at: DateTime<Utc>,
}
/// One playable line of a world. A fork records `(parent timeline, commit)`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Timeline {
pub(crate) id: String,
pub(crate) world_id: String,
pub(crate) parent: Option<(String, String)>,
}
/// Where a timeline's seed stands. A timeline with no entry is Ready: it
/// began unseeded, or its seed finished. The entry is persisted with the
/// timeline so a restart cannot turn a Draft into a playable world.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum SeedStatus {
Seeding,
Failed(String),
}
/// A player's one pointer: which timeline they are in, and where they mean to
/// go next. Keyed by principal, so every device of one player reads the same.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct PlayerSession {
pub(crate) principal: String,
pub(crate) timeline: Option<String>,
pub(crate) destination: Option<String>,
}
/// A Dungeon account: minted here, linked to the external identities Heimdall
/// authenticates. Heimdall holds no accounts.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Account {
pub(crate) account_id: String,
pub(crate) identities: Vec<String>,
pub(crate) created_at: DateTime<Utc>,
}
/// Why a sign-in got no account.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub(crate) enum SignInRefusal {
#[error("this sign-in has no account and no live invite")]
NoInvite,
}
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CatalogState {
worlds: BTreeMap<String, WorldRecord>,
timelines: BTreeMap<String, Timeline>,
players: BTreeMap<String, PlayerSession>,
accounts: BTreeMap<String, Account>,
/// External identity (a Heimdall account id) to Dungeon account id.
identities: BTreeMap<String, String>,
/// Unconsumed invites: sha256 of the token to its expiry. Only the hash is kept.
invites: BTreeMap<String, DateTime<Utc>>,
/// Seeds that are not Ready, by timeline. Absent in a catalog that has
/// never held one, so older catalogs keep their canonical encoding.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
seeds: BTreeMap<String, SeedStatus>,
}
pub(crate) struct Catalog {
store: OwnedRedbMessagePackBackingStore,
row: CultCacheEnvelope,
state: CatalogState,
}
/// `timeline:<uuid>`: the only shape that names a timeline, so the id can be a
/// directory name without ever carrying a path.
pub(crate) fn timeline_id(uuid: Uuid) -> String {
format!("timeline:{}", uuid.hyphenated())
}
/// The directory name a timeline id maps to, or `None` for anything that is
/// not exactly `timeline:<canonical uuid>`.
pub(crate) fn timeline_directory_name(id: &str) -> Option<String> {
let uuid = Uuid::parse_str(id.strip_prefix("timeline:")?).ok()?;
(timeline_id(uuid) == id).then(|| uuid.hyphenated().to_string())
}
impl Catalog {
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
store
.validate_path_identity()
.context("catalog store path identity is invalid")?;
let rows = store.pull_all()?;
let (row, state) = match rows.as_slice() {
[] => {
let state = CatalogState::default();
let row = envelope(&state)?;
ensure!(
store.compare_and_swap_batch(&[], vec![row.clone()])?,
"catalog store changed during initialization"
);
(row, state)
}
[row]
if row.r#type == STORE_TYPE
&& row.key == STORE_KEY
&& row.schema_id.as_deref() == Some(STORE_TYPE) =>
{
let state: CatalogState =
rmp_serde::from_slice(&row.payload).context("catalog state is corrupt")?;
ensure!(
rmp_serde::to_vec_named(&state)? == row.payload,
"catalog state is not canonical"
);
(row.clone(), state)
}
_ => bail!("catalog store contains foreign records"),
};
Ok(Self { store, row, state })
}
pub(crate) fn validate_custody(&self) -> anyhow::Result<()> {
self.store
.validate_path_identity()
.context("catalog store path identity changed")
}
fn commit(&mut self, next: CatalogState) -> anyhow::Result<()> {
let next_row = envelope(&next)?;
let swapped = self
.store
.compare_and_swap_batch(std::slice::from_ref(&self.row), vec![next_row.clone()]);
ensure!(
matches!(swapped, Ok(true)),
"catalog commit outcome is uncertain; sole ownership was lost"
);
self.row = next_row;
self.state = next;
Ok(())
}
/// The one function that makes a timeline. Begin passes the new world's
/// record beside its root timeline; a fork passes `None` and a parent. The
/// player's pointer moves to the new timeline in the same write.
pub(crate) fn mint_timeline(
&mut self,
new_world: Option<WorldRecord>,
timeline: Timeline,
) -> anyhow::Result<()> {
ensure!(
timeline_directory_name(&timeline.id).is_some(),
"timeline id is not canonical"
);
ensure!(
!self.state.timelines.contains_key(&timeline.id),
"timeline already exists"
);
let mut next = self.state.clone();
let owner = match new_world {
Some(record) => {
ensure!(
record.world_id == timeline.world_id && timeline.parent.is_none(),
"a new world's first timeline is its root"
);
ensure!(
!next.worlds.contains_key(&record.world_id),
"world record already exists"
);
let owner = record.owner.clone();
next.worlds.insert(record.world_id.clone(), record);
owner
}
None => {
let (parent, _) = timeline
.parent
.as_ref()
.context("a timeline in an existing world names its parent")?;
let parent = next.timelines.get(parent).context("parent timeline is unknown")?;
ensure!(parent.world_id == timeline.world_id, "fork crosses worlds");
next.worlds
.get(&timeline.world_id)
.context("world record is unknown")?
.owner
.clone()
}
};
let player = next
.players
.entry(owner.clone())
.or_insert_with(|| PlayerSession {
principal: owner,
timeline: None,
destination: None,
});
player.timeline = Some(timeline.id.clone());
next.timelines.insert(timeline.id.clone(), timeline);
self.commit(next)
}
/// Mints a single-use invite and returns its token, the only time it is
/// visible. The catalog keeps its hash and expiry.
pub(crate) fn mint_invite(&mut self, now: DateTime<Utc>, ttl: chrono::Duration) -> anyhow::Result<String> {
let token = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
let mut next = self.state.clone();
next.invites.retain(|_, expires| *expires > now);
next.invites.insert(token_hash(&token), now + ttl);
self.commit(next)?;
Ok(token)
}
/// Whether `token` names an invite that is live at `now`. Read-only: it
/// spends nothing, so a begin can ask it before Heimdall is.
pub(crate) fn invite_is_live(&self, token: &str, now: DateTime<Utc>) -> bool {
self.hash_is_live(&token_hash(token), now)
}
fn hash_is_live(&self, hash: &str, now: DateTime<Utc>) -> bool {
self.state.invites.get(hash).is_some_and(|expires| *expires > now)
}
/// The account an authenticated external identity lands on. A known
/// identity reaches its account, on any device. An unknown one needs a
/// live invite, which is consumed in the same write that creates the
/// account and binds the identity. No account and no live invite: refused,
/// never enrolled. Returns the account's principal key, the identity the
/// account was first created from.
pub(crate) fn sign_in(
&mut self,
identity: &str,
invite: Option<&str>,
now: DateTime<Utc>,
) -> anyhow::Result<Result<String, SignInRefusal>> {
if let Some(account) = self.state.identities.get(identity) {
let account = &self.state.accounts[account];
return Ok(Ok(account.identities[0].clone()));
}
let Some(hash) = invite.map(token_hash).filter(|hash| self.hash_is_live(hash, now)) else {
return Ok(Err(SignInRefusal::NoInvite));
};
let mut next = self.state.clone();
next.invites.remove(&hash);
next.invites.retain(|_, expires| *expires > now);
let account_id = format!("account:{}", Uuid::new_v4());
next.identities.insert(identity.to_owned(), account_id.clone());
next.accounts.insert(
account_id.clone(),
Account {
account_id,
identities: vec![identity.to_owned()],
created_at: now,
},
);
self.commit(next)?;
Ok(Ok(identity.to_owned()))
}
/// Links a second external identity to the account `principal` names.
/// Test-only until a second-identity link is a designed feature.
#[cfg(test)]
pub(crate) fn link_identity(&mut self, principal: &str, identity: &str) -> anyhow::Result<()> {
let account_id = self.state.identities[principal].clone();
let mut next = self.state.clone();
next.identities.insert(identity.to_owned(), account_id.clone());
next.accounts.get_mut(&account_id).unwrap().identities.push(identity.to_owned());
self.commit(next)
}
pub(crate) fn timeline(&self, id: &str) -> Option<&Timeline> {
self.state.timelines.get(id)
}
/// The seed status of a timeline, `None` when it is Ready.
pub(crate) fn seed_status(&self, timeline: &str) -> Option<&SeedStatus> {
self.state.seeds.get(timeline)
}
/// Claims the seed of `timeline`, durably; false when one is running.
pub(crate) fn claim_seed(&mut self, timeline: &str) -> anyhow::Result<bool> {
if self.state.seeds.get(timeline) == Some(&SeedStatus::Seeding) {
return Ok(false);
}
self.settle_seed(timeline, Some(SeedStatus::Seeding))?;
Ok(true)
}
/// Records where a seed stands; `None` is Ready.
pub(crate) fn settle_seed(&mut self, timeline: &str, status: Option<SeedStatus>) -> anyhow::Result<()> {
let mut next = self.state.clone();
match status {
Some(status) => next.seeds.insert(timeline.to_owned(), status),
None => next.seeds.remove(timeline),
};
self.commit(next)
}
/// Marks every seed still Seeding as Failed. A seed runs only inside the
/// process that claimed it, so one still Seeding at startup was cut off
/// by a restart. Returns how many.
pub(crate) fn fail_interrupted_seeds(&mut self) -> anyhow::Result<usize> {
let mut next = self.state.clone();
let mut count = 0;
for status in next.seeds.values_mut().filter(|status| **status == SeedStatus::Seeding) {
*status = SeedStatus::Failed("seeding was interrupted by a restart".into());
count += 1;
}
if count > 0 {
self.commit(next)?;
}
Ok(count)
}
pub(crate) fn world(&self, world_id: &str) -> Option<&WorldRecord> {
self.state.worlds.get(world_id)
}
/// The timeline and its world, only if `principal` owns the world.
pub(crate) fn owned_timeline(
&self,
principal: &str,
id: &str,
) -> Option<(&Timeline, &WorldRecord)> {
let timeline = self.state.timelines.get(id)?;
let world = self.state.worlds.get(&timeline.world_id)?;
(world.owner == principal).then_some((timeline, world))
}
pub(crate) fn timelines_of(&self, principal: &str) -> Vec<(&Timeline, &WorldRecord)> {
self.state
.timelines
.values()
.filter_map(|timeline| {
let world = self.state.worlds.get(&timeline.world_id)?;
(world.owner == principal).then_some((timeline, world))
})
.collect()
}
pub(crate) fn player(&self, principal: &str) -> Option<&PlayerSession> {
self.state.players.get(principal)
}
/// Moves the player's pointer to a timeline they own.
pub(crate) fn set_current(&mut self, principal: &str, timeline: &str) -> anyhow::Result<()> {
ensure!(
self.owned_timeline(principal, timeline).is_some(),
"that timeline is not this player's"
);
let mut next = self.state.clone();
next.players
.entry(principal.to_owned())
.or_insert_with(|| PlayerSession {
principal: principal.to_owned(),
timeline: None,
destination: None,
})
.timeline = Some(timeline.to_owned());
self.commit(next)
}
}
fn envelope(state: &CatalogState) -> anyhow::Result<CultCacheEnvelope> {
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_TYPE.into()),
})
}
#[cfg(test)]
mod tests {
use super::*;
fn record(world: &str, owner: &str) -> WorldRecord {
WorldRecord {
world_id: world.into(),
title: "t".into(),
owner: owner.into(),
snapshot_id: Some("vault-snapshot:abc".into()),
created_at: Utc::now(),
}
}
fn root(world: &str) -> Timeline {
Timeline {
id: timeline_id(Uuid::new_v4()),
world_id: world.into(),
parent: None,
}
}
#[test]
fn a_timeline_id_is_a_directory_name_or_nothing() {
let good = timeline_id(Uuid::new_v4());
assert!(timeline_directory_name(&good).is_some());
for bad in [
"timeline:../../etc",
"timeline:",
"../timeline:00000000-0000-4000-8000-000000000000",
"timeline:00000000-0000-4000-8000-000000000000/..",
"timeline:00000000000040008000000000000000",
"timeline:00000000-0000-4000-8000-00000000000A",
] {
assert!(timeline_directory_name(bad).is_none(), "{bad}");
}
}
#[test]
fn a_restart_reads_back_what_begin_wrote() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("catalog.cc");
let line = root("w1");
{
let mut catalog = Catalog::open(&path).unwrap();
catalog.mint_timeline(Some(record("w1", "alice")), line.clone()).unwrap();
}
let catalog = Catalog::open(&path).unwrap();
assert_eq!(catalog.timeline(&line.id), Some(&line));
assert_eq!(catalog.world("w1").unwrap().snapshot_id.as_deref(), Some("vault-snapshot:abc"));
assert_eq!(catalog.player("alice").unwrap().timeline.as_deref(), Some(line.id.as_str()));
}
#[test]
fn only_the_owner_reaches_a_timeline() {
let directory = tempfile::tempdir().unwrap();
let mut catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
let line = root("w1");
catalog.mint_timeline(Some(record("w1", "alice")), line.clone()).unwrap();
assert!(catalog.owned_timeline("alice", &line.id).is_some());
assert!(catalog.owned_timeline("mallory", &line.id).is_none());
assert!(catalog.timelines_of("mallory").is_empty());
assert!(catalog.set_current("mallory", &line.id).is_err());
}
/// A seed's status is part of the catalog row: it survives a reopen, and a
/// seed still Seeding when the process starts again reads Failed, never
/// Ready.
#[test]
fn a_seed_status_persists_and_a_restart_fails_a_running_seed() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("catalog.cc");
{
let mut catalog = Catalog::open(&path).unwrap();
assert!(catalog.claim_seed("timeline:a").unwrap());
assert!(!catalog.claim_seed("timeline:a").unwrap(), "one seed at a time");
catalog.settle_seed("timeline:b", Some(SeedStatus::Failed("no model".into()))).unwrap();
}
let mut catalog = Catalog::open(&path).unwrap();
assert_eq!(catalog.seed_status("timeline:a"), Some(&SeedStatus::Seeding));
assert_eq!(catalog.fail_interrupted_seeds().unwrap(), 1);
assert!(matches!(catalog.seed_status("timeline:a"), Some(SeedStatus::Failed(reason)) if reason.contains("restart")));
assert_eq!(catalog.seed_status("timeline:b"), Some(&SeedStatus::Failed("no model".into())));
assert_eq!(catalog.fail_interrupted_seeds().unwrap(), 0);
assert!(catalog.claim_seed("timeline:a").unwrap(), "a failed seed may be claimed again");
catalog.settle_seed("timeline:a", None).unwrap();
catalog.settle_seed("timeline:b", None).unwrap();
drop(catalog);
assert_eq!(Catalog::open(&path).unwrap().seed_status("timeline:a"), None);
}
#[test]
fn a_fork_is_minted_by_the_same_function_and_must_name_a_real_parent() {
let directory = tempfile::tempdir().unwrap();
let mut catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
let first = root("w1");
catalog.mint_timeline(Some(record("w1", "alice")), first.clone()).unwrap();
let fork = Timeline {
id: timeline_id(Uuid::new_v4()),
world_id: "w1".into(),
parent: Some((first.id.clone(), "commit-1".into())),
};
catalog.mint_timeline(None, fork.clone()).unwrap();
assert_eq!(catalog.player("alice").unwrap().timeline.as_deref(), Some(fork.id.as_str()));
let orphan = Timeline {
id: timeline_id(Uuid::new_v4()),
world_id: "w1".into(),
parent: Some(("timeline:00000000-0000-4000-8000-000000000000".into(), "c".into())),
};
assert!(catalog.mint_timeline(None, orphan).is_err());
assert!(catalog.mint_timeline(None, root("w1")).is_err());
}
}
fn token_hash(token: &str) -> String {
use sha2::{Digest, Sha256};
format!("{:x}", Sha256::digest(token.as_bytes()))
}
#[cfg(test)]
mod sign_in_tests {
use super::*;
use chrono::Duration;
fn catalog() -> (tempfile::TempDir, Catalog) {
let directory = tempfile::tempdir().unwrap();
let catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
(directory, catalog)
}
#[test]
fn an_invite_is_single_use() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
assert!(catalog.sign_in("google:deru", Some(&token), now).unwrap().is_ok());
// The same invite for a second, different identity is spent.
assert_eq!(
catalog.sign_in("google:other", Some(&token), now).unwrap(),
Err(SignInRefusal::NoInvite)
);
}
#[test]
fn an_expired_invite_is_refused() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let later = now + Duration::hours(2);
assert_eq!(
catalog.sign_in("google:deru", Some(&token), later).unwrap(),
Err(SignInRefusal::NoInvite)
);
assert!(catalog.state.accounts.is_empty());
}
#[test]
fn no_account_and_no_invite_is_refused_and_enrols_nobody() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
assert_eq!(catalog.sign_in("google:deru", None, now).unwrap(), Err(SignInRefusal::NoInvite));
assert_eq!(
catalog.sign_in("google:deru", Some("not-a-token"), now).unwrap(),
Err(SignInRefusal::NoInvite)
);
assert!(catalog.state.accounts.is_empty());
}
#[test]
fn the_same_identity_on_a_second_device_lands_on_the_same_account_without_an_invite() {
let (directory, mut catalog) = catalog();
let now = Utc::now();
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let first = catalog.sign_in("google:deru", Some(&token), now).unwrap().unwrap();
let second = catalog.sign_in("google:deru", None, now).unwrap().unwrap();
assert_eq!(first, second);
assert_eq!(catalog.state.accounts.len(), 1);
// And it survives a restart.
drop(catalog);
let mut reopened = Catalog::open(directory.path().join("catalog.cc")).unwrap();
assert_eq!(reopened.sign_in("google:deru", None, now).unwrap().unwrap(), first);
}
#[test]
fn only_the_minted_token_redeems_its_invite_and_the_catalog_keeps_its_hash_alone() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
assert_eq!(token.len(), 64);
assert!(token.chars().all(|c| c.is_ascii_hexdigit()));
assert_ne!(token, catalog.mint_invite(now, Duration::hours(1)).unwrap());
for wrong in ["", "x", &token[1..], &format!("{token}0"), &token.to_uppercase()] {
assert_eq!(
catalog.sign_in("google:deru", Some(wrong), now).unwrap(),
Err(SignInRefusal::NoInvite),
"{wrong:?} must not redeem a live invite"
);
}
assert!(catalog.state.invites.contains_key(&token_hash(&token)));
assert!(!catalog.state.invites.contains_key(&token), "the raw token is never stored");
assert!(catalog.sign_in("google:deru", Some(&token), now).unwrap().is_ok());
}
#[test]
fn the_token_hash_is_sha256_hex() {
assert_eq!(
token_hash("abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_ne!(token_hash("abc"), token_hash("abd"));
}
#[test]
fn an_invite_dies_at_its_expiry_instant_and_spent_or_dead_invites_are_pruned() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let short = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let long = catalog.mint_invite(now, Duration::hours(3)).unwrap();
let at_expiry = now + Duration::hours(1);
assert_eq!(
catalog.sign_in("a", Some(&short), at_expiry).unwrap(),
Err(SignInRefusal::NoInvite),
"an invite is not live at the instant it expires"
);
assert!(
catalog.sign_in("a", Some(&short), at_expiry - Duration::seconds(1)).unwrap().is_ok(),
"and is live a second before"
);
assert_eq!(catalog.state.invites.len(), 1, "the spent invite is gone");
// Redeeming the long invite after the short one died prunes nothing live.
assert!(catalog.sign_in("b", Some(&long), at_expiry).unwrap().is_ok());
assert!(catalog.state.invites.is_empty());
// A mint prunes dead invites.
let stale = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let later = now + Duration::hours(2);
let fresh = catalog.mint_invite(later, Duration::hours(1)).unwrap();
assert_eq!(catalog.state.invites.len(), 1);
assert!(!catalog.state.invites.contains_key(&token_hash(&stale)));
assert!(catalog.state.invites.contains_key(&token_hash(&fresh)));
assert_eq!(catalog.state.invites[&token_hash(&fresh)], later + Duration::hours(1));
}
#[test]
fn a_new_account_is_bound_to_its_identity_and_returns_it_as_the_principal() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let principal = catalog.sign_in("google:deru", Some(&token), now).unwrap().unwrap();
assert_eq!(principal, "google:deru");
let account_id = &catalog.state.identities["google:deru"];
let account = &catalog.state.accounts[account_id];
assert_eq!(&account.account_id, account_id);
assert_eq!(account.identities, vec!["google:deru".to_owned()]);
assert_eq!(account.created_at, now);
assert!(account_id.starts_with("account:"));
}
#[test]
fn mint_and_redemption_drop_invites_dead_at_that_very_instant() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let dying = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let at = now + Duration::hours(1);
let minted = catalog.mint_invite(at, Duration::hours(1)).unwrap();
assert!(!catalog.state.invites.contains_key(&token_hash(&dying)), "mint prunes at the instant");
let dying = catalog.mint_invite(at, Duration::hours(1) - Duration::seconds(1)).unwrap();
let later = at + Duration::hours(1) - Duration::seconds(1);
assert!(catalog.sign_in("a", Some(&minted), later).unwrap().is_ok());
assert!(
!catalog.state.invites.contains_key(&token_hash(&dying)),
"redemption prunes an invite that expires at that instant"
);
}
#[test]
fn a_store_holding_a_row_of_the_wrong_type_key_or_schema_is_refused() {
for (row_type, key, schema) in [
("ghostlight.other.v1", STORE_KEY, STORE_TYPE),
(STORE_TYPE, "secondary", STORE_TYPE),
(STORE_TYPE, STORE_KEY, "ghostlight.other.v1"),
] {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("catalog.cc");
let store = OwnedRedbMessagePackBackingStore::new(&path).unwrap();
let mut row = envelope(&CatalogState::default()).unwrap();
row.r#type = row_type.into();
row.key = key.into();
row.schema_id = Some(schema.into());
assert!(store.compare_and_swap_batch(&[], vec![row]).unwrap());
drop(store);
assert!(Catalog::open(&path).is_err(), "{row_type} {key} {schema}");
}
}
#[test]
fn custody_fails_once_the_store_path_is_replaced() {
let (directory, catalog) = catalog();
catalog.validate_custody().unwrap();
let path = directory.path().join("catalog.cc");
std::fs::rename(&path, directory.path().join("displaced.cc")).unwrap();
std::fs::File::create(&path).unwrap();
assert!(catalog.validate_custody().is_err());
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,211 +0,0 @@
//! The operator's invite mint.
//!
//! Invites are minted on a Unix domain socket owned by the service user, mode
//! 0600, under the state root. The HTTP router has no invite path, so the
//! reverse proxy has nothing to forward: reaching the mint takes a local
//! process running as the service user, not a peer-address test.
//!
//! Wire: the client writes one line, the number of hours. The daemon answers
//! one JSON line, `{"invite": "<token>"}` or `{"error": "<why>"}`.
use crate::catalog::Catalog;
use anyhow::{Context, bail, ensure};
use chrono::Utc;
use serde_json::{Value, json};
use std::{
os::unix::{
fs::{FileTypeExt, PermissionsExt},
net::UnixStream as StdUnixStream,
},
path::{Path, PathBuf},
sync::Arc,
};
use tokio::{
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
net::{UnixListener, UnixStream},
sync::Mutex,
};
/// An invite lives between one hour and thirty days.
const MAX_HOURS: u32 = 24 * 30;
const REQUEST_LIMIT: u64 = 32;
pub(crate) fn socket_path(runtime_root: &Path) -> PathBuf {
runtime_root.join("service").join("invite.sock")
}
/// Binds the mint socket, replacing a stale socket left by a previous run and
/// refusing anything else at the path. The socket is created under a 0177 umask
/// so it is never visible with wider permissions.
pub(crate) fn bind(path: &Path) -> anyhow::Result<UnixListener> {
match std::fs::symlink_metadata(path) {
Ok(metadata) => {
ensure!(
metadata.file_type().is_socket(),
"{} exists and is not a socket",
path.display()
);
std::fs::remove_file(path).context("removing a stale invite socket")?;
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error).context("inspecting the invite socket path"),
}
// SAFETY: umask only swaps the process file-creation mask.
let previous = unsafe { libc::umask(0o177) };
let bound = UnixListener::bind(path);
unsafe { libc::umask(previous) };
let listener = bound.with_context(|| format!("binding {}", path.display()))?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
Ok(listener)
}
pub(crate) async fn serve(listener: UnixListener, catalog: Arc<Mutex<Catalog>>) -> anyhow::Result<()> {
loop {
let (stream, _) = listener.accept().await.context("accepting on the invite socket")?;
let catalog = catalog.clone();
tokio::spawn(async move {
if let Err(error) = answer(stream, &catalog).await {
tracing::warn!(%error, "an invite request failed");
}
});
}
}
async fn answer(stream: UnixStream, catalog: &Mutex<Catalog>) -> anyhow::Result<()> {
let (read, mut write) = stream.into_split();
let mut line = String::new();
BufReader::new(read.take(REQUEST_LIMIT)).read_line(&mut line).await?;
let reply = match mint(catalog, line.trim()).await {
Ok(token) => json!({"invite": token}),
Err(message) => json!({"error": message}),
};
write.write_all(format!("{reply}\n").as_bytes()).await?;
Ok(())
}
async fn mint(catalog: &Mutex<Catalog>, hours: &str) -> Result<String, String> {
let hours: u32 = hours
.parse()
.map_err(|_| "the request is a whole number of hours".to_owned())?;
if hours == 0 || hours > MAX_HOURS {
return Err("an invite lives between 1 hour and 30 days".into());
}
catalog
.lock()
.await
.mint_invite(Utc::now(), chrono::Duration::hours(i64::from(hours)))
.map_err(|error| {
tracing::error!(%error, "an invite could not be minted");
"the invite could not be minted".to_owned()
})
}
/// The operator command: asks the running daemon at `runtime_root` for an invite.
pub(crate) fn request(runtime_root: &Path, hours: u32) -> anyhow::Result<String> {
use std::io::{BufRead, Write};
let path = socket_path(runtime_root);
let mut stream = StdUnixStream::connect(&path)
.with_context(|| format!("no daemon is listening at {}", path.display()))?;
writeln!(stream, "{hours}")?;
let mut reply = String::new();
std::io::BufReader::new(stream).read_line(&mut reply)?;
let reply: Value = serde_json::from_str(&reply).context("the daemon's answer is not JSON")?;
match (reply["invite"].as_str(), reply["error"].as_str()) {
(Some(token), _) => Ok(token.to_owned()),
(None, Some(error)) => bail!("{error}"),
(None, None) => bail!("the daemon's answer names neither an invite nor an error"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::MetadataExt;
fn catalog(directory: &Path) -> Arc<Mutex<Catalog>> {
Arc::new(Mutex::new(Catalog::open(directory.join("catalog.cc")).unwrap()))
}
async fn serving(root: &Path) -> Arc<Mutex<Catalog>> {
std::fs::create_dir_all(root.join("service")).unwrap();
let catalog = catalog(root);
let listener = bind(&socket_path(root)).unwrap();
tokio::spawn(serve(listener, catalog.clone()));
catalog
}
async fn ask(root: &Path, hours: u32) -> anyhow::Result<String> {
let root = root.to_owned();
tokio::task::spawn_blocking(move || request(&root, hours)).await.unwrap()
}
#[tokio::test]
async fn the_socket_is_private_and_its_token_enrols_exactly_once() {
let directory = tempfile::tempdir().unwrap();
let catalog = serving(directory.path()).await;
let mode = std::fs::metadata(socket_path(directory.path())).unwrap().mode();
assert_eq!(mode & 0o777, 0o600, "mode {mode:o}");
let token = ask(directory.path(), 2).await.unwrap();
let mut catalog = catalog.lock().await;
assert!(catalog.sign_in("google:deru", Some(&token), Utc::now()).unwrap().is_ok());
assert!(catalog.sign_in("google:other", Some(&token), Utc::now()).unwrap().is_err());
}
#[tokio::test]
async fn an_invite_lives_one_hour_to_thirty_days_and_expires_at_its_hours() {
let directory = tempfile::tempdir().unwrap();
let catalog = serving(directory.path()).await;
for hours in [0, 24 * 30 + 1] {
let error = ask(directory.path(), hours).await.unwrap_err();
assert!(error.to_string().contains("between 1 hour and 30 days"), "{hours}: {error}");
}
let longest = ask(directory.path(), 24 * 30).await.unwrap();
let shortest = ask(directory.path(), 1).await.unwrap();
let mut catalog = catalog.lock().await;
let in_two_hours = Utc::now() + chrono::Duration::hours(2);
assert!(catalog.sign_in("a", Some(&shortest), in_two_hours).unwrap().is_err());
let in_thirty_days = Utc::now() + chrono::Duration::days(30) - chrono::Duration::minutes(1);
assert!(catalog.sign_in("b", Some(&longest), in_thirty_days).unwrap().is_ok());
}
#[tokio::test]
async fn binding_replaces_a_stale_socket_and_refuses_a_regular_file() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("invite.sock");
drop(bind(&path).unwrap());
assert!(path.exists(), "the dropped listener leaves its socket file");
drop(bind(&path).unwrap());
std::fs::remove_file(&path).unwrap();
std::fs::write(&path, "not a socket").unwrap();
assert!(bind(&path).is_err());
assert_eq!(std::fs::read_to_string(&path).unwrap(), "not a socket");
}
#[tokio::test]
async fn a_request_that_is_not_hours_mints_nothing() {
let directory = tempfile::tempdir().unwrap();
let catalog = serving(directory.path()).await;
let root = directory.path().to_owned();
let reply = tokio::task::spawn_blocking(move || {
use std::io::{Read, Write};
let mut stream = StdUnixStream::connect(socket_path(&root)).unwrap();
writeln!(stream, "soon").unwrap();
let mut reply = String::new();
stream.read_to_string(&mut reply).unwrap();
reply
})
.await
.unwrap();
assert!(reply.contains("error"), "{reply}");
assert!(catalog.lock().await.sign_in("x", Some("anything"), Utc::now()).unwrap().is_err());
}
#[tokio::test]
async fn a_socket_path_that_cannot_be_inspected_is_an_error_not_a_free_path() {
let directory = tempfile::tempdir().unwrap();
let file = directory.path().join("file");
std::fs::write(&file, "x").unwrap();
let error = bind(&file.join("invite.sock")).unwrap_err();
assert!(format!("{error:#}").contains("inspecting the invite socket path"), "{error:#}");
}
}

View file

@ -1,44 +0,0 @@
mod api;
mod app_session;
mod auth_guard;
mod begin;
mod catalog;
mod heimdall;
mod idunn_health;
mod invite;
mod page;
#[cfg(test)]
mod playtest;
mod play;
mod run_ahead;
mod runtime;
mod session_refresh;
mod state_layout;
#[cfg(test)]
mod test_support;
mod timelines;
mod turn_log;
mod vaults;
use anyhow::bail;
use std::path::PathBuf;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = std::env::args_os().skip(1).collect::<Vec<_>>();
let state_root = match args.as_slice() {
[command, flag, path, hours] if command == "invite" && flag == "--state-root" => {
let hours = hours.to_string_lossy().parse::<u32>()?;
println!("{}", invite::request(&PathBuf::from(path), hours)?);
return Ok(());
}
[command, flag, path, profile] if command == "import-vault" && flag == "--state-root" => {
println!("{}", vaults::import(&PathBuf::from(path), &profile.to_string_lossy())?);
return Ok(());
}
[flag, path] if flag == "--state-root" => Some(PathBuf::from(path)),
[] => None,
_ => bail!("usage: ghostlight-dungeon [--state-root PATH] | ghostlight-dungeon invite --state-root PATH HOURS | ghostlight-dungeon import-vault --state-root PATH PROFILE"),
};
runtime::run(state_root).await
}

View file

@ -1,44 +0,0 @@
//! The play page: three static files compiled into the binary and served from
//! the router's root. They hold presentation only and no secret, so there is
//! no page directory to resolve at run time and nothing to drift from the
//! binary.
use crate::runtime::AppState;
use axum::{
Router,
http::{HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
routing::get,
};
const INDEX: &str = include_str!("../page/index.html");
const STYLE: &str = include_str!("../page/page.css");
const SCRIPT: &str = include_str!("../page/page.js");
/// The page loads only its own script and style and talks only to its own
/// origin, so injected markup has nowhere to run or to send anything.
const POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; \
img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
fn file(content_type: &'static str, body: &'static str) -> Response {
(
StatusCode::OK,
[
(header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
(header::CACHE_CONTROL, HeaderValue::from_static("no-cache")),
(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(POLICY)),
(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer")),
(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")),
],
body,
)
.into_response()
}
pub(crate) fn router() -> Router<AppState> {
Router::new()
.route("/", get(|| async { file("text/html; charset=utf-8", INDEX) }))
.route("/page.css", get(|| async { file("text/css; charset=utf-8", STYLE) }))
.route("/page.js", get(|| async { file("text/javascript; charset=utf-8", SCRIPT) }))
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,108 +0,0 @@
//! Run-ahead: the bounded Active elaboration sweep.
//!
//! A world's scale deficit is answered after play starts, not before: one sweep
//! once Begin activates a seeded world, and one after each closed turn. Each
//! sweep starts at most `Scale::sweep_sessions` elaboration sessions and holds
//! at most `Scale::sweep_permits` permits, so a trigger cannot spend without
//! bound. The elaborator reads the evidence of the snapshot its timeline is
//! bound to, the same evidence the seed read; an unseeded world reads none.
use crate::{
begin::{Scale, Vaults},
catalog::Catalog,
timelines::TimelineHost,
};
use ghostlight::{EvidenceSource, NullEvidenceSource};
use std::sync::Arc;
use tokio::sync::{Mutex, Semaphore};
/// One bounded sweep of `host` over `evidence`. A sweep already running on this
/// timeline is the trigger's answer: the sweep that follows picks up what this
/// one would have.
pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc<dyn EvidenceSource>, scale: &Scale) {
let Ok(_running) = host.sweeping.try_lock() else {
return;
};
let runner = host.controllers.elaborator(evidence);
let permits = Arc::new(Semaphore::new(scale.sweep_permits));
if let Err(error) = runner.sweep(permits, scale.sweep_sessions).await {
tracing::warn!(%error, "run-ahead elaboration stopped");
}
}
/// The evidence a timeline's elaborator reads: its bound snapshot's, for the
/// era its world was pinned to, or none for a world that began unseeded. A
/// bound snapshot that cannot be reopened, or a world that cannot be read,
/// yields no evidence at all and no sweep, never a blind or era-blind one.
pub(crate) async fn evidence_of(
catalog: &Mutex<Catalog>,
vaults: &dyn Vaults,
host: &TimelineHost,
timeline: &str,
) -> Option<Arc<dyn EvidenceSource>> {
let snapshot_id = {
let catalog = catalog.lock().await;
let world = catalog.world(&catalog.timeline(timeline)?.world_id)?;
world.snapshot_id.clone()
};
let Some(id) = snapshot_id else {
return Some(Arc::new(NullEvidenceSource));
};
let era = host.world.snapshot().await.ok()?.era;
match vaults.evidence(&id, era.as_ref().map(|era| era.id.as_str())) {
Ok(evidence) => Some(evidence),
Err(error) => {
tracing::warn!(%error, timeline, "a seeded timeline's snapshot could not be reopened");
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
begin::{
BeginRequest, begin,
tests::{NoVaults, deferred_rig, one_vault, principal, request},
},
};
use uuid::Uuid;
/// A timeline's elaborator reads what its world was bound to: nothing
/// for an unseeded world, the snapshot for a seeded one, and no evidence
/// (so no sweep) for a snapshot that cannot be reopened or a timeline the
/// catalog does not know.
#[tokio::test]
async fn the_evidence_of_a_timeline_is_its_bound_snapshots() {
let vaults = one_vault();
let rig = deferred_rig();
let alice = principal("alice");
let unseeded = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &alice, request(Uuid::new_v4(), None))
.await
.unwrap();
let host = rig.timelines.host(&unseeded.timeline).await.unwrap();
assert!(
evidence_of(&rig.catalog, &NoVaults, &host, &unseeded.timeline).await.is_some(),
"an unseeded world reads none, and still sweeps"
);
let seeded = begin(
&rig.catalog,
&rig.timelines,
vaults.as_ref(),
&rig.scale,
&alice,
BeginRequest { era: Some("b".into()), ..request(Uuid::new_v4(), Some("delvehold")) },
)
.await
.unwrap();
let host = rig.timelines.host(&seeded.timeline).await.unwrap();
assert!(evidence_of(&rig.catalog, vaults.as_ref(), &host, &seeded.timeline).await.is_some());
assert!(
evidence_of(&rig.catalog, &NoVaults, &host, &seeded.timeline).await.is_none(),
"an unreadable snapshot is never swept blind"
);
let stranger = "timeline:00000000-0000-4000-8000-000000000000";
assert!(evidence_of(&rig.catalog, vaults.as_ref(), &host, stranger).await.is_none());
}
}

View file

@ -1,832 +0,0 @@
//! One-process runtime: admission, shared inference, the catalog and the
//! timeline registry, served over one router.
use crate::{
api,
app_session::AppSessionOwner,
auth_guard::AuthGuard,
begin::{Scale, Vaults},
catalog::Catalog,
heimdall::{HeimdallClient, HeimdallPort},
idunn_health::{
IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, ProcessWriteLeaseGuard, RuntimePresencePublisher,
TARGET as GHOSTLIGHT_TARGET,
},
session_refresh::run_refresh_loop,
state_layout::{admitted_runtime_root, prepare_admitted_state_layout},
timelines::{Shared, Timelines},
};
use anyhow::{Context, bail, ensure};
use axum::{
Json, Router,
body::Bytes,
extract::{ConnectInfo, DefaultBodyLimit, State},
http::{HeaderMap, HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
routing::{get, post},
};
use chrono::Utc;
use cultnet_rs::{
CultNetMessage, CultNetWireContract, GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA,
decode_cultnet_message_from_slice, encode_cultnet_message_to_vec,
};
use ghostlight::{
ConnectorBinding, ControllerModels, ControllerWorkCustody, InferencePort, open_inference,
};
use serde_json::{Value, json};
use std::{
fs,
net::SocketAddr,
path::PathBuf,
sync::Arc,
time::{Duration, Instant},
};
use tokio::sync::{Mutex, Semaphore, mpsc};
use tracing_subscriber::EnvFilter;
const CULTNET_SNAPSHOT_BODY_LIMIT: usize = 16 * 1024;
const PROXY_HEADERS: [&str; 5] = [
"x-real-ip",
"x-forwarded-for",
"x-forwarded-host",
"x-forwarded-proto",
"forwarded",
];
const CONNECTOR_ADDRESS_ENVIRONMENT: &str = "GHOSTLIGHT_CONNECTOR_ADDR";
/// The credential path Idunn hands the workload: the operator binding's
/// `[workload.secret_files]` entry of this name becomes a systemd credential
/// and this variable holds the path of the loaded file, never its bytes.
const CONNECTOR_KEY_FILE_ENVIRONMENT: &str = "GHOSTLIGHT_CONNECTOR_KEY_FILE";
const CONNECTOR_CALLER: &str = "ghostlight";
#[derive(Clone)]
pub(crate) struct RuntimeHealthOwner {
publisher: Arc<Mutex<RuntimePresencePublisher>>,
write_lease: Arc<ProcessWriteLeaseGuard>,
}
#[derive(Clone)]
pub(crate) struct AppState {
pub(crate) catalog: Arc<Mutex<Catalog>>,
pub(crate) timelines: Arc<Timelines>,
pub(crate) vaults: Arc<dyn Vaults>,
pub(crate) scale: Arc<Scale>,
pub(crate) sessions: Arc<Mutex<AppSessionOwner>>,
pub(crate) heimdall: Arc<dyn HeimdallPort>,
pub(crate) auth: Arc<AuthGuard>,
pub(crate) runtime_id: String,
pub(crate) runtime_health: Option<RuntimeHealthOwner>,
pub(crate) fatal: mpsc::UnboundedSender<String>,
}
struct ProductionAdmission {
health: RuntimePresencePublisher,
write_lease: ProcessWriteLeaseGuard,
}
/// The connector binding the Dungeon opens its one inference port with. Only
/// the path of the key's credential file is read here; the one connector port
/// opens the file.
fn connector_binding() -> anyhow::Result<ConnectorBinding> {
let endpoint = std::env::var(CONNECTOR_ADDRESS_ENVIRONMENT)
.with_context(|| format!("{CONNECTOR_ADDRESS_ENVIRONMENT} is required"))?
.parse()
.with_context(|| format!("{CONNECTOR_ADDRESS_ENVIRONMENT} is not a socket address"))?;
let key_path = std::env::var_os(CONNECTOR_KEY_FILE_ENVIRONMENT)
.map(PathBuf::from)
.with_context(|| format!("{CONNECTOR_KEY_FILE_ENVIRONMENT} is required"))?;
ensure!(
key_path.is_absolute(),
"{CONNECTOR_KEY_FILE_ENVIRONMENT} is not an absolute path"
);
Ok(ConnectorBinding {
endpoint,
key_path,
caller_runtime_id: CONNECTOR_CALLER.into(),
})
}
/// The model each lane runs on, from env over the defaults the rulings set
/// (dungeon-models-dm-opus): Opus for the play table (the DM) and the narrator (the projector),
/// Sonnet for the NPC Personas and the elaborator (which also
/// seeds), Haiku for the interpreter and the operational agent.
fn lane_models() -> (ControllerModels, String) {
lane_models_from(|name| std::env::var(name).ok())
}
fn lane_models_from(read: impl Fn(&str) -> Option<String>) -> (ControllerModels, String) {
let lane = |name: &str, default: &str| read(name).unwrap_or_else(|| default.into());
(
ControllerModels {
projector: lane("GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL", "claude-opus-5-5"),
persona: lane("GHOSTLIGHT_CONTROLLER_PERSONA_MODEL", "claude-sonnet-5-5"),
interpreter: lane("GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL", "claude-haiku-5-5"),
operational_agent: lane("GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL", "claude-haiku-5-5"),
elaborator: lane("GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL", "claude-sonnet-5-5"),
},
lane("GHOSTLIGHT_PLAY_MODEL", "claude-opus-5-5"),
)
}
/// The one routed inference port every timeline and lane shares.
pub(crate) fn open_shared() -> anyhow::Result<Shared> {
let (models, play_model) = lane_models();
let mut all: Vec<&str> = models.each().to_vec();
all.push(&play_model);
let inference: Arc<dyn InferencePort> =
open_inference(Some(connector_binding()?), None, None, None, &all)?;
Ok(Shared {
inference,
models,
play_model,
permits: Arc::new(Semaphore::new(configured_controller_concurrency())),
})
}
/// Sized to the connector's per-caller quota. `Capacity` and `InFlight`
/// refusals are retryable faults, so a pool above that quota degrades to retry.
fn configured_controller_concurrency() -> usize {
std::env::var("GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT")
.ok()
.and_then(|value| value.trim().parse::<usize>().ok())
.filter(|value| *value >= 1)
.unwrap_or(4)
}
pub(crate) fn service_router(state: AppState) -> Router {
Router::new()
.route("/health", get(health))
.route(
"/cultnet/snapshot",
post(cultnet_snapshot).layer(DefaultBodyLimit::max(CULTNET_SNAPSHOT_BODY_LIMIT)),
)
.merge(api::router())
.merge(crate::page::router())
.with_state(state)
}
pub(crate) async fn run(state_root_binding: Option<PathBuf>) -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.init();
let runtime_root = admitted_runtime_root(state_root_binding)?;
let service_root = runtime_root.join("service");
// The bound socket is service observation, not configuration. Retain it
// unopened to application traffic while Warming waits for Idunn's lease.
let requested_address = candidate_bind()?;
let listener = tokio::net::TcpListener::bind(requested_address).await?;
let bound_address = listener.local_addr()?;
let (fatal, mut fatal_events) = mpsc::unbounded_channel();
let production_admission = initialize_production_admission(bound_address).await?;
let dependency_bindings = production_admission
.as_ref()
.map(|admission| admission.health.dependency_bindings().clone());
let runtime_id = match &production_admission {
Some(admission) => admission.health.runtime_id().to_owned(),
None => std::env::var("GHOSTLIGHT_RUNTIME_ID")
.context("GHOSTLIGHT_RUNTIME_ID is required outside managed runtime")?,
};
if runtime_id.is_empty() || runtime_id.trim() != runtime_id {
bail!("GHOSTLIGHT_RUNTIME_ID must be a canonical non-empty identity");
}
// Production may bind but not serve its candidate socket, then publish
// Warming. Catalog, session and timeline state stay unopened until Idunn
// grants the lease bound to that exact observed process.
let mut write_lease_guard = None;
let mut idunn_health = match production_admission {
Some(ProductionAdmission { health, write_lease }) => {
write_lease.require_current()?;
write_lease_guard = Some(write_lease);
Some(health)
}
None => None,
};
tokio::task::yield_now().await;
require_no_runtime_custody_failure(&mut fatal_events)?;
require_current_write_lease(write_lease_guard.as_ref())?;
if write_lease_guard.is_none() {
fs::create_dir_all(&runtime_root)?;
}
prepare_admitted_state_layout(&runtime_root)?;
require_current_write_lease(write_lease_guard.as_ref())?;
let mut catalog = Catalog::open(runtime_root.join("catalog.cc"))?;
// A seed runs only in the process that claimed it; any still Seeding was cut off.
let interrupted = catalog.fail_interrupted_seeds()?;
if interrupted > 0 {
tracing::warn!(interrupted, "seeds interrupted by the last shutdown were marked failed");
}
let shared = open_shared()?;
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 odin_endpoint = dependency_bindings
.as_ref()
.map(|bindings| bindings.odin_rudp)
.map(Ok)
.unwrap_or_else(configured_odin_endpoint)?;
// Heimdall is discovered through Odin at use and is not an Idunn
// dependency; loopback-only, non-secret-bearing, app-bound envelopes are
// enforced regardless.
let heimdall = Arc::new(HeimdallClient::from_env(&runtime_id, odin_endpoint, None)?);
require_no_runtime_custody_failure(&mut fatal_events)?;
let mut state = AppState {
catalog: Arc::new(Mutex::new(catalog)),
timelines: Arc::new(Timelines::new(runtime_root.clone(), shared, fatal.clone())),
vaults: Arc::new(crate::vaults::SnapshotVaults::new(&runtime_root)),
scale: Arc::new(Scale::from_env()),
sessions: Arc::new(Mutex::new(sessions)),
heimdall,
auth: Arc::default(),
runtime_id,
runtime_health: None,
fatal,
};
require_no_runtime_custody_failure(&mut fatal_events)?;
require_current_write_lease(write_lease_guard.as_ref())?;
canonical_readiness(&state)
.await
.context("runtime is not ready for active signed health")?;
if let Some(publisher) = idunn_health.as_mut() {
let write_lease = write_lease_guard
.as_ref()
.context("production runtime lost its process write lease")?;
// Odin refuses Active until it has correlated the lease Idunn just
// granted; each call is a fresh sequenced message.
retry_until_deadline(
|| publisher.publish_active(write_lease),
INITIAL_PRESENCE_RETRY_CADENCE,
Instant::now() + WRITE_LEASE_WAIT_TIMEOUT,
"publishing initial active runtime presence",
Instant::now,
|duration| tokio::time::sleep(duration),
)
.await?;
}
require_current_write_lease(write_lease_guard.as_ref())?;
state.runtime_health = match (idunn_health, write_lease_guard) {
(Some(publisher), Some(write_lease)) => Some(RuntimeHealthOwner {
publisher: Arc::new(Mutex::new(publisher)),
write_lease: Arc::new(write_lease),
}),
(None, None) => None,
_ => bail!("managed runtime health authority is partial"),
};
let invite_socket = crate::invite::bind(&crate::invite::socket_path(&runtime_root))?;
let app = service_router(state.clone());
tracing::info!(address = %bound_address, "Ghostlight Dungeon serving");
let server = axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
);
tokio::select! {
result = server => result.context("Ghostlight HTTP server stopped"),
result = crate::invite::serve(invite_socket, state.catalog.clone()) => {
result?;
bail!("invite socket owner stopped while the daemon was serving")
}
result = maintain_runtime_health(state.clone()) => {
result?;
bail!("runtime readiness owner stopped while the daemon was serving")
}
result = run_refresh_loop(&state.sessions, state.heimdall.as_ref()) => {
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())
)
}
}
}
async fn cultnet_snapshot(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<AppState>,
headers: HeaderMap,
body: Bytes,
) -> Response {
// Idunn's route observation reaches this daemon straight over loopback and
// carries no proxy header. nginx sets `X-Real-IP` on every request it
// forwards, so a request that carries any of these came from the public
// side and finds no route here, whatever its peer address says.
if !peer.ip().is_loopback() || PROXY_HEADERS.iter().any(|name| headers.contains_key(*name)) {
return StatusCode::NOT_FOUND.into_response();
}
if headers.get(header::CONTENT_TYPE) != Some(&HeaderValue::from_static("application/msgpack")) {
return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response();
}
let message_id = match exact_route_observation_message_id(&body) {
Ok(message_id) => message_id,
Err(_) => return StatusCode::BAD_REQUEST.into_response(),
};
let Some(owner) = state.runtime_health.clone() else {
return StatusCode::SERVICE_UNAVAILABLE.into_response();
};
// Hold the one publisher across readiness observation and signing so a
// periodic publication cannot age the checked state before this challenge
// is bound into the signed record.
let write_lease = owner.write_lease.clone();
let mut publisher = owner.publisher.clone().lock_owned().await;
let ready = canonical_readiness(&state).await.is_ok();
let response = tokio::task::spawn_blocking(move || {
let response = publisher.route_observation(&message_id, ready, &write_lease)?;
encode_cultnet_message_to_vec(&response, CultNetWireContract::CultNetSchemaV0)
})
.await;
let Ok(Ok(response)) = response else {
return StatusCode::SERVICE_UNAVAILABLE.into_response();
};
(
StatusCode::OK,
[(header::CONTENT_TYPE, "application/msgpack")],
response,
)
.into_response()
}
fn exact_route_observation_message_id(body: &[u8]) -> anyhow::Result<String> {
let request = decode_cultnet_message_from_slice(body, CultNetWireContract::CultNetSchemaV0)
.context("decoding route-observation request")?;
ensure!(
encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)? == body,
"route-observation request is not canonical MessagePack"
);
let CultNetMessage::SnapshotRequest {
message_id,
schema_ids,
record_keys,
} = request
else {
bail!("route-observation request is not a snapshot request");
};
ensure!(
!message_id.is_empty(),
"route-observation message id is empty"
);
ensure!(
matches!(
schema_ids.as_deref(),
Some([schema_id]) if schema_id == GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA
) && matches!(
record_keys.as_deref(),
Some([record_key]) if record_key == GHOSTLIGHT_TARGET
),
"route-observation request is not the exact Ghostlight presence record"
);
let detail = format!("route-observation:{message_id}");
ensure!(
detail.len() <= 512 && !detail.chars().any(char::is_control),
"route-observation message id cannot be signed canonically"
);
Ok(message_id)
}
async fn health(State(state): State<AppState>) -> 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(),
}
}
/// The custody every response rests on: the catalog and the session store.
async fn canonical_readiness(state: &AppState) -> anyhow::Result<Value> {
state
.catalog
.lock()
.await
.validate_custody()
.context("catalog is not ready")?;
state
.sessions
.lock()
.await
.validate_custody()
.context("app-session owner is not ready")?;
Ok(json!({
"schema":"ghostlight.service_health.v3",
"status":"ok",
"updatedAtUtc":Utc::now().to_rfc3339(),
"runtime":state.runtime_id,
"commit":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development"),
}))
}
async fn runtime_readiness(state: &AppState) -> anyhow::Result<Value> {
let mut health = canonical_readiness(state).await?;
let opened = state.timelines.opened().await;
let mut controller_status = "ok";
let mut play_status = "ok".to_owned();
for (id, host) in &opened {
match tokio::time::timeout(Duration::from_millis(100), host.controllers.custody_probe())
.await
{
Ok(Ok(ControllerWorkCustody::Owned { .. })) => {}
Ok(Ok(ControllerWorkCustody::Uncertain { .. })) | Ok(Err(_)) => {
controller_status = "degraded";
}
Err(_) => controller_status = "busy",
}
// A retired unreadable play row is reported, not hidden.
if let Some(sidecar) = host.play.retired_row_sidecar() {
play_status = format!("a play-turn row of {id} was retired to {}", sidecar.display());
}
}
if state.timelines.shared().permits.available_permits() == 0 && controller_status == "ok" {
controller_status = "active";
}
health["openTimelines"] = json!(opened.len());
health["controllerStatus"] = Value::String(controller_status.into());
health["playStatus"] = Value::String(play_status);
Ok(health)
}
/// Idunn publishes Expected and starts the unit before it observes the
/// running process on a later tick and publishes the activation. Until then,
/// Odin refuses every Warming presence this daemon publishes. This is the
/// bound both the initial Warming publish retries against and
/// `wait_for_write_lease`'s own timeout.
const WRITE_LEASE_WAIT_TIMEOUT: Duration = Duration::from_secs(120);
/// Matches Muninn's own Warming re-publish cadence while tolerating the same
/// activation-publication gap.
const INITIAL_PRESENCE_RETRY_CADENCE: Duration = Duration::from_secs(2);
/// Retries `attempt` at `cadence` until it returns `Ok` or `deadline` passes,
/// returning the last error once the deadline is reached. `sleep` and `now`
/// are seams so the bounded-retry policy is provable without waiting.
async fn retry_until_deadline<T, Attempt, Sleep, SleepFut>(
mut attempt: Attempt,
cadence: Duration,
deadline: Instant,
what: &str,
mut now: impl FnMut() -> Instant,
mut sleep: Sleep,
) -> anyhow::Result<T>
where
Attempt: FnMut() -> anyhow::Result<T>,
Sleep: FnMut(Duration) -> SleepFut,
SleepFut: std::future::Future<Output = ()>,
{
loop {
match attempt() {
Ok(value) => return Ok(value),
Err(error) => {
tracing::warn!(%error, "{what} failed; retrying");
if now() >= deadline {
return Err(error).context(format!("{what} timed out"));
}
sleep(cadence).await;
}
}
}
}
async fn initialize_production_admission(
bound_endpoint: SocketAddr,
) -> anyhow::Result<Option<ProductionAdmission>> {
let Some(mut publisher) = RuntimePresencePublisher::from_environment(bound_endpoint)? else {
return Ok(None);
};
// Each `publish_warming()` mints a fresh sequence and timestamp, so a
// retried publish is a new message Odin evaluates, never a duplicate.
let warming = retry_until_deadline(
|| publisher.publish_warming(),
INITIAL_PRESENCE_RETRY_CADENCE,
Instant::now() + WRITE_LEASE_WAIT_TIMEOUT,
"publishing initial Warming runtime presence",
Instant::now,
|duration| tokio::time::sleep(duration),
)
.await?;
let write_lease = publisher
.wait_for_write_lease(&warming, WRITE_LEASE_WAIT_TIMEOUT)
.await
.with_context(|| {
format!(
"waiting for process lease bound to Warming {}",
warming.canonical_sha256()
)
})?;
Ok(Some(ProductionAdmission {
health: publisher,
write_lease,
}))
}
async fn maintain_runtime_health(state: AppState) -> anyhow::Result<()> {
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")?;
let Some(owner) = state.runtime_health.clone() else {
continue;
};
owner
.write_lease
.require_current()
.context("runtime process write lease is not current")?;
let mut publisher = owner.publisher.clone().lock_owned().await;
let published = tokio::task::spawn_blocking(move || {
publisher.republish_active()?;
Ok::<(), anyhow::Error>(())
})
.await;
let Ok(result) = published else {
tracing::warn!("runtime-presence worker panicked; publication will retry");
continue;
};
if let Err(error) = result {
tracing::warn!(%error, "signed runtime-presence publication failed");
}
}
}
fn candidate_bind() -> anyhow::Result<SocketAddr> {
match std::env::var(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT) {
Ok(value) => value
.parse()
.context("Idunn candidate bind is not a socket address"),
Err(_) => {
#[cfg(target_os = "linux")]
bail!("{IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT} is mandatory on Linux");
#[cfg(not(target_os = "linux"))]
return Ok("127.0.0.1:8831".parse()?);
}
}
}
fn configured_odin_endpoint() -> anyhow::Result<SocketAddr> {
std::env::var("GHOSTLIGHT_ODIN_RUDP")
.context("GHOSTLIGHT_ODIN_RUDP is required")?
.parse()
.context("GHOSTLIGHT_ODIN_RUDP is not a socket address")
}
fn require_current_write_lease(lease: Option<&ProcessWriteLeaseGuard>) -> anyhow::Result<()> {
match lease {
Some(lease) => lease.require_current(),
None => Ok(()),
}
}
fn require_no_runtime_custody_failure(
failures: &mut mpsc::UnboundedReceiver<String>,
) -> 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")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Live: Begin on an imported snapshot through the real connector.
/// `GHOSTLIGHT_LIVE_STATE_ROOT` holds `snapshots/` from `import-vault`,
/// `GHOSTLIGHT_LIVE_PROFILE` names the profile, and the connector address
/// and key credential are the daemon's own (`GHOSTLIGHT_CONNECTOR_ADDR`,
/// `$CREDENTIALS_DIRECTORY/connector-key`). Spends real credit.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "live: spends connector credit; run on Yggdrasil under a unit that loads the connector key"]
async fn live_seeded_begin_reaches_ready_with_a_place_and_people() {
use crate::{
begin::{BeginRequest, Scale, begin, tests::principal}, catalog::SeedStatus,
catalog::Catalog,
state_layout::prepare_admitted_state_layout,
timelines::{Shared, Timelines},
};
let root = PathBuf::from(std::env::var("GHOSTLIGHT_LIVE_STATE_ROOT").unwrap());
let profile = std::env::var("GHOSTLIGHT_LIVE_PROFILE").unwrap();
prepare_admitted_state_layout(&root).unwrap();
let shared = open_shared().unwrap();
let counting = crate::test_support::CountingPort::new(shared.inference.clone());
let shared = Shared { inference: counting.clone(), ..shared };
let (fatal, _fatal_events) = mpsc::unbounded_channel();
let timelines = Timelines::new(root.clone(), shared, fatal);
let catalog = Arc::new(Mutex::new(Catalog::open(root.join("catalog.cc")).unwrap()));
let vaults = crate::vaults::SnapshotVaults::new(&root);
let scale = Arc::new(Scale::from_env());
let started = Instant::now();
let begun = begin(
&catalog,
&timelines,
&vaults,
&scale,
&principal("live"),
BeginRequest {
key: uuid::Uuid::new_v4().to_string(),
title: "Ghostlight Live".into(),
name: "Deru".into(),
brief: None,
vault: Some(profile.clone()),
era: None,
lenses: None,
},
)
.await
.unwrap();
println!("LIVE begin returned after {:?}: {}", started.elapsed(), begun.reached);
let ready = loop {
let status = catalog.lock().await.seed_status(&begun.timeline).cloned();
match status {
None => break started.elapsed(),
Some(SeedStatus::Failed(reason)) => panic!("the seed failed: {reason}"),
Some(SeedStatus::Seeding) if started.elapsed() > Duration::from_secs(1800) => {
panic!("still seeding after 30 minutes")
}
Some(SeedStatus::Seeding) => tokio::time::sleep(Duration::from_secs(2)).await,
}
};
let used = counting.totals();
println!("LIVE ready after {ready:?}; calls={} prompt_tokens={} completion_tokens={}", used.calls, used.prompt, used.completion);
let host = timelines.host(&begun.timeline).await.unwrap();
// A position is not public on the snapshot; the Debug text names it by
// the same entity id a place carries.
let standing = |world: &ghostlight::WorldSnapshot, place: &ghostlight::PlaceSnapshot| -> Vec<String> {
let at = format!("position: Some({:?})", place.id);
world.subjects.iter().filter(|subject| format!("{subject:?}").contains(&at)).map(|subject| subject.label.clone()).collect()
};
let report = |label: &str, world: &ghostlight::WorldSnapshot| {
println!("LIVE {label}: phase={:?}", world.phase);
for place in &world.places {
println!("LIVE place {} <- {:?}", place.label, standing(world, place));
}
for subject in &world.subjects {
println!("LIVE subject {:?} {} qualified={}", subject.kind, subject.label, subject.qualified);
}
for row in &world.scale_deficit {
println!("LIVE row {:?} target={} qualified={} deficit={}", row.kind, row.target, row.qualified, row.deficit);
}
};
let world = host.world.snapshot().await.unwrap();
report("after seed", &world);
assert_eq!(world.phase, ghostlight::WorldPhase::Active);
let authored = world.places.iter().filter(|place| place.label != "The Commons" && place.label != "Ghostlight Live").count();
assert!(authored >= 2, "the seed authored places beyond the root and The Commons, got {authored}");
let person = world.scale_deficit.iter().find(|row| row.kind == ghostlight::SubjectKind::Person).unwrap();
assert!(person.qualified >= 2, "at least two qualifying people");
// The first run-ahead sweep, then the world as play would meet it.
tokio::time::sleep(Duration::from_secs(1)).await;
let sweep_started = Instant::now();
while host.sweeping.try_lock().is_err() && sweep_started.elapsed() < Duration::from_secs(1800) {
tokio::time::sleep(Duration::from_secs(2)).await;
}
let used = counting.totals();
println!("LIVE after run-ahead at {:?}: calls={} prompt_tokens={} completion_tokens={}", started.elapsed(), used.calls, used.prompt, used.completion);
report("after run-ahead", &host.world.snapshot().await.unwrap());
}
#[test]
fn lanes_default_to_the_ruled_tiers_and_each_reads_its_own_override() {
let (models, play) = lane_models_from(|_| None);
assert_eq!(models.projector, "claude-opus-5-5", "the narrator");
assert_eq!(models.persona, "claude-sonnet-5-5");
assert_eq!(models.elaborator, "claude-sonnet-5-5");
assert_eq!(play, "claude-opus-5-5", "the DM");
assert_eq!(models.interpreter, "claude-haiku-5-5");
assert_eq!(models.operational_agent, "claude-haiku-5-5");
for (name, lane) in [
("GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL", 0),
("GHOSTLIGHT_CONTROLLER_PERSONA_MODEL", 1),
("GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL", 2),
("GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL", 3),
("GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL", 4),
("GHOSTLIGHT_PLAY_MODEL", 5),
] {
let (models, play) = lane_models_from(|asked| (asked == name).then(|| "override".to_owned()));
let mut all = models.each().to_vec();
all.push(&play);
let overridden: Vec<usize> = all
.iter()
.enumerate()
.filter(|(_, model)| **model == "override")
.map(|(index, _)| index)
.collect();
assert_eq!(overridden, vec![lane], "{name} moves exactly its own lane");
}
}
struct FakeClock {
now: std::cell::Cell<Instant>,
}
impl FakeClock {
fn new() -> Self {
Self {
now: std::cell::Cell::new(Instant::now()),
}
}
fn now(&self) -> Instant {
self.now.get()
}
fn advance(&self, by: Duration) {
self.now.set(self.now.get() + by);
}
}
#[tokio::test]
async fn retry_until_deadline_returns_the_first_accepted_value() {
let clock = FakeClock::new();
let deadline = clock.now() + Duration::from_secs(120);
let mut calls = 0;
let result = retry_until_deadline(
|| {
calls += 1;
if calls < 3 {
Err(anyhow::anyhow!("refused (attempt {calls})"))
} else {
Ok(format!("accepted on attempt {calls}"))
}
},
Duration::from_secs(2),
deadline,
"test publish",
|| clock.now(),
|cadence| {
clock.advance(cadence);
std::future::ready(())
},
)
.await;
assert_eq!(result.unwrap(), "accepted on attempt 3");
assert_eq!(calls, 3);
}
#[tokio::test]
async fn retry_until_deadline_fails_with_the_last_error_after_the_window() {
let clock = FakeClock::new();
let deadline = clock.now() + Duration::from_secs(10);
let mut calls = 0;
let result: anyhow::Result<()> = retry_until_deadline(
|| {
calls += 1;
Err(anyhow::anyhow!("refused (attempt {calls})"))
},
Duration::from_secs(2),
deadline,
"test publish",
|| clock.now(),
|cadence| {
clock.advance(cadence);
std::future::ready(())
},
)
.await;
let error = result.unwrap_err();
assert!(format!("{error:#}").contains("test publish timed out"));
assert!(format!("{error:#}").contains("refused (attempt"));
assert_eq!(calls, 6);
}
/// The connector key is a credential path, never a value: the binding
/// carries the path Idunn's credential delivered and the caller id, and
/// nothing else of it.
#[test]
fn the_connector_key_is_bound_by_credential_path_only() {
// SAFETY: the test sets and clears process env it alone reads.
unsafe {
std::env::set_var(CONNECTOR_ADDRESS_ENVIRONMENT, "127.0.0.1:7001");
std::env::set_var(
CONNECTOR_KEY_FILE_ENVIRONMENT,
"/run/credentials/idunn-ghostlight-x.service/GHOSTLIGHT_CONNECTOR_KEY_FILE",
);
}
let binding = connector_binding().unwrap();
assert_eq!(binding.caller_runtime_id, "ghostlight");
assert_eq!(
binding.key_path,
PathBuf::from("/run/credentials/idunn-ghostlight-x.service/GHOSTLIGHT_CONNECTOR_KEY_FILE")
);
unsafe {
std::env::set_var(CONNECTOR_KEY_FILE_ENVIRONMENT, "relative/key");
}
assert!(connector_binding().is_err(), "a relative path is no credential");
unsafe {
std::env::remove_var(CONNECTOR_KEY_FILE_ENVIRONMENT);
}
assert!(connector_binding().is_err(), "no credential path, no binding");
unsafe {
std::env::remove_var(CONNECTOR_ADDRESS_ENVIRONMENT);
}
}
}

View file

@ -1,619 +0,0 @@
//! The app-session refresh loop: renews Heimdall sessions before they lapse
//! and revokes any whose custody changed.
use crate::{
app_session::{AppSessionOwner, RefreshRefusal},
heimdall::{self, HeimdallDenied, SessionRefresher, VerificationUnavailable},
};
use anyhow::Context;
use chrono::Utc;
use std::{collections::HashMap, time::Duration};
use tokio::sync::Mutex;
const SESSION_REFRESH_PERIOD: Duration = Duration::from_secs(60);
/// Runs `refresh_due_sessions` once per `SESSION_REFRESH_PERIOD` for as long
/// as the daemon serves. The receipts it holds are Heimdall refreshes already
/// spent upstream whose verification could not yet be judged.
pub(crate) async fn run_refresh_loop(
sessions: &Mutex<AppSessionOwner>,
heimdall: &(impl SessionRefresher + ?Sized),
) -> anyhow::Result<()> {
let mut interval = tokio::time::interval(SESSION_REFRESH_PERIOD);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut unverified = HashMap::new();
loop {
interval.tick().await;
refresh_due_sessions(sessions, heimdall, &mut unverified).await?;
}
}
/// One pass of the refresh loop over every session due for refresh.
/// `unverified` holds, per session, a receipt Heimdall issued for a refresh
/// that is already spent upstream but whose signing keys could not be
/// fetched: the next pass verifies it instead of refreshing again.
async fn refresh_due_sessions(
sessions: &Mutex<AppSessionOwner>,
heimdall: &(impl SessionRefresher + ?Sized),
unverified: &mut HashMap<String, heimdall::AuthCompletionReceipt>,
) -> anyhow::Result<()> {
let candidates = sessions
.lock()
.await
.sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2))
.context("app-session refresh scan lost custody")?;
unverified.retain(|cookie_hash, _| {
candidates
.iter()
.any(|candidate| &candidate.cookie_hash == cookie_hash)
});
for candidate in candidates {
let completion = match unverified.remove(&candidate.cookie_hash) {
Some(completion) => completion,
None => {
let idempotency =
crate::app_session::refresh_idempotency_key(&candidate.refresh_claim);
match heimdall.refresh(&candidate.refresh_claim, &idempotency).await {
Ok(value) => value,
Err(error) if error.downcast_ref::<HeimdallDenied>().is_some() => {
// Heimdall refused this refresh claim: it can never succeed.
tracing::warn!(%error, "Heimdall denied the refresh; revoking the local session");
let mut sessions = sessions.lock().await;
if let Err(revoke_error) =
sessions.revoke_cookie_hash(&candidate.cookie_hash)
{
return Err(revoke_error)
.context("denied Heimdall refresh could not revoke local custody");
}
continue;
}
Err(error) => {
tracing::warn!(%error, "Heimdall refresh transport unavailable");
continue;
}
}
}
};
let verified = match heimdall.verify_refresh(completion.clone()).await {
Ok(value) => value,
Err(error) if error.downcast_ref::<VerificationUnavailable>().is_some() => {
// The claim is spent upstream and the receipt may be genuine:
// keep it and verify again on the next pass.
tracing::warn!(%error, "Heimdall refresh receipt could not be verified yet");
unverified.insert(candidate.cookie_hash.clone(), completion);
continue;
}
Err(error) => {
tracing::warn!(%error, "Heimdall refresh receipt was invalid");
let mut sessions = 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 = 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 = sessions.lock().await;
if let Err(error) =
sessions.apply_refresh(&candidate.cookie_hash, candidate.access_revision, verified)
{
if !sessions.is_healthy() {
return Err(error).context("app-session refresh commit lost custody");
}
tracing::warn!(%error, "local app session refused Heimdall refresh");
// The refresh claim is spent upstream, so a receipt that went
// backwards leaves nothing to retry. A session that merely moved
// is newer state: the next scan decides.
if error.downcast_ref::<RefreshRefusal>()
== Some(&RefreshRefusal::RevisionWentBackwards)
&& let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash)
{
return Err(revoke_error)
.context("backwards Heimdall refresh could not revoke local session");
}
}
}
Ok(())
}
/// Idunn publishes Expected and starts the unit before it observes the
/// running process on a later tick and publishes the activation
/// (Idunn/src/control_plane.rs). Until that activation exists, Odin refuses
/// queue and records the claim and idempotency key it was sent.
#[cfg(test)]
mod refresh_loop_tests {
use super::*;
use crate::heimdall::{AuthCompletionReceipt, HeimdallClient, VerifiedSessionRefresh};
use anyhow::bail;
use std::{collections::VecDeque, sync::Mutex as StdMutex};
enum Reply {
Deny,
Timeout,
Receipt { revision: u64, claim: &'static str },
/// A receipt for the same claim but another Heimdall session.
OtherSession,
/// A receipt for the same claim but another account.
OtherAccount,
}
/// What `verify_refresh` answers; an empty queue accepts the receipt.
enum Verdict {
/// The signing keys could not be fetched.
Unavailable,
/// The receipt positively fails verification.
Invalid,
}
#[derive(Default)]
struct ScriptedHeimdall {
replies: StdMutex<VecDeque<Reply>>,
verdicts: StdMutex<VecDeque<Verdict>>,
verifications: StdMutex<usize>,
/// While answering a refresh, apply a newer revision to this store,
/// as a concurrent refresh of the same session would.
moving: Option<std::sync::Arc<Mutex<AppSessionOwner>>>,
pending: StdMutex<Option<VerifiedSessionRefresh>>,
calls: StdMutex<Vec<(String, String)>>,
/// Verify receipts with this real client, against the access token
/// each receipt carries, instead of from the verdict queue.
real: Option<(HeimdallClient, String)>,
}
impl ScriptedHeimdall {
fn answering(replies: Vec<Reply>) -> Self {
Self {
replies: StdMutex::new(replies.into()),
..Self::default()
}
}
fn verifying(mut self, verdicts: Vec<Verdict>) -> Self {
self.verdicts = StdMutex::new(verdicts.into());
self
}
fn verifying_for_real(mut self, client: HeimdallClient, token: String) -> Self {
self.real = Some((client, token));
self
}
fn verifications(&self) -> usize {
*self.verifications.lock().unwrap()
}
fn calls(&self) -> Vec<(String, String)> {
self.calls.lock().unwrap().clone()
}
}
#[async_trait::async_trait]
impl SessionRefresher for ScriptedHeimdall {
async fn refresh(
&self,
refresh_token: &str,
idempotency_key: &str,
) -> anyhow::Result<AuthCompletionReceipt> {
self.calls
.lock()
.unwrap()
.push((refresh_token.into(), idempotency_key.into()));
if let Some(sessions) = &self.moving {
let mut sessions = sessions.lock().await;
let candidate = sessions
.sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2))
.unwrap()
.remove(0);
sessions
.apply_refresh(
&candidate.cookie_hash,
candidate.access_revision,
VerifiedSessionRefresh::fixture(
"operator-account",
"heimdall-session",
candidate.access_revision + 1,
Utc::now() + chrono::Duration::seconds(90),
Utc::now() + chrono::Duration::days(1),
"claim-moved",
),
)
.unwrap();
}
match self.replies.lock().unwrap().pop_front().expect("scripted reply") {
Reply::Deny => Err(HeimdallDenied {
diagnostics: "Idempotency key was reused".into(),
}
.into()),
Reply::Timeout => bail!("Heimdall private command timed out"),
reply @ (Reply::Receipt { .. } | Reply::OtherSession | Reply::OtherAccount) => {
let (account, session, revision, claim) = match reply {
Reply::OtherSession => ("operator-account", "other-session", 1, "claim-1"),
Reply::OtherAccount => ("other-account", "heimdall-session", 1, "claim-1"),
Reply::Receipt { revision, claim } => {
("operator-account", "heimdall-session", revision, claim)
}
_ => unreachable!("matched above"),
};
*self.pending.lock().unwrap() = Some(VerifiedSessionRefresh::fixture(
account,
session,
revision,
Utc::now() + chrono::Duration::seconds(90),
Utc::now() + chrono::Duration::days(1),
claim,
));
Ok(AuthCompletionReceipt {
status: "authenticated".into(),
handle: None,
error: None,
account: None,
session: None,
access_token: self.real.as_ref().map(|(_, token)| token.clone()),
refresh_token: None,
refresh: None,
shared_capabilities: Vec::new(),
})
}
}
}
async fn verify_refresh(
&self,
completion: AuthCompletionReceipt,
) -> anyhow::Result<VerifiedSessionRefresh> {
*self.verifications.lock().unwrap() += 1;
if let Some((client, _)) = &self.real {
return client.verify_refresh(completion).await;
}
match self.verdicts.lock().unwrap().pop_front() {
Some(Verdict::Unavailable) => {
Err(VerificationUnavailable::new("timed out").into())
}
Some(Verdict::Invalid) => bail!("Heimdall access token signature is invalid"),
None => Ok(self.pending.lock().unwrap().take().expect("scripted receipt")),
}
}
}
/// A store holding one live session at `revision` whose access expires in
/// a minute, so every pass finds it due.
fn due_session(
revision: u64,
) -> (tempfile::TempDir, std::sync::Arc<Mutex<AppSessionOwner>>, String) {
let directory = tempfile::tempdir().unwrap();
let key = directory.path().join("session.key");
std::fs::write(&key, [23_u8; 32]).unwrap();
let mut owner = AppSessionOwner::open(directory.path().join("sessions.cc"), &key).unwrap();
let cookie = owner
.create_session(heimdall::VerifiedSessionAdmission::fixture(
"operator-account",
"heimdall-session",
revision,
Utc::now() + chrono::Duration::seconds(60),
Utc::now() + chrono::Duration::days(1),
"claim-0",
))
.unwrap();
(directory, std::sync::Arc::new(Mutex::new(owner)), cookie)
}
/// One refresh pass with no receipt carried over from an earlier one.
async fn pass(sessions: &Mutex<AppSessionOwner>, heimdall: &ScriptedHeimdall) {
refresh_due_sessions(sessions, heimdall, &mut HashMap::new())
.await
.unwrap();
}
async fn is_live(sessions: &Mutex<AppSessionOwner>, cookie: &str) -> bool {
sessions
.lock()
.await
.account_for_cookie(cookie, Utc::now())
.unwrap()
.is_some()
}
#[derive(Clone, Default)]
struct Captured(std::sync::Arc<StdMutex<Vec<u8>>>);
impl std::io::Write for Captured {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Captured {
type Writer = Captured;
fn make_writer(&'a self) -> Captured {
self.clone()
}
}
#[tokio::test]
async fn a_real_refresh_at_an_equal_revision_is_applied_and_the_session_stays_live() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 1, claim: "claim-1" },
Reply::Timeout,
]);
pass(&sessions, &heimdall).await;
assert!(is_live(&sessions, &cookie).await);
// The wrapped claim is the receipt's: the next refresh spends it.
pass(&sessions, &heimdall).await;
assert_eq!(heimdall.calls()[1].0, "claim-1");
assert!(is_live(&sessions, &cookie).await);
}
#[tokio::test]
async fn a_retry_of_the_same_refresh_sends_the_same_key() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![Reply::Timeout, Reply::Timeout]);
pass(&sessions, &heimdall).await;
pass(&sessions, &heimdall).await;
let calls = heimdall.calls();
assert_eq!(calls.len(), 2, "a transport failure leaves the session offered");
assert_eq!(calls[0], calls[1]);
assert!(is_live(&sessions, &cookie).await);
}
#[tokio::test]
async fn the_refresh_after_a_successful_one_sends_a_new_key() {
let (_directory, sessions, _cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 1, claim: "claim-1" },
Reply::Timeout,
]);
pass(&sessions, &heimdall).await;
pass(&sessions, &heimdall).await;
let calls = heimdall.calls();
assert_ne!(calls[0].1, calls[1].1);
assert!(calls.iter().all(|(claim, key)| !key.contains(claim)));
}
#[tokio::test]
async fn a_receipt_with_a_lower_revision_is_refused_and_the_session_revoked() {
let (_directory, sessions, cookie) = due_session(2);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 1, claim: "claim-1" },
Reply::Timeout,
]);
pass(&sessions, &heimdall).await;
assert!(!is_live(&sessions, &cookie).await);
pass(&sessions, &heimdall).await;
assert_eq!(heimdall.calls().len(), 1, "a revoked session is not offered again");
}
#[tokio::test]
async fn a_receipt_for_another_session_or_account_revokes_the_local_session() {
for reply in [Reply::OtherSession, Reply::OtherAccount] {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![reply]);
pass(&sessions, &heimdall).await;
assert!(!is_live(&sessions, &cookie).await);
}
}
#[tokio::test]
async fn a_heimdall_denial_revokes_the_session_and_it_is_not_offered_again() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![Reply::Deny, Reply::Timeout]);
pass(&sessions, &heimdall).await;
assert!(!is_live(&sessions, &cookie).await);
pass(&sessions, &heimdall).await;
assert_eq!(heimdall.calls().len(), 1);
}
#[tokio::test]
async fn a_local_refusal_logs_the_clause_that_fired() {
let (_directory, sessions, _cookie) = due_session(2);
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
revision: 1,
claim: "claim-1",
}]);
let captured = Captured::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(captured.clone())
.with_ansi(false)
.finish();
let _guard = tracing::subscriber::set_default(subscriber);
pass(&sessions, &heimdall).await;
let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
assert!(
logged.contains("refresh receipt revision went backwards"),
"{logged}"
);
}
#[tokio::test]
async fn a_receipt_whose_keys_were_unavailable_is_kept_and_applied_on_the_next_pass() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 1, claim: "claim-1" },
Reply::Timeout,
])
.verifying(vec![Verdict::Unavailable]);
let mut unverified = HashMap::new();
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert!(is_live(&sessions, &cookie).await, "unavailable keys do not revoke");
assert_eq!(unverified.len(), 1);
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert_eq!(heimdall.calls().len(), 1, "the spent claim is not sent again");
assert_eq!(heimdall.verifications(), 2);
assert!(unverified.is_empty(), "an applied receipt is not kept");
assert!(is_live(&sessions, &cookie).await);
// The applied receipt's claim is the one the next refresh spends.
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert_eq!(heimdall.calls()[1].0, "claim-1");
assert_eq!(heimdall.verifications(), 2, "the receipt was applied once");
}
#[tokio::test]
async fn a_receipt_that_positively_fails_verification_revokes_and_is_not_kept() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 1, claim: "claim-1" },
Reply::Timeout,
])
.verifying(vec![Verdict::Invalid]);
let mut unverified = HashMap::new();
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert!(!is_live(&sessions, &cookie).await);
assert!(unverified.is_empty());
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert_eq!(heimdall.calls().len(), 1);
assert_eq!(heimdall.verifications(), 1);
}
#[tokio::test]
async fn a_kept_receipt_for_a_session_that_is_gone_is_dropped() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
revision: 1,
claim: "claim-1",
}])
.verifying(vec![Verdict::Unavailable]);
let mut unverified = HashMap::new();
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert_eq!(unverified.len(), 1);
let cookie_hash = unverified.keys().next().unwrap().clone();
sessions.lock().await.revoke_cookie_hash(&cookie_hash).unwrap();
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert!(unverified.is_empty());
assert!(!is_live(&sessions, &cookie).await);
assert_eq!(heimdall.verifications(), 1);
}
#[tokio::test]
async fn a_session_that_moved_while_refreshing_is_not_revoked() {
let (_directory, sessions, cookie) = due_session(1);
let mut heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
revision: 1,
claim: "claim-1",
}]);
heimdall.moving = Some(sessions.clone());
pass(&sessions, &heimdall).await;
assert!(is_live(&sessions, &cookie).await);
// The newer state wins: the next refresh spends its claim, not the
// stale receipt's.
heimdall.moving = None;
heimdall.replies.lock().unwrap().push_back(Reply::Timeout);
pass(&sessions, &heimdall).await;
assert_eq!(heimdall.calls()[1].0, "claim-moved");
}
#[tokio::test]
async fn a_receipt_with_a_higher_revision_is_applied() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 2, claim: "claim-1" },
Reply::Receipt { revision: 1, claim: "claim-2" },
]);
pass(&sessions, &heimdall).await;
assert!(is_live(&sessions, &cookie).await);
// The session now sits at revision 2, so a revision-1 receipt is
// backwards.
pass(&sessions, &heimdall).await;
assert_eq!(heimdall.calls()[1].0, "claim-1");
assert!(!is_live(&sessions, &cookie).await);
}
/// Lets the loop under test run everything that is ready, without moving
/// the paused clock.
async fn settle() {
for _ in 0..16 {
tokio::task::yield_now().await;
}
}
#[tokio::test(start_paused = true)]
async fn the_refresh_loop_runs_a_pass_every_sixty_seconds_and_keeps_going() {
let (_directory, sessions, _cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering((0..64).map(|_| Reply::Timeout).collect());
let observed = async {
settle().await;
assert_eq!(heimdall.calls().len(), 1, "the first pass runs at once");
tokio::time::advance(Duration::from_millis(59_999)).await;
settle().await;
assert_eq!(heimdall.calls().len(), 1, "no pass before sixty seconds");
tokio::time::advance(Duration::from_millis(1)).await;
settle().await;
assert_eq!(heimdall.calls().len(), 2, "the second pass at sixty seconds");
for passes in 3..=12 {
tokio::time::advance(Duration::from_secs(60)).await;
settle().await;
assert_eq!(heimdall.calls().len(), passes);
}
};
tokio::select! {
ran = run_refresh_loop(&sessions, &heimdall) => panic!("the loop returned: {ran:?}"),
() = observed => {}
}
}
/// A refresh receipt verified by the real client against `issuer_url`,
/// whose key-set fetch fails. Returns whether the session stayed live,
/// how many receipts were kept, and the log the pass wrote.
async fn pass_through_real_verification(issuer_url: &str) -> (bool, usize, String) {
let (_directory, sessions, cookie) = due_session(1);
let client = HeimdallClient::fixture().with_issuer(issuer_url);
let token = heimdall::test_issuer::signed_token(issuer_url);
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
revision: 1,
claim: "claim-1",
}])
.verifying_for_real(client, token);
let captured = Captured::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(captured.clone())
.with_ansi(false)
.finish();
let _guard = tracing::subscriber::set_default(subscriber);
let mut unverified = HashMap::new();
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
(is_live(&sessions, &cookie).await, unverified.len(), logged)
}
#[tokio::test]
async fn a_key_fetch_failure_in_the_real_verification_keeps_the_session_and_the_receipt() {
let failing = heimdall::test_issuer::Issuer::start(heimdall::test_issuer::Answer::ServerError)
.await;
for issuer_url in [heimdall::test_issuer::Issuer::closed_url(), failing.url.clone()] {
let (live, kept, logged) = pass_through_real_verification(&issuer_url).await;
assert!(live, "{issuer_url}: a key-fetch failure signed the session out");
assert_eq!(kept, 1, "{issuer_url}: the spent receipt was not kept");
assert!(logged.contains("could not be verified yet"), "{logged}");
}
}
#[tokio::test]
async fn the_unverified_warning_names_the_error_class_and_no_url() {
let canary = format!("{}/canary-q7x1", heimdall::test_issuer::Issuer::closed_url());
let (_, _, logged) = pass_through_real_verification(&canary).await;
assert!(logged.contains("could not connect"), "{logged}");
for leaked in [canary.as_str(), "canary-q7x1", "127.0.0.1", "jwks.json"] {
assert!(!logged.contains(leaked), "{leaked} leaked into the log: {logged}");
}
}
}

View file

@ -1,204 +0,0 @@
//! The admitted state layout: every declared state path must be a direct,
//! single-linked regular file or directory before anything is written to it.
use anyhow::{Context, bail, ensure};
use std::{
fs,
path::{Path, PathBuf},
};
/// The stores one timeline owns, each proved direct before it is opened.
pub(crate) const TIMELINE_STORES: [&str; 3] = ["world.cc", "controller-work.cc", "play-turn-v1.cc"];
fn default_runtime_root() -> PathBuf {
#[cfg(windows)]
{
PathBuf::from(r"F:\GameCult\GhostlightDungeon")
}
#[cfg(not(windows))]
{
PathBuf::from("/var/lib/gamecult/ghostlight-dungeon")
}
}
pub(crate) fn admitted_runtime_root(binding: Option<PathBuf>) -> anyhow::Result<PathBuf> {
let Some(binding) = binding else {
#[cfg(target_os = "linux")]
bail!("--state-root is mandatory for the managed Linux runtime");
#[cfg(not(target_os = "linux"))]
return Ok(default_runtime_root());
};
ensure!(binding.is_absolute(), "state-root binding is not absolute");
let metadata = fs::symlink_metadata(&binding)
.with_context(|| format!("inspecting state-root binding {}", binding.display()))?;
ensure!(
metadata.is_dir() && !metadata.file_type().is_symlink(),
"state-root binding is not a direct directory"
);
let canonical = fs::canonicalize(&binding)
.with_context(|| format!("canonicalizing state-root binding {}", binding.display()))?;
ensure!(
canonical == binding,
"state-root binding is indirect or non-canonical"
);
Ok(binding)
}
fn ensure_direct_directory(path: &Path, label: &str) -> anyhow::Result<()> {
match fs::symlink_metadata(path) {
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
fs::create_dir(path)
.with_context(|| format!("creating direct {label} {}", path.display()))?;
}
Err(error) => return Err(error).with_context(|| format!("inspecting {label}")),
}
let metadata = fs::symlink_metadata(path)
.with_context(|| format!("inspecting {label} {}", path.display()))?;
ensure!(
metadata.is_dir() && !metadata.file_type().is_symlink(),
"{label} is indirect or not a directory"
);
Ok(())
}
pub(crate) fn prepare_admitted_state_layout(runtime_root: &Path) -> anyhow::Result<()> {
let rebound = admitted_runtime_root(Some(runtime_root.to_owned()))?;
ensure!(
rebound == runtime_root,
"state-root binding changed after process-write-lease admission"
);
let service_root = runtime_root.join("service");
ensure_direct_directory(&service_root, "service state directory")?;
ensure_direct_directory(&runtime_root.join("timelines"), "timelines directory")?;
ensure_direct_directory(
&runtime_root.join(crate::vaults::SNAPSHOT_DIRECTORY),
"vault snapshot directory",
)?;
for path in [
runtime_root.join("catalog.cc"),
service_root.join("app-sessions-v2.cc"),
] {
require_direct_state_file_or_absent(&path)?;
require_direct_state_file_or_absent(&sibling_state_lock_path(&path))?;
}
Ok(())
}
/// Proves a timeline's stores direct before it is opened and returns its
/// directory, created if absent.
pub(crate) fn prepare_timeline_directory(
runtime_root: &Path,
directory_name: &str,
) -> anyhow::Result<PathBuf> {
let directory = runtime_root.join("timelines").join(directory_name);
ensure_direct_directory(&directory, "timeline directory")?;
for name in TIMELINE_STORES {
let path = directory.join(name);
require_direct_state_file_or_absent(&path)?;
require_direct_state_file_or_absent(&sibling_state_lock_path(&path))?;
}
Ok(directory)
}
fn require_direct_state_file_or_absent(path: &Path) -> anyhow::Result<()> {
match fs::symlink_metadata(path) {
Ok(metadata) => {
ensure!(
metadata.is_file() && !metadata.file_type().is_symlink(),
"declared state path {} is indirect or not a regular file",
path.display()
);
#[cfg(target_os = "linux")]
ensure!(
std::os::unix::fs::MetadataExt::nlink(&metadata) == 1,
"declared state path {} is multiply linked",
path.display()
);
Ok(())
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => {
Err(error).with_context(|| format!("inspecting declared state path {}", path.display()))
}
}
}
fn sibling_state_lock_path(path: &Path) -> PathBuf {
let mut name = path
.file_name()
.map(|value| value.to_os_string())
.unwrap_or_else(|| "state.cc".into());
name.push(".lock");
path.with_file_name(name)
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(target_os = "linux")]
#[test]
fn managed_linux_runtime_requires_the_admitted_state_root_binding() {
assert!(admitted_runtime_root(None).is_err());
}
#[test]
fn admitted_state_root_must_name_the_direct_canonical_directory() {
let directory = tempfile::tempdir().unwrap();
let root = fs::canonicalize(directory.path()).unwrap();
assert_eq!(admitted_runtime_root(Some(root.clone())).unwrap(), root);
assert!(admitted_runtime_root(Some(directory.path().join("missing"))).is_err());
}
#[test]
fn post_lease_state_layout_creates_only_the_direct_declared_directories() {
let directory = tempfile::tempdir().unwrap();
let root = fs::canonicalize(directory.path()).unwrap();
prepare_admitted_state_layout(&root).unwrap();
for name in ["service", "timelines"] {
let metadata = fs::symlink_metadata(root.join(name)).unwrap();
assert!(metadata.is_dir());
assert!(!metadata.file_type().is_symlink());
}
}
#[cfg(target_os = "linux")]
#[test]
fn post_lease_state_layout_rejects_symlinks_and_hardlinks() {
use std::os::unix::fs::symlink;
let symlink_directory = tempfile::tempdir().unwrap();
let symlink_root = fs::canonicalize(symlink_directory.path()).unwrap();
let target = symlink_root.join("other.cc");
fs::write(&target, b"not-catalog").unwrap();
symlink(&target, symlink_root.join("catalog.cc")).unwrap();
assert!(prepare_admitted_state_layout(&symlink_root).is_err());
let hardlink_directory = tempfile::tempdir().unwrap();
let hardlink_root = fs::canonicalize(hardlink_directory.path()).unwrap();
let target = hardlink_root.join("other.cc");
fs::write(&target, b"not-catalog").unwrap();
fs::hard_link(&target, hardlink_root.join("catalog.cc")).unwrap();
assert!(prepare_admitted_state_layout(&hardlink_root).is_err());
}
/// A timeline's own stores get the same proof as the service's, before the
/// timeline is opened: a symlink standing in for its play-turn store is
/// refused.
#[cfg(target_os = "linux")]
#[test]
fn a_symlinked_timeline_store_is_refused() {
use std::os::unix::fs::symlink;
let directory = tempfile::tempdir().unwrap();
let root = fs::canonicalize(directory.path()).unwrap();
prepare_admitted_state_layout(&root).unwrap();
let name = "00000000-0000-4000-8000-000000000001";
let timeline = prepare_timeline_directory(&root, name).unwrap();
let target = root.join("other.cc");
fs::write(&target, b"not-play-turn").unwrap();
symlink(&target, timeline.join("play-turn-v1.cc")).unwrap();
assert!(prepare_timeline_directory(&root, name).is_err());
}
}

View file

@ -1,173 +0,0 @@
//! Test support the API tests, the live runtime check and the playtest
//! harness share: a counting port that keeps usage per model, and the one
//! assembly of an `AppState` with signed-in test sessions.
use crate::{
app_session::AppSessionOwner,
begin::{Scale, Vaults},
catalog::Catalog,
heimdall::{HeimdallPort, VerifiedSessionAdmission},
runtime::AppState,
timelines::Timelines,
};
use chrono::Utc;
use ghostlight::{
InferenceFault, InferenceOutput, InferencePort, InferenceRequest, PreparedInference,
};
use serde_json::Value;
use std::{
collections::BTreeMap,
path::Path,
sync::{Arc, Mutex as StdMutex},
};
use tokio::sync::{Mutex, mpsc};
/// What one model was asked and what the provider says it spent.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct ModelUsage {
pub(crate) calls: u64,
pub(crate) prompt: u64,
pub(crate) cached_prompt: u64,
pub(crate) completion: u64,
}
/// Counts every call and the usage the connector reports, per model, around
/// the real port.
pub(crate) struct CountingPort {
inner: Arc<dyn InferencePort>,
usage: StdMutex<BTreeMap<String, ModelUsage>>,
}
impl CountingPort {
pub(crate) fn new(inner: Arc<dyn InferencePort>) -> Arc<Self> {
Arc::new(Self { inner, usage: StdMutex::new(BTreeMap::new()) })
}
pub(crate) fn by_model(&self) -> BTreeMap<String, ModelUsage> {
self.usage.lock().unwrap().clone()
}
pub(crate) fn totals(&self) -> ModelUsage {
self.by_model().values().fold(ModelUsage::default(), |sum, each| ModelUsage {
calls: sum.calls + each.calls,
prompt: sum.prompt + each.prompt,
cached_prompt: sum.cached_prompt + each.cached_prompt,
completion: sum.completion + each.completion,
})
}
}
/// The model a prepared request names: the `model` key wherever the request's
/// serialization keeps it, including inside a string that holds JSON.
fn model_of(value: &Value) -> Option<String> {
match value {
Value::Object(map) => map
.get("model")
.and_then(Value::as_str)
.map(str::to_owned)
.or_else(|| map.values().find_map(model_of)),
Value::Array(items) => items.iter().find_map(model_of),
Value::String(text) if text.starts_with('{') => {
serde_json::from_str::<Value>(text).ok().and_then(|inner| model_of(&inner))
}
_ => None,
}
}
#[async_trait::async_trait]
impl InferencePort for CountingPort {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
self.inner.prepare(request)
}
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
let model = serde_json::to_value(&request)
.ok()
.and_then(|seen| model_of(&seen))
.unwrap_or_else(|| "unknown".into());
let output = self.inner.infer(request).await?;
let usage = output.usage();
let mut table = self.usage.lock().unwrap();
let row = table.entry(model).or_default();
row.calls += 1;
if let Some(usage) = usage {
row.prompt += usage.prompt;
row.cached_prompt += usage.cached_prompt.unwrap_or(0);
row.completion += usage.completion;
}
Ok(output)
}
}
/// An `AppState` over the given pieces with one signed-in session per entry of
/// `accounts` (the same account twice is the same player on two devices), the
/// session cookies in order, and the receiver of the fatal signals. Session
/// custody lives under `directory`.
pub(crate) fn assemble(
directory: &Path,
catalog: Arc<Mutex<Catalog>>,
timelines: Arc<Timelines>,
scale: Arc<Scale>,
vaults: Arc<dyn Vaults>,
heimdall: Arc<dyn HeimdallPort>,
accounts: &[&str],
) -> (AppState, Vec<String>, mpsc::UnboundedReceiver<String>) {
let key = directory.join("session.key");
std::fs::write(&key, [17_u8; 32]).unwrap();
let mut sessions =
AppSessionOwner::open(directory.join("service/app-sessions-v2.cc"), &key).unwrap();
let cookies = accounts
.iter()
.enumerate()
.map(|(index, account)| {
sessions
.create_session(VerifiedSessionAdmission::fixture(
*account,
format!("heimdall-session-{index}"),
1,
Utc::now() + chrono::Duration::hours(1),
Utc::now() + chrono::Duration::days(1),
"fixture-refresh",
))
.unwrap()
})
.collect();
let (fatal, fatal_events) = mpsc::unbounded_channel();
let state = AppState {
catalog,
timelines,
vaults,
scale,
sessions: Arc::new(Mutex::new(sessions)),
heimdall,
auth: Arc::default(),
runtime_id: "ghostlight-test".into(),
runtime_health: None,
fatal,
};
(state, cookies, fatal_events)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::play::tests::ScriptedPort;
#[test]
fn a_prepared_request_names_its_model() {
let port = ScriptedPort::new(vec![]);
let request = InferenceRequest::play(
ghostlight::CommandId::new(),
0,
"claude-opus-5-5",
"be brief",
vec![],
vec![],
100,
)
.unwrap();
let prepared = port.prepare(request).unwrap();
let seen = serde_json::to_value(&prepared).unwrap();
assert_eq!(model_of(&seen).as_deref(), Some("claude-opus-5-5"));
}
}

View file

@ -1,120 +0,0 @@
//! Many timelines in one daemon.
//!
//! Each timeline is its own kernel store with its own mailbox, play table and
//! controller work; every one shares the single routed inference port and the
//! one concurrency pool. A timeline opens on first use and stays warm.
use crate::{
catalog::timeline_directory_name,
play::PlayTable,
state_layout::prepare_timeline_directory,
};
use ghostlight::{
ControllerModels, ControllerPort, ControllerRunner, InferencePort, PersonaLane, WorldMailbox,
open_controller_work,
};
use anyhow::Context;
use std::{collections::HashMap, path::PathBuf, sync::Arc};
use tokio::sync::{Mutex, Semaphore, broadcast, mpsc};
/// What every timeline shares: the one inference port all lanes route through,
/// the model each lane runs on, and the concurrency pool sized to the
/// connector's quota.
pub(crate) struct Shared {
pub(crate) inference: Arc<dyn InferencePort>,
pub(crate) models: ControllerModels,
pub(crate) play_model: String,
pub(crate) permits: Arc<Semaphore>,
}
/// One opened timeline.
pub(crate) struct TimelineHost {
pub(crate) world: WorldMailbox,
pub(crate) controllers: ControllerRunner,
pub(crate) play: Arc<PlayTable>,
/// Pulsed whenever this timeline's turn changes; the stream wakes on it.
pub(crate) changes: broadcast::Sender<()>,
/// Held while a run-ahead sweep runs: one at a time per timeline.
pub(crate) sweeping: Mutex<()>,
}
pub(crate) struct Timelines {
root: PathBuf,
shared: Shared,
hosts: Mutex<HashMap<String, Arc<TimelineHost>>>,
fatal: mpsc::UnboundedSender<String>,
}
impl Timelines {
pub(crate) fn new(root: PathBuf, shared: Shared, fatal: mpsc::UnboundedSender<String>) -> Self {
Self {
root,
shared,
hosts: Mutex::new(HashMap::new()),
fatal,
}
}
pub(crate) fn shared(&self) -> &Shared {
&self.shared
}
/// The host for `id`, opened on first use. Refuses an id that is not
/// exactly `timeline:<canonical uuid>`.
pub(crate) async fn host(&self, id: &str) -> anyhow::Result<Arc<TimelineHost>> {
let name = timeline_directory_name(id).context("timeline id is not canonical")?;
let mut hosts = self.hosts.lock().await;
if let Some(host) = hosts.get(id) {
return Ok(host.clone());
}
let directory = prepare_timeline_directory(&self.root, &name)?;
let (world, owner) = WorldMailbox::open(directory.join("world.cc"))?;
let fatal = self.fatal.clone();
let label = id.to_owned();
tokio::spawn(async move {
let _ = owner.await;
let _ = fatal.send(format!("world owner of {label} stopped while serving"));
});
let work = open_controller_work(directory.join("controller-work.cc"))?;
let controllers = ControllerRunner::open(
world.clone(),
self.shared.inference.clone(),
work,
self.shared.models.clone(),
)?;
let personas = PersonaLane::new(
ControllerPort::new(world.clone()),
self.shared.inference.clone(),
self.shared.models.projector.clone(),
self.shared.models.persona.clone(),
)?;
let play = PlayTable::new(
world.clone(),
personas,
self.shared.inference.clone(),
self.shared.play_model.clone(),
self.shared.permits.clone(),
directory.join("play-turn-v1.cc"),
)?;
let (changes, _) = broadcast::channel(16);
let host = Arc::new(TimelineHost {
world,
controllers,
play: Arc::new(play),
changes,
sweeping: Mutex::new(()),
});
hosts.insert(id.to_owned(), host.clone());
Ok(host)
}
/// Every timeline opened so far; readiness probes these.
pub(crate) async fn opened(&self) -> Vec<(String, Arc<TimelineHost>)> {
self.hosts
.lock()
.await
.iter()
.map(|(id, host)| (id.clone(), host.clone()))
.collect()
}
}

View file

@ -1,242 +0,0 @@
//! The turn log: what the player was shown, turn by turn, kept for as long as
//! the timeline lives.
//!
//! The kernel journal records what happened in the world, not the prose the
//! storyteller wrote about it, and the play row holds only the current turn.
//! So the narration a player read exists in one place until the next turn
//! replaces it. This log is where it stays. It sits next to the timeline's
//! other state and is written by `PlayTable` from the row the screen is drawn
//! from, right after that row is committed, so an entry can never say
//! something the screen did not. It is append-only: nothing here edits or
//! deletes an entry, and a Retry is a new entry that names the one it retries.
use anyhow::{Context, bail, ensure};
use chrono::{DateTime, Utc};
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, path::Path};
const TYPE: &str = "ghostlight.dungeon_turn_log.v1";
/// How a submission ended, as the player was told.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum TurnStatus {
/// The turn closed and narrated.
Committed,
/// The world refused an act of the turn; `refusal` holds the line.
Refused,
/// The turn died on its model; `fault` holds the line shown.
Faulted,
/// The storyteller asked a question and is waiting; `question` holds it.
Asked,
}
/// One submission and what it produced. `seq` is its place in the log, from 1.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct LogEntry {
pub(crate) seq: u64,
pub(crate) turn_id: String,
/// Which submission of that turn this is: 1 opens it, each answer adds one.
pub(crate) submission: u32,
/// The player's text exactly as sent.
pub(crate) text: String,
pub(crate) narration: Option<String>,
pub(crate) question: Option<String>,
pub(crate) refusal: Option<String>,
pub(crate) fault: Option<String>,
pub(crate) status: TurnStatus,
/// The world revision the entry rests on, or `None` when the kernel could
/// not be read at the moment the entry was written.
pub(crate) world_revision: Option<u64>,
/// The entry this one retries.
pub(crate) retry_of: Option<u64>,
pub(crate) recorded_at: DateTime<Utc>,
}
/// An entry before it has a place in the log.
pub(crate) struct NewEntry {
pub(crate) turn_id: String,
pub(crate) submission: u32,
pub(crate) text: String,
pub(crate) narration: Option<String>,
pub(crate) question: Option<String>,
pub(crate) refusal: Option<String>,
pub(crate) fault: Option<String>,
pub(crate) status: TurnStatus,
pub(crate) world_revision: Option<u64>,
pub(crate) retry_of: Option<u64>,
}
/// A page of the log, oldest first, newest last.
pub(crate) struct Page {
pub(crate) entries: Vec<(LogEntry, Option<u64>)>,
/// Pass as `before` to read the page of older entries; `None` at the start.
pub(crate) older: Option<u64>,
}
pub(crate) struct TurnLog {
store: OwnedRedbMessagePackBackingStore,
/// Every entry, `entries[n]` having `seq == n + 1`.
entries: Vec<LogEntry>,
}
fn key_of(seq: u64) -> String {
format!("{seq:012}")
}
impl TurnLog {
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
store.validate_path_identity().context("turn log path identity is invalid")?;
let mut entries = Vec::new();
for row in store.pull_all()? {
ensure!(row.r#type == TYPE, "turn log holds a foreign record");
let entry: LogEntry = rmp_serde::from_slice(&row.payload).context("a turn log entry did not decode")?;
ensure!(row.key == key_of(entry.seq), "a turn log entry sits under the wrong key");
entries.push(entry);
}
entries.sort_by_key(|entry| entry.seq);
for (index, entry) in entries.iter().enumerate() {
if entry.seq != index as u64 + 1 {
bail!("the turn log has a gap before entry {}", entry.seq);
}
}
Ok(Self { store, entries })
}
pub(crate) fn contains(&self, seq: u64) -> bool {
seq >= 1 && seq <= self.entries.len() as u64
}
pub(crate) fn recorded(&self, turn_id: &str, submission: u32) -> bool {
self.entries
.iter()
.rev()
.any(|entry| entry.turn_id == turn_id && entry.submission == submission)
}
/// Appends `new` unless that turn's submission is already recorded.
/// Returns the new entry's `seq`, or `None` when it was already there.
pub(crate) fn record(&mut self, new: NewEntry) -> anyhow::Result<Option<u64>> {
if self.recorded(&new.turn_id, new.submission) {
return Ok(None);
}
if let Some(target) = new.retry_of {
ensure!(self.contains(target), "a retry names an entry the log does not hold");
}
let seq = self.entries.len() as u64 + 1;
let entry = LogEntry {
seq,
turn_id: new.turn_id,
submission: new.submission,
text: new.text,
narration: new.narration,
question: new.question,
refusal: new.refusal,
fault: new.fault,
status: new.status,
world_revision: new.world_revision,
retry_of: new.retry_of,
recorded_at: Utc::now(),
};
let row = CultCacheEnvelope {
key: key_of(seq),
r#type: TYPE.into(),
payload: rmp_serde::to_vec_named(&entry)?,
stored_at: entry.recorded_at.to_rfc3339(),
schema_id: Some(TYPE.into()),
};
self.store.validate_path_identity().context("turn log ownership was lost")?;
if !self.store.compare_and_swap_batch(&[], vec![row])? {
bail!("turn log entry {seq} already exists on disk");
}
self.entries.push(entry);
Ok(Some(seq))
}
/// Up to `limit` entries older than `before` (the newest when `None`),
/// each with the `seq` of the entry that retried it, if one did.
pub(crate) fn page(&self, before: Option<u64>, limit: usize) -> Page {
let end = before.map_or(self.entries.len(), |before| (before.saturating_sub(1) as usize).min(self.entries.len()));
let start = end.saturating_sub(limit.max(1));
let retried_by: HashMap<u64, u64> = self
.entries
.iter()
.rev()
.filter_map(|entry| entry.retry_of.map(|target| (target, entry.seq)))
.collect();
let entries = self.entries[start..end]
.iter()
.map(|entry| (entry.clone(), retried_by.get(&entry.seq).copied()))
.collect();
Page { entries, older: (start > 0).then_some(start as u64 + 1) }
}
}
#[cfg(test)]
mod tests {
use super::*;
fn new(turn: &str, submission: u32, text: &str) -> NewEntry {
NewEntry {
turn_id: turn.into(),
submission,
text: text.into(),
narration: Some(format!("story of {text}")),
question: None,
refusal: None,
fault: None,
status: TurnStatus::Committed,
world_revision: Some(7),
retry_of: None,
}
}
#[test]
fn entries_append_page_newest_last_and_survive_a_reopen() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("turn-log-v1.cc");
{
let mut log = TurnLog::open(&path).unwrap();
for n in 1..=5 {
assert_eq!(log.record(new(&format!("t{n}"), 1, &format!("say {n}"))).unwrap(), Some(n));
}
assert_eq!(log.record(new("t3", 1, "say 3 again")).unwrap(), None, "a recorded submission is never rewritten");
let newest = log.page(None, 2);
assert_eq!(newest.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [4, 5]);
assert_eq!(newest.older, Some(4));
let older = log.page(newest.older, 2);
assert_eq!(older.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [2, 3]);
let oldest = log.page(older.older, 2);
assert_eq!(oldest.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [1]);
assert_eq!(oldest.older, None);
}
let log = TurnLog::open(&path).unwrap();
let all = log.page(None, 50);
assert_eq!(all.entries.len(), 5);
assert_eq!(all.entries[2].0.text, "say 3", "the first write stands");
assert_eq!(all.entries[2].0.narration.as_deref(), Some("story of say 3"));
}
#[test]
fn a_retry_is_a_new_entry_and_the_old_one_reads_as_superseded() {
let directory = tempfile::tempdir().unwrap();
let mut log = TurnLog::open(directory.path().join("turn-log-v1.cc")).unwrap();
let mut faulted = new("t1", 1, "I knock");
faulted.status = TurnStatus::Faulted;
faulted.narration = None;
faulted.fault = Some("the storyteller lost the thread".into());
log.record(faulted).unwrap();
let mut retry = new("t2", 1, "I knock");
retry.retry_of = Some(1);
log.record(retry).unwrap();
let page = log.page(None, 10);
assert_eq!(page.entries[0].0.status, TurnStatus::Faulted, "the old entry stays as it was");
assert_eq!(page.entries[0].1, Some(2), "and reads as superseded by the retry");
assert_eq!(page.entries[1].1, None);
let mut bad = new("t3", 1, "x");
bad.retry_of = Some(99);
assert!(log.record(bad).is_err(), "a retry must name an entry the log holds");
}
}

View file

@ -1,249 +0,0 @@
//! The production vault catalog: the profiles production serves, over the
//! snapshots an operator import left in the store.
//!
//! The daemon never reads a vault directory. `VaultSnapshot::build` is the
//! only reader of one, and it runs in the `import-vault` command; what lives
//! here is a read of the store the import wrote: which snapshot a profile last
//! produced, and that snapshot's evidence.
use crate::begin::{VaultOffer, VaultSeed, Vaults};
use anyhow::{Context, bail};
use ghostlight::{
EvidenceSource, SnapshotId, VaultEra, VaultEvidenceSource, VaultError, VaultSnapshot, WorldEra,
production_eras, production_profile, production_vault_names,
};
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
/// The snapshot store, under the state root.
pub(crate) const SNAPSHOT_DIRECTORY: &str = "snapshots";
/// The directory the host keeps its vault copies in; the importer roots every
/// production profile under it.
pub(crate) const VAULT_BASE_ENVIRONMENT: &str = "GHOSTLIGHT_VAULT_BASE";
pub(crate) struct SnapshotVaults {
store: PathBuf,
/// A snapshot's evidence for one era, loaded once: every turn's run-ahead
/// sweep asks for it again. Cache only; the era is the world's.
evidence: Mutex<HashMap<(String, String), Arc<dyn EvidenceSource>>>,
}
impl SnapshotVaults {
pub(crate) fn new(state_root: &Path) -> Self {
Self {
store: state_root.join(SNAPSHOT_DIRECTORY),
evidence: Mutex::new(HashMap::new()),
}
}
fn imported(&self, profile: &str) -> Result<SnapshotId, VaultError> {
VaultSnapshot::current_id(&self.store, profile)
}
}
/// The evidence of `snapshot` for `era`, which withholds the era's paths; a
/// world with no era withholds nothing.
fn evidence_for(snapshot: &VaultSnapshot, era: Option<&VaultEra>) -> anyhow::Result<Arc<dyn EvidenceSource>> {
let evidence = VaultEvidenceSource::from_snapshot(snapshot, "", era.map_or(&[], |era| era.withhold))
.context("the snapshot holds no evidence")?;
Ok(Arc::new(evidence))
}
impl Vaults for SnapshotVaults {
fn offers(&self) -> Vec<VaultOffer> {
production_vault_names()
.filter(|name| self.imported(name).is_ok())
.filter_map(|name| {
let (eras, default) = production_eras(name)?;
Some(VaultOffer {
name: name.to_owned(),
default_era: default.to_owned(),
eras: eras.iter().map(world_era).collect(),
})
})
.collect()
}
fn open(&self, profile: &str, era: Option<&str>) -> anyhow::Result<VaultSeed> {
let Some((eras, default)) = production_eras(profile) else {
bail!("vault profile `{profile}` is not one this server serves");
};
let wanted = era.unwrap_or(default);
let chosen = eras
.iter()
.find(|candidate| candidate.id == wanted)
.with_context(|| format!("vault profile `{profile}` has no era `{wanted}`"))?;
let id = self
.imported(profile)
.map_err(|_| anyhow::anyhow!("vault profile `{profile}` has not been imported"))?;
let snapshot = VaultSnapshot::load(&self.store, &id)
.map_err(|error| anyhow::anyhow!("vault profile `{profile}`: {error}"))?;
let evidence = evidence_for(&snapshot, Some(chosen))?;
self.evidence
.lock()
.unwrap()
.insert((id.to_string(), chosen.id.to_owned()), evidence.clone());
Ok(VaultSeed {
snapshot_id: id.to_string(),
evidence,
premise: snapshot.premise(),
era: world_era(chosen),
})
}
fn evidence(&self, snapshot_id: &str, era: Option<&str>) -> anyhow::Result<Arc<dyn EvidenceSource>> {
let key = (snapshot_id.to_owned(), era.unwrap_or_default().to_owned());
if let Some(held) = self.evidence.lock().unwrap().get(&key) {
return Ok(held.clone());
}
let id = SnapshotId::parse(snapshot_id).context("the snapshot id is not an id")?;
let snapshot = VaultSnapshot::load(&self.store, &id)
.map_err(|error| anyhow::anyhow!("snapshot {snapshot_id}: {error}"))?;
let name = &snapshot.profile().name;
let chosen = match era {
None => None,
Some(era) => Some(
production_eras(name)
.and_then(|(eras, _)| eras.iter().find(|candidate| candidate.id == era))
.with_context(|| format!("vault profile `{name}` has no era `{era}`"))?,
),
};
let evidence = evidence_for(&snapshot, chosen)?;
self.evidence.lock().unwrap().insert(key, evidence.clone());
Ok(evidence)
}
}
fn world_era(era: &VaultEra) -> WorldEra {
WorldEra {
id: era.id.to_owned(),
label: era.label.to_owned(),
description: era.description.to_owned(),
}
}
/// `ghostlight-dungeon import-vault --state-root PATH PROFILE`: the one reader
/// of a vault directory. Builds the production profile of `profile` rooted
/// under `$GHOSTLIGHT_VAULT_BASE`, stores the snapshot and records it as the
/// profile's current import. Prints the snapshot id.
pub(crate) fn import(state_root: &Path, profile: &str) -> anyhow::Result<String> {
let base = std::env::var_os(VAULT_BASE_ENVIRONMENT)
.map(PathBuf::from)
.with_context(|| format!("{VAULT_BASE_ENVIRONMENT} is required"))?;
let Some(profile) = production_profile(profile, &base) else {
bail!("vault profile `{profile}` is not one this server serves");
};
let store = state_root.join(SNAPSHOT_DIRECTORY);
let snapshot = VaultSnapshot::build(&profile).map_err(|error| anyhow::anyhow!("{error}"))?;
snapshot
.import_into(&store)
.map_err(|error| anyhow::anyhow!("{error}"))?;
snapshot
.record_current(&store)
.map_err(|error| anyhow::anyhow!("{error}"))?;
Ok(format!("{} notes={} id={}", profile.name, snapshot.note_count(), snapshot.id()))
}
#[cfg(test)]
mod tests {
use super::*;
fn write(root: &Path, relative: &str, text: &str) {
let path = root.join(relative);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
/// An imported snapshot of a tiny Avatar vault under a state root.
fn imported_avatar() -> (tempfile::TempDir, SnapshotVaults, String) {
let state = tempfile::tempdir().unwrap();
let vault = tempfile::tempdir().unwrap();
write(vault.path(), "Avatar/index.md", "A river city under a spirit sky.\n");
write(vault.path(), "Avatar/Places/Harbor.md", "The harbor of the river city.\n");
let profile = production_profile("avatar", vault.path()).unwrap();
let snapshot = VaultSnapshot::build(&profile).unwrap();
let store = state.path().join(SNAPSHOT_DIRECTORY);
snapshot.import_into(&store).unwrap();
snapshot.record_current(&store).unwrap();
let id = snapshot.id().to_string();
let vaults = SnapshotVaults::new(state.path());
(state, vaults, id)
}
/// The id gate keeps a stored id from naming another path: a short hex
/// string and a long non-hex one are both refused before any path is built.
#[test]
fn a_stored_snapshot_id_that_is_not_an_id_is_refused_before_a_path_is_built() {
let (_state, vaults, id) = imported_avatar();
for bad in ["abc".to_owned(), format!("../{}", &id[3..]), id.to_uppercase()] {
let error = vaults.evidence(&bad, Some("rda-return")).err().expect("refused").to_string();
assert!(error.contains("not an id"), "{bad}: {error}");
}
assert!(vaults.evidence(&id, Some("rda-return")).is_ok());
}
#[test]
fn it_lists_the_imported_profiles_and_opens_the_recorded_snapshot() {
let (_state, vaults, id) = imported_avatar();
assert_eq!(vaults.offers().iter().map(|offer| offer.name.as_str()).collect::<Vec<_>>(), ["avatar"]);
let seed = vaults.open("avatar", None).unwrap();
assert_eq!(seed.snapshot_id, id);
assert_eq!(seed.premise.as_deref(), Some("A river city under a spirit sky."));
assert_eq!(seed.era.id, "rda-return", "an omitted era is the profile's default");
assert!(vaults.evidence(&id, Some("rda-return")).is_ok());
assert!(vaults.evidence(&id, Some("no-such-era")).is_err());
}
#[test]
fn a_profile_never_imported_is_refused_by_name_and_so_is_a_stranger() {
let (_state, vaults, _) = imported_avatar();
let never = vaults.open("zyphos", None).err().unwrap().to_string();
assert!(never.contains("`zyphos` has not been imported"), "{never}");
let stranger = vaults.open("../avatar", None).err().unwrap().to_string();
assert!(stranger.contains("is not one this server serves"), "{stranger}");
assert!(vaults.evidence("not-an-id", Some("rda-return")).is_err());
}
/// The daemon side is a read of the store alone: with the vault directory
/// gone the profile still opens.
#[test]
fn opening_a_profile_reads_the_store_and_never_the_vault() {
let (_state, vaults, _) = imported_avatar();
// `imported_avatar` dropped its vault directory already.
assert!(vaults.open("avatar", None).is_ok());
}
/// A pre-Elysium Aetheria world never sees the Post-Elysium folder, in the
/// seed's evidence or in the evidence reopened for run-ahead; a
/// post-Elysium world does.
#[tokio::test]
async fn a_pre_elysium_world_never_sees_the_post_elysium_folder() {
use ghostlight::EvidenceQuery;
let state = tempfile::tempdir().unwrap();
let vault = tempfile::tempdir().unwrap();
write(vault.path(), "AetheriaLore/Aetheria/Worldbuilding/Post-Elysium/Aether.md", "The aether answers espers.\n");
write(vault.path(), "AetheriaLore/Aetheria/Worldbuilding/Pre-Elysium/Collapse.md", "The grid fails.\n");
let snapshot = VaultSnapshot::build(&production_profile("aetheria", vault.path()).unwrap()).unwrap();
let store = state.path().join(SNAPSHOT_DIRECTORY);
snapshot.import_into(&store).unwrap();
snapshot.record_current(&store).unwrap();
let id = snapshot.id().to_string();
let vaults = SnapshotVaults::new(state.path());
let aether = EvidenceQuery { referents: vec!["Aether".into()] };
let seed = vaults.open("aetheria", None).unwrap();
assert_eq!(seed.era.id, "pre-elysium", "late Sol is the default");
assert!(seed.evidence.retrieve(&aether).await.unwrap().is_empty(), "the seed's evidence");
let reopened = vaults.evidence(&id, Some("pre-elysium")).unwrap();
assert!(reopened.retrieve(&aether).await.unwrap().is_empty(), "run-ahead's evidence");
let after = vaults.open("aetheria", Some("post-elysium")).unwrap();
assert!(!after.evidence.retrieve(&aether).await.unwrap().is_empty());
assert!(vaults.open("aetheria", Some("nowhen")).is_err());
}
}

View file

@ -1,27 +0,0 @@
use std::{fs, path::Path, process::Command};
#[test]
fn embedded_commit_matches_checkout_head() {
let repo_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let output = Command::new("git")
.args(["rev-parse", "HEAD"])
.current_dir(&repo_root)
.output()
.expect("git must be available for the provenance regression test");
let checkout_head = if output.status.success() {
String::from_utf8(output.stdout)
.expect("git commit must be UTF-8")
.trim()
.to_owned()
} else {
fs::read_to_string(repo_root.join(".ghostlight-source-commit"))
.expect("frozen source archive must carry its exact commit witness")
.trim()
.to_owned()
};
assert_eq!(
env!("GHOSTLIGHT_BUILD_COMMIT"),
checkout_head,
"the binary embedded stale Git provenance"
);
}

View file

@ -1,11 +0,0 @@
[package]
name = "ghostlight-persona-projection"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
serde.workspace = true
sha2.workspace = true
unicode-segmentation.workspace = true

File diff suppressed because it is too large Load diff

View file

@ -1,15 +0,0 @@
[package]
name = "ghostlight-verse"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
anyhow.workspace = true
chrono.workspace = true
ghostlight = { path = "../ghostlight" }
tokio.workspace = true
[dev-dependencies]
serde_json.workspace = true
tempfile = "3"

View file

@ -1,349 +0,0 @@
//! The verse runner's operator command line.
//!
//! `genesis` creates the canonical Aetheria verse world in a state root, and
//! `run` advances it a given number of ticks under a token cap, printing per
//! tick what each faction did and what it cost. A run starts only when this
//! command is invoked, and ends when it has done what it was asked.
//!
//! The state root holds `world.cc`, `controller-work.cc`, `runs.cc` and
//! `calls.cc`. The provider key is read from a file at run time and appears
//! nowhere else.
use anyhow::{Context, Result, anyhow, bail};
use chrono::{Duration, Utc};
use ghostlight::{
CommandBody, CommandId, ControllerModels, ControllerOpenError, ControllerRunner, DEFAULT_HOSTED_MODEL_PREFIX,
DEFAULT_LOCAL_MODEL_PREFIX, CallRecordStore, CoverBudget, CreateVerseWorldIntent,
HostedBinding, Lens, LensWeights, LocalBinding, PrincipalCommandIntent, RecordingInferencePort,
RunStart, RunStatus, TickMinutes, VerifiedPrincipalEvidence, VerseRunConfig, VerseRunStore,
WorldMailbox, call_run_id, id_text, open_controller_work, open_inference,
read_aetheria_catalog, run_manual,
};
use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
/// What a manual run spends per tick on cognition cells. The operator's lever
/// on cost is the token cap; the partition always covers every faction.
const COVER: CoverBudget = CoverBudget {
cells: 8,
constituent_cap: 8,
urgency_slots: 2,
};
const RUNTIME_ID: &str = "ghostlight-verse";
#[tokio::main]
async fn main() -> ExitCode {
let arguments: Vec<String> = std::env::args().skip(1).collect();
match command(arguments).await {
Ok(code) => code,
Err(error) => {
eprintln!("ghostlight-verse: {error:#}");
ExitCode::FAILURE
}
}
}
async fn command(arguments: Vec<String>) -> Result<ExitCode> {
let Some((name, rest)) = arguments.split_first() else {
bail!("usage: ghostlight-verse genesis|run [flags]");
};
match name.as_str() {
"genesis" => genesis(Flags::parse(rest, &GENESIS_FLAGS)?).await,
"run" => run(Flags::parse(rest, &RUN_FLAGS)?).await,
_ => bail!("unknown command, expected genesis or run"),
}
}
const GENESIS_FLAGS: [&str; 4] = ["catalog", "aetheria-commit", "state", "owner-hash"];
const RUN_FLAGS: [&str; 7] = [
"state",
"ticks",
"token-cap",
"tick-span-minutes",
"model",
"base-url",
"key-file",
];
/// Flags a command may omit.
const OPTIONAL: [&str; 1] = ["key-file"];
/// `--name value` pairs, each named once and from the command's own list.
struct Flags(BTreeMap<&'static str, String>);
impl Flags {
fn parse(arguments: &[String], allowed: &[&'static str]) -> Result<Self> {
let mut seen = BTreeMap::new();
let mut rest = arguments.iter();
while let Some(flag) = rest.next() {
let Some(name) = flag.strip_prefix("--") else {
bail!("expected a --flag, found a bare argument");
};
let Some(&known) = allowed.iter().find(|candidate| **candidate == name) else {
bail!("a flag this command does not take was given");
};
let Some(value) = rest.next() else {
bail!("--{known} needs a value");
};
if seen.insert(known, value.clone()).is_some() {
bail!("--{known} was given twice");
}
}
for &required in allowed {
if !OPTIONAL.contains(&required) && !seen.contains_key(required) {
bail!("--{required} is required");
}
}
Ok(Self(seen))
}
fn text(&self, name: &str) -> &str {
self.0.get(name).map_or("", String::as_str)
}
fn path(&self, name: &str) -> PathBuf {
PathBuf::from(self.text(name))
}
fn number<T: std::str::FromStr + PartialOrd + Default>(&self, name: &str) -> Result<T> {
match self.text(name).parse::<T>() {
Ok(value) if value > T::default() => Ok(value),
_ => bail!("--{name} is not a positive integer"),
}
}
}
async fn genesis(flags: Flags) -> Result<ExitCode> {
let state = flags.path("state");
std::fs::create_dir_all(&state).context("the state directory cannot be created")?;
let catalog = read_aetheria_catalog(flags.path("catalog"))
.context("the Aetheria catalog cannot be read")?;
let factions = catalog.factions.len();
let principal = VerifiedPrincipalEvidence::new(flags.text("owner-hash"), Utc::now() + Duration::hours(1));
let (mailbox, task) = WorldMailbox::open(state.join("world.cc"))
.map_err(store_fault("the world file in --state cannot be opened"))?;
let receipt = mailbox
.create_verse(
CreateVerseWorldIntent {
id: CommandId::new(),
title: "The Aetheria Verse".into(),
brief: "The Aetheria verse, simulated from its catalog.".into(),
catalog,
aetheria_commit: flags.text("aetheria-commit").into(),
lens_weights: LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 1)).collect()),
targets: BTreeMap::new(),
},
&principal,
)
.await
.context("the verse world cannot be created")?;
// A created world is a draft: the owner approves and activates it, so the
// factions hold opportunities.
for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] {
let revision = mailbox.snapshot().await.context("the world cannot be read")?.revision;
mailbox
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: revision,
body,
},
&principal,
)
.await
.context("the world cannot be activated")?;
}
drop(mailbox);
task.await.context("the world file did not close cleanly")?;
println!("world {}", id_text(receipt.world_id));
println!("factions {factions}");
println!("phase Active");
Ok(ExitCode::SUCCESS)
}
async fn run(flags: Flags) -> Result<ExitCode> {
let state = flags.path("state");
let ticks: u32 = flags.number("ticks")?;
let cap: u64 = flags.number("token-cap")?;
let span: u32 = flags.number("tick-span-minutes")?;
let tick_span = TickMinutes::new(span).context("--tick-span-minutes is outside the clock's span")?;
if !state.join("world.cc").is_file() {
bail!("the state directory holds no world; run genesis first");
}
let model = flags.text("model").to_owned();
let models = ControllerModels {
projector: model.clone(),
persona: model.clone(),
interpreter: model.clone(),
operational_agent: model.clone(),
elaborator: model.clone(),
};
let inner = open_lane(&flags, &model, &models)?;
let (mailbox, task) = WorldMailbox::open(state.join("world.cc"))
.map_err(store_fault("the world file in --state cannot be opened"))?;
let world = mailbox.snapshot().await.context("the world cannot be read")?;
let calls = Arc::new(CallRecordStore::open(state.join("calls.cc")).map_err(store_fault("the call records in --state cannot be opened"))?);
let runs = VerseRunStore::open(state.join("runs.cc")).map_err(store_fault("the run records in --state cannot be opened"))?;
let work = open_controller_work(state.join("controller-work.cc"))
.map_err(store_fault("the controller work store in --state cannot be opened"))?;
let config = VerseRunConfig {
ticks,
tick_span,
cover: COVER,
};
let claim = runs
.claim(&world, cap, &config)
.context("the run cannot be claimed")?;
let sequence = claim.sequence();
// A start that fails after the claim ends the claimed run, so it binds
// nothing: the next claim takes the next number.
let started = RecordingInferencePort::open(
inner,
calls,
call_run_id(sequence),
cap,
&RunStart::of(&world),
)
.context("the run's call records cannot be opened")
.and_then(|port| {
let port = Arc::new(port);
ControllerRunner::open(mailbox.clone(), port.clone(), work, models)
.map(|runner| (port, runner))
.context("the controller organ cannot open")
});
let (port, runner) = match started {
Ok(started) => started,
Err(error) => {
return Err(match runs.abandon(claim, "start_refused") {
Ok(()) => error,
Err(_) => error.context("the refused run's record could not be ended"),
});
}
};
println!(
"run {sequence}: {ticks} ticks of {span} minutes, cap {cap} tokens, model {model}"
);
let interrupted = Arc::new(AtomicBool::new(false));
{
let interrupted = interrupted.clone();
tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_ok() {
interrupted.store(true, Ordering::SeqCst);
}
});
}
let outcome = run_manual(
&mailbox,
&runner,
&port,
&runs,
claim,
&config,
|report| {
print!("{report}");
if interrupted.load(Ordering::SeqCst) {
ControlFlow::Break(())
} else {
ControlFlow::Continue(())
}
},
)
.await
.context("the run could not be recorded")?;
println!(
"status: {}; {} of {} ticks closed",
outcome.record.status,
outcome.record.ticks_closed(),
outcome.record.ticks_requested
);
drop(runner);
drop(port);
drop(mailbox);
task.await.context("the world file did not close cleanly")?;
Ok(match outcome.record.status {
RunStatus::Failed { .. } => ExitCode::FAILURE,
_ => ExitCode::SUCCESS,
})
}
/// The inference lane the model's prefix names. A hosted model needs an https
/// origin and a key file; a local one reaches a loopback server and needs
/// neither, so a key file beside it is refused.
fn open_lane(
flags: &Flags,
model: &str,
models: &ControllerModels,
) -> Result<Arc<dyn ghostlight::InferencePort>> {
let (mut hosted, mut local) = (None, None);
if model.starts_with(DEFAULT_HOSTED_MODEL_PREFIX) {
let Some(key) = flags.0.get("key-file") else {
bail!("a hosted model needs --key-file");
};
hosted = Some(HostedBinding {
base_url: flags.text("base-url").to_owned(),
key_path: Path::new(key).to_owned(),
model_prefix: DEFAULT_HOSTED_MODEL_PREFIX.into(),
caller_runtime_id: RUNTIME_ID.into(),
});
} else if model.starts_with(DEFAULT_LOCAL_MODEL_PREFIX) {
if flags.0.contains_key("key-file") {
bail!("a local model takes no --key-file");
}
let endpoint: SocketAddr = flags
.text("base-url")
.strip_prefix("http://")
.and_then(|address| address.trim_end_matches('/').parse().ok())
.context("--base-url for a local model is not http://<address>:<port>")?;
local = Some(LocalBinding {
endpoint,
model_prefix: DEFAULT_LOCAL_MODEL_PREFIX.into(),
caller_runtime_id: RUNTIME_ID.into(),
});
} else {
bail!("--model names no inference lane (expected a hosted/ or local/ prefix)");
}
open_inference(None, None, local, hosted, &models.each())
.map_err(|error| anyhow!(lane_fault(&error)))
}
/// A store that cannot open says which one and that it is under `--state`,
/// never the path or the store's own text, which carries the path.
fn store_fault<E>(message: &'static str) -> impl FnOnce(E) -> anyhow::Error {
move |_| anyhow!(message)
}
/// What a lane that cannot open says: the flag or the kind of fault, never a
/// value the operator passed.
fn lane_fault(error: &ControllerOpenError) -> &'static str {
match error {
ControllerOpenError::InvalidModels => "--model is not an exact nonempty identifier",
ControllerOpenError::Connector(_) => "the connector lane cannot open",
ControllerOpenError::WorkStore(_) => "the controller work journal cannot open",
ControllerOpenError::UnroutableModel { .. } => "--model is claimed by no inference lane",
ControllerOpenError::SdkSidecarMissing { .. } => "the SDK sidecar entry is not a file",
ControllerOpenError::LocalEndpointNotLoopback { .. } => {
"--base-url for a local model must be a loopback address"
}
ControllerOpenError::HostedEndpointNotHttps => {
"--base-url for a hosted model must be an https URL"
}
ControllerOpenError::HostedKeyUnreadable => {
"--key-file is unreadable, empty, or not one run of visible ASCII"
}
ControllerOpenError::SharedModelPrefix { .. } => "two inference lanes claim one model prefix",
ControllerOpenError::SidecarClaimsConnectorModel { .. } => {
"the SDK sidecar prefix claims a connector model"
}
ControllerOpenError::EmptyModelPrefix { .. } => "an inference lane's model prefix is empty",
}
}

View file

@ -1,445 +0,0 @@
//! The `ghostlight-verse` command against a loopback scripted responder. No
//! real model is called and no key file is read: the responder answers the
//! OpenAI-compatible chat-completions request the local lane sends.
use serde_json::{Value, json};
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::Path;
use std::process::{Command, Output};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
const BINARY: &str = env!("CARGO_BIN_EXE_ghostlight-verse");
const CATALOG: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../ghostlight/tests/fixtures/aetheria-verse-catalog.cc"
);
const COMMIT: &str = "92b82e9aa5bb422c568c4bfc85a8f641426a41fc";
/// What the responder reports each call cost: 120 prompt and 30 completion.
const PER_CALL: u64 = 150;
fn verse(arguments: &[&str]) -> Output {
Command::new(BINARY).args(arguments).output().unwrap()
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).into_owned()
}
fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).into_owned()
}
fn genesis(state: &Path) -> Output {
verse(&[
"genesis",
"--catalog",
CATALOG,
"--aetheria-commit",
COMMIT,
"--state",
state.to_str().unwrap(),
"--owner-hash",
"verse-owner",
])
}
/// Answers every chat-completions request with one tool call: the faction the
/// prompt names speaks its own line. Counts the requests it served.
struct Responder {
address: SocketAddr,
served: Arc<AtomicUsize>,
}
impl Responder {
fn start() -> Self {
Self::answering(200)
}
/// A provider that refuses every call with this status.
fn refusing(status: u16) -> Self {
Self::answering(status)
}
fn answering(status: u16) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let served = Arc::new(AtomicUsize::new(0));
let counter = served.clone();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { return };
let counter = counter.clone();
std::thread::spawn(move || serve(stream, &counter, status));
}
});
Self { address, served }
}
fn url(&self) -> String {
format!("http://{}", self.address)
}
}
fn serve(mut stream: TcpStream, served: &AtomicUsize, status: u16) {
let mut raw = Vec::new();
let mut chunk = [0u8; 4096];
let (head_end, length) = loop {
let read = stream.read(&mut chunk).unwrap_or(0);
if read == 0 {
return;
}
raw.extend_from_slice(&chunk[..read]);
if let Some(end) = raw.windows(4).position(|window| window == b"\r\n\r\n") {
let head = String::from_utf8_lossy(&raw[..end]).to_ascii_lowercase();
let length = head
.lines()
.find_map(|line| line.strip_prefix("content-length:"))
.and_then(|value| value.trim().parse::<usize>().ok())
.unwrap_or(0);
break (end + 4, length);
}
};
while raw.len() < head_end + length {
let read = stream.read(&mut chunk).unwrap_or(0);
if read == 0 {
return;
}
raw.extend_from_slice(&chunk[..read]);
}
let request: Value = serde_json::from_slice(&raw[head_end..head_end + length]).unwrap();
let text = request.to_string();
let faction = ["Adrasteia", "Brannoch"]
.into_iter()
.find(|name| text.contains(&format!("Decision owner:\\n{name}\\n")))
.expect("a request names its faction");
let sequence = served.fetch_add(1, Ordering::SeqCst);
let reply = json!({
"id": format!("reply-{sequence}"),
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": format!("call-{sequence}"),
"type": "function",
"function": {
"name": "speak",
"arguments": json!({ "text": format!("{faction} holds the line.") }).to_string(),
},
}],
},
"finish_reason": "tool_calls",
}],
"usage": { "prompt_tokens": 120, "completion_tokens": 30 },
})
.to_string();
let response = format!(
"HTTP/1.1 {status} Scripted\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}",
reply.len()
);
let _ = stream.write_all(response.as_bytes());
}
fn run(state: &Path, responder: &Responder, ticks: &str, cap: &str) -> Output {
verse(&[
"run",
"--state",
state.to_str().unwrap(),
"--ticks",
ticks,
"--token-cap",
cap,
"--tick-span-minutes",
"60",
"--model",
"local/scripted",
"--base-url",
&responder.url(),
])
}
#[test]
fn binary_run_prints_acts_and_spend() {
let state = tempfile::tempdir().unwrap();
let made = genesis(state.path());
assert!(made.status.success(), "{}", stderr(&made));
let made = stdout(&made);
assert!(made.contains("factions 2\n") && made.contains("phase Active\n"), "{made}");
assert!(state.path().join("world.cc").is_file());
let responder = Responder::start();
let output = run(state.path(), &responder, "2", "1000000");
assert!(output.status.success(), "{}", stderr(&output));
let text = stdout(&output);
// Two ticks, each with both factions named by verb, and the spend as it
// accrues against the cap.
assert!(text.starts_with("run 1: 2 ticks of 60 minutes, cap 1000000 tokens"), "{text}");
for tick in 0..2u64 {
let spent = PER_CALL * 2 * (tick + 1);
assert!(
text.contains(&format!("tick {tick} closed: 2 cells, 2 acts, 0 refused\n")),
"{text}"
);
assert!(
text.contains(&format!(
" tokens: {} this tick, {spent} spent, {} remaining\n",
PER_CALL * 2,
1_000_000 - spent
)),
"{text}"
);
}
for faction in ["Adrasteia", "Brannoch"] {
assert_eq!(
text.matches(&format!(" {faction} speak [")).count(),
2,
"{text}"
);
assert!(text.contains(&format!("says \"{faction} holds the line.\"")), "{text}");
}
assert!(text.ends_with("status: Completed; 2 of 2 ticks closed\n"), "{text}");
assert_eq!(responder.served.load(Ordering::SeqCst), 4);
// The state root holds each store the run wrote.
for file in ["world.cc", "controller-work.cc", "runs.cc", "calls.cc"] {
assert!(state.path().join(file).is_file(), "{file} was not written");
}
// A second run is the next in the world and carries on from its clock.
let again = run(state.path(), &responder, "1", "1000000");
assert!(again.status.success(), "{}", stderr(&again));
let text = stdout(&again);
assert!(text.starts_with("run 2: 1 ticks of 60 minutes"), "{text}");
assert!(text.contains("tick 2 closed: 2 cells, 2 acts, 0 refused\n"), "{text}");
}
#[test]
fn a_cap_the_first_call_could_pass_ends_the_run_with_nothing_spent() {
let state = tempfile::tempdir().unwrap();
assert!(genesis(state.path()).status.success());
let responder = Responder::start();
let output = run(state.path(), &responder, "3", "1000");
assert!(output.status.success(), "{}", stderr(&output));
let text = stdout(&output);
assert!(text.contains("tick 0 open: "), "{text}");
assert!(text.contains("tokens: 0 this tick, 0 spent, 1000 remaining"), "{text}");
assert!(text.ends_with("status: BudgetExhausted; 0 of 3 ticks closed\n"), "{text}");
assert_eq!(responder.served.load(Ordering::SeqCst), 0, "no call was made");
}
#[test]
fn a_run_that_fails_says_so_and_exits_nonzero() {
let state = tempfile::tempdir().unwrap();
assert!(genesis(state.path()).status.success());
let responder = Responder::refusing(500);
let output = run(state.path(), &responder, "2", "1000000");
assert!(!output.status.success());
let text = stdout(&output);
assert!(text.contains("tick 0 open: "), "{text}");
assert!(
text.ends_with("status: Failed (inference_recovery_required); 0 of 2 ticks closed\n"),
"{text}"
);
assert_eq!(
responder.served.load(Ordering::SeqCst),
1,
"the run stopped at the first refusal"
);
}
#[test]
fn the_command_refuses_what_it_cannot_run_and_never_echoes_a_value() {
let state = tempfile::tempdir().unwrap();
let responder = Responder::start();
// No world yet.
let output = run(state.path(), &responder, "1", "1000");
assert!(!output.status.success());
assert!(stderr(&output).contains("run genesis first"), "{}", stderr(&output));
assert!(genesis(state.path()).status.success());
// A second genesis does not overwrite the first.
assert!(!genesis(state.path()).status.success());
let secret = "sk-not-a-real-key-0000";
let key = state.path().join(secret);
let cases: [(Vec<&str>, &str); 9] = [
(vec![], "usage"),
(vec!["fly"], "unknown command"),
(
vec!["run", "--state", state.path().to_str().unwrap(), "--ticks", "0"],
"--token-cap is required",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "many",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
"--base-url", "http://127.0.0.1:1",
],
"--ticks is not a positive integer",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "0",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
"--base-url", "http://127.0.0.1:1",
],
"--ticks is not a positive integer",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
"--token-cap", "0", "--tick-span-minutes", "60", "--model", "local/x",
"--base-url", "http://127.0.0.1:1",
],
"--token-cap is not a positive integer",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "gpt-4",
"--base-url", "http://127.0.0.1:1",
],
"--model names no inference lane",
),
(
// A hosted model needs its key file; a missing one is named by flag.
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "hosted/x",
"--base-url", "https://api.example.test", "--key-file", key.to_str().unwrap(),
],
"--key-file is unreadable",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
"--base-url", "http://127.0.0.1:1", "--key-file", key.to_str().unwrap(),
],
"a local model takes no --key-file",
),
];
for (arguments, expected) in cases {
let output = verse(&arguments);
assert!(!output.status.success(), "{arguments:?} succeeded");
let error = stderr(&output);
assert!(error.contains(expected), "{arguments:?}: {error}");
assert!(!error.contains(secret), "{arguments:?} echoed a path: {error}");
assert!(!error.contains("many"), "{arguments:?} echoed a value: {error}");
}
}
#[test]
fn a_non_loopback_local_endpoint_is_refused_without_echoing_it() {
let state = tempfile::tempdir().unwrap();
assert!(genesis(state.path()).status.success());
let output = verse(&[
"run",
"--state",
state.path().to_str().unwrap(),
"--ticks",
"1",
"--token-cap",
"1000",
"--tick-span-minutes",
"60",
"--model",
"local/x",
"--base-url",
"http://10.77.0.99:4242",
]);
assert!(!output.status.success());
let error = stderr(&output);
assert!(error.contains("--base-url"), "{error}");
assert!(!error.contains("10.77.0.99"), "the endpoint was echoed: {error}");
// The lane failed before any run was claimed.
assert!(!stdout(&output).contains("run 1"), "{}", stdout(&output));
}
/// A start refused after its claim ends the claimed record Failed, so the run
/// binds nothing. Reached from the command by removing the run records while
/// the call ledger still holds run 1 under another cap.
#[test]
fn a_start_the_ledger_refuses_ends_its_claimed_record_failed() {
let parent = tempfile::tempdir().unwrap();
let state = parent.path().join("state");
std::fs::create_dir_all(&state).unwrap();
assert!(genesis(&state).status.success());
let responder = Responder::start();
let first = run(&state, &responder, "1", "1000000");
assert!(first.status.success(), "{}", stderr(&first));
std::fs::remove_file(state.join("runs.cc")).unwrap();
let refused = run(&state, &responder, "1", "500000");
assert!(!refused.status.success());
let world = {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let _entered = runtime.enter();
let (mailbox, task) = ghostlight::WorldMailbox::open(state.join("world.cc")).unwrap();
let world = runtime.block_on(mailbox.snapshot()).unwrap().world_id;
drop(mailbox);
runtime.block_on(task).unwrap();
world
};
let runs = ghostlight::VerseRunStore::open(state.join("runs.cc"))
.unwrap()
.runs(world)
.unwrap();
assert_eq!(runs.len(), 1);
assert_eq!(
runs[0].status,
ghostlight::RunStatus::Failed {
reason: "start_refused".into()
}
);
}
/// A store that cannot open names the flag and the fault, never the path.
#[test]
fn a_store_that_cannot_open_never_echoes_the_state_path() {
let responder = Responder::start();
for file in ["world.cc", "controller-work.cc"] {
for held in [false, true] {
let parent = tempfile::tempdir().unwrap();
let state = parent.path().join("distinctivestatename");
std::fs::create_dir_all(&state).unwrap();
assert!(genesis(&state).status.success());
let first = run(&state, &responder, "1", "1000000");
assert!(first.status.success(), "{}", stderr(&first));
let target = state.join(file);
let _guard: Box<dyn std::any::Any> = if !held {
std::fs::write(&target, b"not a database").unwrap();
Box::new(())
} else if file == "world.cc" {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let entered = runtime.enter();
let opened = ghostlight::WorldMailbox::open(&target).unwrap();
drop(entered);
Box::new((runtime, opened))
} else {
Box::new(ghostlight::open_controller_work(&target).unwrap())
};
let output = run(&state, &responder, "1", "1000000");
assert!(!output.status.success(), "{file} held={held}");
let error = stderr(&output);
assert!(error.contains("--state"), "{file} held={held}: {error}");
assert!(
!error.contains("distinctivestatename"),
"{file} held={held} echoed the path: {error}"
);
}
}
}

View file

@ -1,34 +0,0 @@
[package]
name = "ghostlight"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
async-trait.workspace = true
chrono.workspace = true
model-connector.workspace = true
cultcache-rs.workspace = true
ghostlight-persona-projection = { path = "../ghostlight-persona-projection" }
reqwest.workspace = true
rmp-serde.workspace = true
rmpv = "1.3"
serde.workspace = true
serde_bytes = "0.11"
serde_json.workspace = true
sha2.workspace = true
thiserror.workspace = true
tokio.workspace = true
tracing.workspace = true
unicode-normalization = "0.1.25"
unicode-properties = "0.1.4"
uuid.workspace = true
zeroize.workspace = true
[features]
# Exposes `open_local_port_with_timeout` to a consumer's tests. Production
# builds never enable it.
test-support = []
[dev-dependencies]
tempfile = "3"

File diff suppressed because it is too large Load diff

View file

@ -1,297 +0,0 @@
//! Aetheria's catalog file, read once into the two things Ghostlight takes from
//! it: the verse grammar, as a `GrammarBinding`, and the factions, as records
//! keyed for import.
//!
//! The catalog is Aetheria's: this reader opens it read-only and never writes
//! it, and it ignores every schema it does not mirror. The mirrors below decode
//! `aetheria.verse_grammar` v1, `aetheria.verse_verb` v1 and `aetheria.faction`
//! v1 by integer key: a MessagePack-keyed object is an array indexed by key,
//! nil in the gaps, so a field Aetheria adds later at a higher key is ignored
//! and a field it drops is an error naming the record and the key. A record
//! that does not decode, an enum value outside the mirror and a verb that
//! breaks the grammar's name or role rules are errors, never skipped rows.
use crate::ImportKey;
use crate::grammar::{
GrammarBinding, GrammarError, GrammarReferentKind, GrammarRole, GrammarVerb, RenderPath,
};
use cultcache_rs::SingleFileMessagePackBackingStore;
use rmpv::Value;
use std::collections::BTreeMap;
use std::path::Path;
const GRAMMAR_SCHEMA: &str = "aetheria.verse_grammar";
const VERB_SCHEMA: &str = "aetheria.verse_verb";
const FACTION_SCHEMA: &str = "aetheria.faction";
const VERB_NAME_MAX: usize = 48;
const ROLE_NAME_MAX: usize = 32;
/// The invoking subject, never a role.
const ACTOR_ROLE: &str = "actor";
/// What Ghostlight takes from Aetheria's catalog.
#[derive(Clone, Debug, PartialEq)]
pub struct AetheriaCatalog {
pub grammar: GrammarBinding,
/// In record-key order.
pub factions: Vec<AetheriaFaction>,
}
/// One `aetheria.faction` record. `allegiance` is carried and read by no
/// consumer yet.
#[derive(Clone, Debug, PartialEq)]
pub struct AetheriaFaction {
pub key: ImportKey,
pub name: String,
pub short_name: String,
pub description: String,
pub allegiance: BTreeMap<ImportKey, f32>,
}
/// Which of the grammar's name or role rules a verb broke.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum VerbRule {
#[error("verb name is not canonical")]
Name,
#[error("role name is not canonical")]
RoleName,
#[error("role name is reserved for the invoking subject")]
ReservedRole,
#[error("role name is declared twice")]
DuplicateRole,
}
/// Why a catalog could not be read. Records are named by record key and fields
/// by integer key; no error carries a value the catalog held.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum CatalogReadError {
#[error("the catalog file cannot be read")]
Unreadable,
#[error("the catalog holds no aetheria.verse_grammar global")]
NoGrammar,
#[error("the catalog holds more than one aetheria.verse_grammar record")]
MultipleGrammars,
#[error("record {record:?} field {field} is missing or not the mirrored type")]
MalformedRecord { record: String, field: u8 },
#[error("record {record:?} field {field} is not a canonical import key")]
NonCanonicalKey { record: String, field: u8 },
#[error("record {record:?} is a second aetheria.faction under one record key")]
DuplicateFaction { record: String },
#[error("record {record:?} field {field} is not a known render path")]
UnknownRenderPath { record: String, field: u8 },
#[error("record {record:?} field {field} is not a known referent kind")]
UnknownReferentKind { record: String, field: u8 },
#[error("verb record {record:?} breaks a grammar rule: {rule}")]
InvalidVerb { record: String, rule: VerbRule },
#[error("the verbs do not bind a grammar: {0}")]
Grammar(#[from] GrammarError),
}
/// Reads the catalog at `path` without writing it. An absent file is
/// `Unreadable`, not an empty catalog.
pub fn read_aetheria_catalog(path: impl AsRef<Path>) -> Result<AetheriaCatalog, CatalogReadError> {
let path = path.as_ref();
std::fs::metadata(path).map_err(|_| CatalogReadError::Unreadable)?;
let mut rows = SingleFileMessagePackBackingStore::new(path)
.pull_all_read_only_snapshot()
.map_err(|_| CatalogReadError::Unreadable)?;
rows.sort_by(|a, b| a.key.cmp(&b.key));
let mut revision = None;
let mut verbs = Vec::new();
let mut factions = Vec::new();
for row in &rows {
match row.r#type.as_str() {
GRAMMAR_SCHEMA => {
if revision.is_some() {
return Err(CatalogReadError::MultipleGrammars);
}
let cells = Cells::of(&row.key, &row.payload)?;
revision = Some(u32::try_from(cells.int(1)?).map_err(|_| cells.malformed(1))?);
}
VERB_SCHEMA => verbs.push(read_verb(&Cells::of(&row.key, &row.payload)?)?),
FACTION_SCHEMA => {
let faction = read_faction(&row.key, &Cells::of(&row.key, &row.payload)?)?;
if factions
.last()
.is_some_and(|seen: &AetheriaFaction| seen.key == faction.key)
{
return Err(CatalogReadError::DuplicateFaction {
record: row.key.clone(),
});
}
factions.push(faction);
}
_ => {}
}
}
let revision = revision.ok_or(CatalogReadError::NoGrammar)?;
Ok(AetheriaCatalog {
grammar: GrammarBinding::new(GRAMMAR_SCHEMA, revision, verbs)?,
factions,
})
}
/// A record's payload: the positional array of its keyed fields.
struct Cells<'a> {
record: &'a str,
cells: Vec<Value>,
}
impl<'a> Cells<'a> {
fn of(record: &'a str, payload: &[u8]) -> Result<Self, CatalogReadError> {
let mut payload = payload;
match rmpv::decode::read_value(&mut payload) {
Ok(Value::Array(cells)) => Ok(Self { record, cells }),
_ => Err(CatalogReadError::MalformedRecord {
record: record.to_owned(),
field: 0,
}),
}
}
fn malformed(&self, field: u8) -> CatalogReadError {
CatalogReadError::MalformedRecord {
record: self.record.to_owned(),
field,
}
}
fn non_canonical(&self, field: u8) -> CatalogReadError {
CatalogReadError::NonCanonicalKey {
record: self.record.to_owned(),
field,
}
}
fn cell(&self, field: u8) -> Result<&Value, CatalogReadError> {
self.cells
.get(usize::from(field))
.ok_or_else(|| self.malformed(field))
}
fn int(&self, field: u8) -> Result<i64, CatalogReadError> {
self.cell(field)?
.as_i64()
.ok_or_else(|| self.malformed(field))
}
fn text(&self, field: u8) -> Result<String, CatalogReadError> {
self.cell(field)?
.as_str()
.map(str::to_owned)
.ok_or_else(|| self.malformed(field))
}
/// A string Aetheria may leave null; null reads as empty.
fn text_or_empty(&self, field: u8) -> Result<String, CatalogReadError> {
match self.cell(field)? {
Value::Nil => Ok(String::new()),
Value::String(text) => text
.as_str()
.map(str::to_owned)
.ok_or_else(|| self.malformed(field)),
_ => Err(self.malformed(field)),
}
}
fn array(&self, field: u8) -> Result<&Vec<Value>, CatalogReadError> {
self.cell(field)?
.as_array()
.ok_or_else(|| self.malformed(field))
}
}
fn read_verb(cells: &Cells) -> Result<(String, GrammarVerb), CatalogReadError> {
let invalid = |rule| CatalogReadError::InvalidVerb {
record: cells.record.to_owned(),
rule,
};
let name = cells.text(1)?;
if !canonical_name(&name, VERB_NAME_MAX) {
return Err(invalid(VerbRule::Name));
}
let render_path = match cells.int(2)? {
1 => RenderPath::ShipAction,
2 => RenderPath::Conversation,
_ => {
return Err(CatalogReadError::UnknownRenderPath {
record: cells.record.to_owned(),
field: 2,
});
}
};
let mut roles: Vec<GrammarRole> = Vec::new();
for role in cells.array(3)? {
let role = Cells {
record: cells.record,
cells: role.as_array().cloned().ok_or_else(|| cells.malformed(3))?,
};
let role_name = role.text(1).map_err(|_| cells.malformed(3))?;
if !canonical_name(&role_name, ROLE_NAME_MAX) {
return Err(invalid(VerbRule::RoleName));
}
if role_name == ACTOR_ROLE {
return Err(invalid(VerbRule::ReservedRole));
}
if roles.iter().any(|seen| seen.role == role_name) {
return Err(invalid(VerbRule::DuplicateRole));
}
let referent = match role.int(2).map_err(|_| cells.malformed(3))? {
1 => GrammarReferentKind::Person,
2 => GrammarReferentKind::Faction,
3 => GrammarReferentKind::Population,
4 => GrammarReferentKind::Place,
5 => GrammarReferentKind::Cargo,
_ => {
return Err(CatalogReadError::UnknownReferentKind {
record: cells.record.to_owned(),
field: 3,
});
}
};
roles.push(GrammarRole {
role: role_name,
referent,
});
}
Ok((name, GrammarVerb { render_path, roles }))
}
/// A lower-case letter, then lower-case letters, digits and underscores.
fn canonical_name(name: &str, max_len: usize) -> bool {
let mut chars = name.chars();
name.len() <= max_len
&& chars.next().is_some_and(|c| c.is_ascii_lowercase())
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
fn read_faction(key: &str, cells: &Cells) -> Result<AetheriaFaction, CatalogReadError> {
let own = ImportKey::new(FACTION_SCHEMA, key);
if !own.is_canonical() {
return Err(cells.non_canonical(0));
}
let Some(allegiance) = cells.cell(12)?.as_map() else {
return Err(cells.malformed(12));
};
let mut standing = BTreeMap::new();
for (other, weight) in allegiance {
let other = other.as_str().ok_or_else(|| cells.malformed(12))?;
let weight = weight.as_f64().ok_or_else(|| cells.malformed(12))?;
let other = ImportKey::new(FACTION_SCHEMA, other);
if !other.is_canonical() {
return Err(cells.non_canonical(12));
}
standing.insert(other, weight as f32);
}
Ok(AetheriaFaction {
key: own,
name: cells.text(1)?,
short_name: cells.text_or_empty(2)?,
description: cells.text_or_empty(3)?,
allegiance: standing,
})
}
#[cfg(test)]
mod tests;

View file

@ -1,589 +0,0 @@
use super::*;
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope};
use serde_json::{Value, json};
/// Written by Aetheria's own fixture writer (`VerseGrammarTests.WriteFixture`)
/// at Aetheria master 92b82e9a; never edited. See `tests/fixtures/aetheria-verse-catalog.provenance.txt`.
const FIXTURE: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/aetheria-verse-catalog.cc"
);
fn fixture_rows() -> Vec<CultCacheEnvelope> {
SingleFileMessagePackBackingStore::new(FIXTURE)
.pull_all_read_only_snapshot()
.unwrap()
}
fn row_of<'a>(rows: &'a mut [CultCacheEnvelope], key: &str) -> &'a mut CultCacheEnvelope {
rows.iter_mut().find(|row| row.key == key).unwrap()
}
/// Re-encodes one record's positional payload after `edit`.
fn edit(rows: &mut [CultCacheEnvelope], key: &str, change: impl FnOnce(&mut Vec<Value>)) {
let row = row_of(rows, key);
let Value::Array(mut cells) = rmp_serde::from_slice(&row.payload).unwrap() else {
panic!("{key} is not a positional record");
};
change(&mut cells);
row.payload = rmp_serde::to_vec(&Value::Array(cells)).unwrap();
}
fn catalog_of(rows: &[CultCacheEnvelope]) -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("catalog.cc");
let mut store = SingleFileMessagePackBackingStore::new(&path);
for row in rows {
store.push(row).unwrap();
}
(dir, path)
}
fn read(rows: &[CultCacheEnvelope]) -> Result<AetheriaCatalog, CatalogReadError> {
let (_dir, path) = catalog_of(rows);
read_aetheria_catalog(&path)
}
fn verb(path: RenderPath, roles: &[(&str, GrammarReferentKind)]) -> GrammarVerb {
GrammarVerb {
render_path: path,
roles: roles
.iter()
.map(|(role, referent)| GrammarRole {
role: (*role).into(),
referent: *referent,
})
.collect(),
}
}
/// What Aetheria's fixture writer authored, spelled out by hand.
fn authored_verbs() -> Vec<(String, GrammarVerb)> {
vec![
(
"haul".into(),
verb(
RenderPath::ShipAction,
&[
("cargo", GrammarReferentKind::Cargo),
("destination", GrammarReferentKind::Place),
],
),
),
(
"attack".into(),
verb(
RenderPath::ShipAction,
&[("target", GrammarReferentKind::Faction)],
),
),
("speak".into(), verb(RenderPath::Conversation, &[])),
]
}
fn faction_key(record: &str) -> ImportKey {
ImportKey::new("aetheria.faction", record)
}
#[test]
fn reads_the_aetheria_written_fixture() {
let catalog = read_aetheria_catalog(FIXTURE).unwrap();
let identity = catalog.grammar.identity();
assert_eq!(identity.schema_id, "aetheria.verse_grammar");
assert_eq!(identity.revision, 1);
for (kind, expected) in authored_verbs() {
assert_eq!(catalog.grammar.verb(&kind), Some(&expected), "{kind}");
}
assert!(catalog.grammar.verb("mine").is_none());
assert_eq!(
catalog.factions,
vec![
AetheriaFaction {
key: faction_key("faction-adrasteia"),
name: "Adrasteia".into(),
short_name: "ADR".into(),
description: "First.".into(),
allegiance: BTreeMap::from([(faction_key("faction-brannoch"), 0.75)]),
},
AetheriaFaction {
key: faction_key("faction-brannoch"),
name: "Brannoch".into(),
short_name: "BRN".into(),
description: "Second.".into(),
allegiance: BTreeMap::from([(faction_key("faction-adrasteia"), 0.25)]),
},
]
);
}
#[test]
fn grammar_digest_matches_a_binding_built_by_hand() {
let by_hand = GrammarBinding::new("aetheria.verse_grammar", 1, authored_verbs()).unwrap();
let read = read_aetheria_catalog(FIXTURE).unwrap().grammar;
assert_eq!(read.identity().digest, by_hand.identity().digest);
assert_eq!(read, by_hand);
// The digest follows the verbs: a role the file drops is a different grammar.
let mut rows = fixture_rows();
edit(&mut rows, "verb-haul", |cells| {
cells[3].as_array_mut().unwrap().pop();
});
assert_ne!(
read_catalog_digest(&rows),
by_hand.identity().digest,
"dropping a role did not move the digest"
);
}
fn read_catalog_digest(rows: &[CultCacheEnvelope]) -> String {
read(rows).unwrap().grammar.identity().digest
}
#[test]
fn refuses_a_catalog_without_a_grammar() {
let mut rows = fixture_rows();
rows.retain(|row| row.r#type != "aetheria.verse_grammar");
assert_eq!(read(&rows), Err(CatalogReadError::NoGrammar));
}
#[test]
fn refuses_a_second_grammar_record() {
let mut rows = fixture_rows();
let mut second = rows
.iter()
.find(|row| row.r#type == "aetheria.verse_grammar")
.unwrap()
.clone();
second.key.push_str("-again");
rows.push(second);
assert_eq!(read(&rows), Err(CatalogReadError::MultipleGrammars));
}
#[test]
fn refuses_an_unknown_render_path() {
let mut rows = fixture_rows();
edit(&mut rows, "verb-haul", |cells| cells[2] = json!(3));
let error = read(&rows).unwrap_err();
assert_eq!(
error,
CatalogReadError::UnknownRenderPath {
record: "verb-haul".into(),
field: 2
}
);
assert!(!error.to_string().contains('3'), "the value was echoed");
}
#[test]
fn refuses_an_unknown_referent_kind() {
let mut rows = fixture_rows();
edit(&mut rows, "verb-attack", |cells| {
cells[3][0][2] = json!(9);
});
assert_eq!(
read(&rows),
Err(CatalogReadError::UnknownReferentKind {
record: "verb-attack".into(),
field: 3
})
);
}
#[test]
fn a_verb_breaking_the_name_or_role_rules_is_refused_by_key() {
let broken = |mutate: fn(&mut Vec<Value>)| {
let mut rows = fixture_rows();
edit(&mut rows, "verb-haul", mutate);
read(&rows).unwrap_err()
};
let invalid = |rule| CatalogReadError::InvalidVerb {
record: "verb-haul".into(),
rule,
};
assert_eq!(
broken(|cells| cells[1] = json!("Haul")),
invalid(VerbRule::Name)
);
assert_eq!(
broken(|cells| cells[1] = json!("1haul")),
invalid(VerbRule::Name)
);
assert_eq!(
broken(|cells| cells[1] = json!("")),
invalid(VerbRule::Name)
);
assert_eq!(
broken(|cells| cells[1] = json!("h".repeat(49))),
invalid(VerbRule::Name)
);
assert_eq!(
broken(|cells| cells[3][0][1] = json!("Cargo")),
invalid(VerbRule::RoleName)
);
assert_eq!(
broken(|cells| cells[3][0][1] = json!("c".repeat(33))),
invalid(VerbRule::RoleName)
);
assert_eq!(
broken(|cells| cells[3][0][1] = json!("actor")),
invalid(VerbRule::ReservedRole)
);
assert_eq!(
broken(|cells| cells[3][1][1] = json!("cargo")),
invalid(VerbRule::DuplicateRole)
);
}
#[test]
fn the_longest_canonical_names_are_admitted() {
let mut rows = fixture_rows();
edit(&mut rows, "verb-haul", |cells| {
cells[1] = json!(format!("h{}9", "_9".repeat(23)));
cells[3][0][1] = json!(format!("c{}", "z".repeat(31)));
});
let catalog = read(&rows).unwrap();
assert_eq!(catalog.grammar.identity().revision, 1);
}
#[test]
fn two_verbs_with_one_name_do_not_bind() {
let mut rows = fixture_rows();
edit(&mut rows, "verb-haul", |cells| cells[1] = json!("attack"));
assert_eq!(
read(&rows),
Err(CatalogReadError::Grammar(GrammarError::DuplicateVerb))
);
}
#[test]
fn a_record_that_is_not_the_mirrored_shape_is_named_by_key_and_field() {
let malformed = |record: &str, field| CatalogReadError::MalformedRecord {
record: record.into(),
field,
};
let mut rows = fixture_rows();
row_of(&mut rows, "faction-brannoch").payload =
rmp_serde::to_vec(&json!("not an array")).unwrap();
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 0)));
let mut rows = fixture_rows();
edit(&mut rows, "faction-brannoch", |cells| {
cells[1] = Value::Null
});
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 1)));
let mut rows = fixture_rows();
edit(&mut rows, "faction-brannoch", |cells| {
cells[12] = json!({"faction-adrasteia": "heavy"});
});
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 12)));
let mut rows = fixture_rows();
edit(&mut rows, "faction-brannoch", |cells| cells.truncate(12));
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 12)));
let mut rows = fixture_rows();
let grammar = rows
.iter()
.find(|row| row.r#type == "aetheria.verse_grammar")
.unwrap()
.key
.clone();
edit(&mut rows, &grammar, |cells| cells[1] = json!(-1));
assert_eq!(read(&rows), Err(malformed(&grammar, 1)));
}
#[test]
fn fields_aetheria_adds_and_schemas_it_does_not_mirror_are_ignored() {
let mut rows = fixture_rows();
edit(&mut rows, "verb-speak", |cells| cells.push(json!("later")));
edit(&mut rows, "faction-adrasteia", |cells| cells.push(json!(7)));
let mut stranger = rows[0].clone();
stranger.key = "ship-1".into();
stranger.r#type = "aetheria.ship".into();
stranger.schema_id = Some("sha256:not-mirrored".into());
stranger.payload = vec![0xc1];
rows.push(stranger);
assert_eq!(
read(&rows).unwrap(),
read_aetheria_catalog(FIXTURE).unwrap()
);
}
#[test]
fn a_null_short_name_or_description_reads_as_empty() {
let mut rows = fixture_rows();
edit(&mut rows, "faction-adrasteia", |cells| {
cells[2] = Value::Null;
cells[3] = Value::Null;
});
let catalog = read(&rows).unwrap();
assert_eq!(catalog.factions[0].short_name, "");
assert_eq!(catalog.factions[0].description, "");
}
#[test]
fn an_absent_file_is_unreadable_not_an_empty_catalog() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(
read_aetheria_catalog(dir.path().join("missing.cc")),
Err(CatalogReadError::Unreadable)
);
}
#[test]
fn reading_leaves_the_catalog_and_its_directory_untouched() {
let (dir, path) = catalog_of(&fixture_rows());
let bytes = std::fs::read(&path).unwrap();
let listing = |dir: &std::path::Path| {
let mut names: Vec<_> = std::fs::read_dir(dir)
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
names.sort();
names
};
let before = listing(dir.path());
read_aetheria_catalog(&path).unwrap();
read_aetheria_catalog(&path).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), bytes);
assert_eq!(listing(dir.path()), before, "the reader created a file");
}
#[test]
fn every_referent_code_maps_to_its_own_kind() {
// The fixture binds only Faction, Cargo and Place; Person and Population
// are authored here at the role's integer key, each read back as itself.
for (code, expected) in [
(1, GrammarReferentKind::Person),
(2, GrammarReferentKind::Faction),
(3, GrammarReferentKind::Population),
(4, GrammarReferentKind::Place),
(5, GrammarReferentKind::Cargo),
] {
let mut rows = fixture_rows();
edit(&mut rows, "verb-attack", |cells| {
cells[3][0][2] = json!(code)
});
let catalog = read(&rows).unwrap();
assert_eq!(
catalog.grammar.verb("attack"),
Some(&verb(RenderPath::ShipAction, &[("target", expected)])),
"code {code}"
);
}
}
fn faction_with_key(record: &str) -> Vec<CultCacheEnvelope> {
let mut rows = fixture_rows();
row_of(&mut rows, "faction-brannoch").key = record.into();
rows
}
#[test]
fn a_faction_record_key_that_is_not_canonical_text_is_refused_by_key_and_field() {
for bad in [
"faction-cafe\u{301}",
"faction-brannoch ",
"faction-\u{202e}brannoch",
"",
] {
assert_eq!(
read(&faction_with_key(bad)),
Err(CatalogReadError::NonCanonicalKey {
record: bad.into(),
field: 0
}),
"{bad:?}"
);
}
}
#[test]
fn an_allegiance_key_that_is_not_canonical_text_is_refused_by_key_and_field() {
for bad in ["faction-cafe\u{301}", "faction-adrasteia ", "\u{202e}"] {
let mut rows = fixture_rows();
edit(&mut rows, "faction-brannoch", |cells| {
cells[12] = json!({ bad: 0.5 });
});
assert_eq!(
read(&rows),
Err(CatalogReadError::NonCanonicalKey {
record: "faction-brannoch".into(),
field: 12
}),
"{bad:?}"
);
}
}
/// The fixture's snapshot bytes with the record rows changed by `change`, for
/// what the store's own writer will not produce: it keeps one row per record
/// key and stores rows in key order.
fn spliced_catalog(
change: impl FnOnce(&mut Vec<rmpv::Value>),
) -> (tempfile::TempDir, std::path::PathBuf) {
let bytes = std::fs::read(FIXTURE).unwrap();
let rmpv::Value::Array(mut snapshot) = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap()
else {
panic!("snapshot is not a tuple");
};
let rmpv::Value::Array(records) = &mut snapshot[2] else {
panic!("snapshot holds no records");
};
change(records);
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("catalog.cc");
let mut spliced = Vec::new();
rmpv::encode::write_value(&mut spliced, &rmpv::Value::Array(snapshot)).unwrap();
std::fs::write(&path, spliced).unwrap();
(dir, path)
}
#[test]
fn two_faction_rows_under_one_record_key_are_refused() {
let (_dir, path) = spliced_catalog(|records| {
let twin = records
.iter()
.find(|record| record[0].as_str() == Some("faction-adrasteia"))
.unwrap()
.clone();
records.push(twin);
});
assert_eq!(
read_aetheria_catalog(&path),
Err(CatalogReadError::DuplicateFaction {
record: "faction-adrasteia".into()
})
);
}
#[test]
fn factions_are_read_in_record_key_order_whatever_the_file_order() {
let (_dir, path) = spliced_catalog(|records| {
records.sort_by(|a, b| b[0].as_str().cmp(&a[0].as_str()));
assert_eq!(records[0][0].as_str(), Some("verb-speak"));
});
let names: Vec<_> = read_aetheria_catalog(&path)
.unwrap()
.factions
.into_iter()
.map(|faction| faction.name)
.collect();
assert_eq!(names, ["Adrasteia", "Brannoch"]);
}
#[test]
fn an_allegiance_that_is_not_a_map_is_malformed_not_empty() {
for not_a_map in [
json!([]),
json!(["faction-adrasteia"]),
Value::Null,
json!(1),
] {
let mut rows = fixture_rows();
let shape = not_a_map.clone();
edit(&mut rows, "faction-brannoch", |cells| cells[12] = shape);
assert_eq!(
read(&rows),
Err(CatalogReadError::MalformedRecord {
record: "faction-brannoch".into(),
field: 12
}),
"{not_a_map}"
);
}
}
/// Appends cells to a faction as Aetheria's C# CultCache writes a `byte[]`
/// (MessagePack bin) and a `DateTime` (MessagePack timestamp, ext -1).
#[test]
fn bin_and_ext_fields_aetheria_adds_at_higher_keys_are_ignored() {
let mut rows = fixture_rows();
let row = row_of(&mut rows, "faction-adrasteia");
let rmpv::Value::Array(mut cells) =
rmpv::decode::read_value(&mut row.payload.as_slice()).unwrap()
else {
panic!("not positional");
};
cells.push(rmpv::Value::Binary(vec![1, 0, 7]));
cells.push(rmpv::Value::Ext(
-1,
vec![0, 0, 0, 0, 0x65, 0x1f, 0x2a, 0x80],
));
let mut payload = Vec::new();
rmpv::encode::write_value(&mut payload, &rmpv::Value::Array(cells)).unwrap();
row.payload = payload;
assert_eq!(
read(&rows).unwrap(),
read_aetheria_catalog(FIXTURE).unwrap()
);
}
/// A faction record re-encoded with `change` applied to its decoded cells, for
/// shapes `serde_json` cannot spell: a non-string map key, raw invalid bytes.
fn with_cells(key: &str, change: impl FnOnce(&mut Vec<rmpv::Value>)) -> Vec<CultCacheEnvelope> {
let mut rows = fixture_rows();
let row = row_of(&mut rows, key);
let rmpv::Value::Array(mut cells) =
rmpv::decode::read_value(&mut row.payload.as_slice()).unwrap()
else {
panic!("not positional");
};
change(&mut cells);
let mut payload = Vec::new();
rmpv::encode::write_value(&mut payload, &rmpv::Value::Array(cells)).unwrap();
row.payload = payload;
rows
}
#[test]
fn an_allegiance_key_that_is_not_a_string_is_malformed_by_key_and_field() {
for key in [
rmpv::Value::from(5),
rmpv::Value::Nil,
rmpv::Value::Binary(b"faction-adrasteia".to_vec()),
] {
let rows = with_cells("faction-brannoch", |cells| {
cells[12] = rmpv::Value::Map(vec![(key, rmpv::Value::F64(0.5))]);
});
assert_eq!(
read(&rows),
Err(CatalogReadError::MalformedRecord {
record: "faction-brannoch".into(),
field: 12
})
);
}
}
#[test]
fn text_that_is_not_utf8_is_malformed_by_key_and_field() {
// The marker is overwritten in the encoded bytes with an invalid sequence of
// the same length, since a decoded string cannot hold one.
const MARKER: &str = "ZZZZ";
for field in [1usize, 3] {
let mut rows = with_cells("faction-brannoch", |cells| {
cells[field] = rmpv::Value::from(MARKER);
});
let payload = &mut row_of(&mut rows, "faction-brannoch").payload;
let at = payload
.windows(MARKER.len())
.position(|window| window == MARKER.as_bytes())
.unwrap();
payload[at..at + MARKER.len()].copy_from_slice(&[0xff, 0xfe, 0xfd, 0xfc]);
assert_eq!(
read(&rows),
Err(CatalogReadError::MalformedRecord {
record: "faction-brannoch".into(),
field: field as u8
}),
"field {field}"
);
}
}

View file

@ -1,213 +0,0 @@
//! The world clock and the motion one tick produces.
//!
//! One entry point into the reducer, [`derive_motion`], reached from `reduce`'s
//! `AdvanceTime` arm and from `apply_effect`'s `TimeAdvanced` arm, so a forged
//! tick is re-derived by the same function that produced the honest one. It is
//! pure over `(state, to)`: no wall clock, no entropy, no caller value beyond
//! the span.
use super::patch::{Commitment, CommitmentKey, CommitmentKind, DependencyTarget, MAX_ROUTE_COST};
use super::{PressureMagnitude, PressureSource, SubjectId, WorldState, action, is_retired};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// Minutes since genesis. Monotonic, kernel-owned, world-level. `u64` because a
/// world clock has no bound; `Cost` is `1..=MAX_ROUTE_COST` because it weighs
/// one edge, and reusing it here would put an edge's bound on the world's age.
#[derive(
Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
#[serde(transparent)]
pub struct FictionalMinutes(pub u64);
impl FictionalMinutes {
pub(crate) fn checked_add(self, span: TickMinutes) -> Option<Self> {
self.0.checked_add(u64::from(span.0)).map(Self)
}
/// Minutes elapsed since an earlier reading. Saturating because the caller
/// is the attention order, which reads a stamp `verify_state_shape` already
/// holds to `<= now`.
pub(crate) fn since(self, earlier: Self) -> u64 {
self.0.saturating_sub(earlier.0)
}
}
/// The span one `AdvanceTime` names. Constructor-checked `1..=MAX_ROUTE_COST`
/// (one year of minutes), reusing pass 2's constant as a span bound rather than
/// an edge bound: an unbounded span lets one command jump the clock past every
/// due date in the world and makes the size of a commit a caller-chosen number.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub struct TickMinutes(u32);
impl TickMinutes {
pub fn new(minutes: u32) -> Option<Self> {
(1..=MAX_ROUTE_COST)
.contains(&minutes)
.then_some(Self(minutes))
}
pub fn minutes(self) -> u32 {
self.0
}
}
/// Everything one tick moves, stated as outcomes rather than deltas so the
/// effect says what the world became.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub(crate) struct Motion {
/// Routines that fulfilled, in `(subject, key)` order.
pub(crate) fulfilled: Vec<RoutineFulfilled>,
/// Pressure rows written, in `(target, source)` order, with the resulting
/// magnitude — not the delta.
pub(crate) pressed: Vec<PressureWritten>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub(crate) struct RoutineFulfilled {
pub(crate) subject: SubjectId,
pub(crate) key: CommitmentKey,
pub(crate) next_due: FictionalMinutes,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub(crate) struct PressureWritten {
pub(crate) target: SubjectId,
pub(crate) source: PressureSource,
pub(crate) magnitude: PressureMagnitude,
}
/// The whole magnitude policy, in one place, with no per-world tuning. A
/// blocked routine raises none at all: it retries on the next tick, which is
/// what keeps an unattended subject free of spurious pressure.
mod step {
pub(super) const OBLIGATION_PAST_DUE: u32 = 1;
pub(super) const GOAL_PAST_DUE: u32 = 1;
pub(super) const DEPENDENCY_UNAVAILABLE: u32 = 1;
}
/// Three stages, each reading only committed `state` and `to`. No stage sees
/// another stage's writes, which is what makes this a one-pass total function
/// with no ordering hazard and no partial state to reason about.
///
/// Pressure accrues per command, not per minute: one thousand one-minute ticks
/// and one thousand-minute tick over the same span produce different
/// magnitudes. The kernel stays an exact function of the command sequence, and
/// the tick cadence is one operational constant in `runtime.rs`.
pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion {
let mut fulfilled = Vec::new();
let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new();
for (subject, held) in &state.commitments {
// A retired subject cannot act, and neither fulfilling a routine nor
// pressing an obligation or goal is anything but that subject acting:
// its commitments stay in history, un-discharged and un-deleted, but
// the clock stops moving them the moment they are its.
if is_retired(state, *subject) {
continue;
}
for (key, commitment) in held {
if commitment.due > to {
continue;
}
match commitment.kind {
CommitmentKind::Routine => {
if let Some(next_due) = routine_rolls(state, *subject, commitment) {
fulfilled.push(RoutineFulfilled {
subject: *subject,
key: *key,
next_due,
});
}
}
CommitmentKind::Obligation | CommitmentKind::Goal => {
let step = if commitment.kind == CommitmentKind::Obligation {
step::OBLIGATION_PAST_DUE
} else {
step::GOAL_PAST_DUE
};
let source = PressureSource::Commitment {
subject: *subject,
key: *key,
};
*pressed.entry((*subject, source)).or_default() += step;
}
}
}
}
for (subject, targets) in &state.dependencies {
if is_retired(state, *subject) {
continue;
}
for target in targets {
if dependency_unavailable(state, *subject, *target) {
let source = PressureSource::Dependency(*target);
*pressed.entry((*subject, source)).or_default() += step::DEPENDENCY_UNAVAILABLE;
}
}
}
Motion {
fulfilled,
pressed: pressed
.into_iter()
.map(|((target, source), step)| PressureWritten {
target,
source,
magnitude: PressureMagnitude(
state
.pressures
.get(&target)
.and_then(|held| held.get(&source))
.map_or(0, |magnitude| magnitude.0)
.saturating_add(step),
),
})
.collect(),
}
}
/// A routine fulfils when every one of its checks holds, and its `due` then
/// rolls forward by exactly one period per command. Catch-up arithmetic would
/// make the number of fulfilments a function of the operator's tick cadence in
/// a second place; one roll converges over subsequent ticks.
fn routine_rolls(
state: &WorldState,
subject: SubjectId,
commitment: &Commitment,
) -> Option<FictionalMinutes> {
if !action::preconditions_hold(state, subject, &commitment.checks).is_empty() {
return None;
}
commitment.due.checked_add(commitment.period?)
}
/// Whether a subject's dependency is currently failing it. A closed route is a
/// supply failure; an unusable one is a permission question, and reading
/// authority here would drag `effective_authority` into every tick for every
/// dependency in the world.
pub(super) fn dependency_unavailable(
state: &WorldState,
subject: SubjectId,
target: DependencyTarget,
) -> bool {
match target {
DependencyTarget::Route(edge_id) => !state
.edges
.get(&edge_id)
.is_some_and(super::EdgeRecord::is_open),
// Absence is zero, per pass 3: the depender holds none of what it
// depends on.
DependencyTarget::Resource(entity_id) => !state
.holdings
.get(&subject)
.is_some_and(|held| held.contains_key(&entity_id)),
// The subject it depends on is nowhere in the world's topology.
DependencyTarget::Subject(other) => !state.positions.contains_key(&other),
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,209 +0,0 @@
//! The action grammar a world is bound to at creation.
//!
//! A grammar is the closed set of affordance kinds a world may declare, each
//! with its role signature and the one render path its acts take. The grammar's
//! home is the Aetheria repo; the kernel holds only this binding: the verbs it
//! enforces, and a content digest that names exactly which grammar that was.
//! The digest is derived here and nowhere else, so a binding cannot claim a
//! digest its verbs do not have.
use crate::SubjectKind;
use crate::patch::{AffordanceKindName, EntityKind, RefKind, Role, RoleSpec, kernel_speak_entry};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
/// How an act of one verb reaches the player: filmed in the engine as a ship
/// action, or shown as Aetheria's portrait-and-choices conversation.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum RenderPath {
ShipAction,
Conversation,
}
/// What a grammar role may be bound to, in the grammar's own vocabulary. Each
/// lowers to exactly one kernel `RefKind`.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum GrammarReferentKind {
Person,
Faction,
Population,
Place,
Cargo,
}
impl GrammarReferentKind {
fn ref_kind(self) -> RefKind {
match self {
Self::Person => RefKind::Subject(Some(SubjectKind::Person)),
Self::Faction => RefKind::Subject(Some(SubjectKind::Institution)),
Self::Population => RefKind::Subject(Some(SubjectKind::Population)),
Self::Place => RefKind::Entity(EntityKind::Place),
Self::Cargo => RefKind::Entity(EntityKind::Resource),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct GrammarRole {
pub role: String,
pub referent: GrammarReferentKind,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct GrammarVerb {
pub render_path: RenderPath,
/// In signature order: the order is part of the verb.
pub roles: Vec<GrammarRole>,
}
impl GrammarVerb {
/// Whether a declared role list is this verb's signature: same names, same
/// referent kinds, same order.
pub(crate) fn admits_roles(&self, roles: &[RoleSpec]) -> bool {
self.role_specs() == roles
}
/// This verb's signature as the kernel declares it: the one lowering of a
/// grammar role, so declaring a verb and admitting a declaration cannot
/// disagree.
pub(crate) fn role_specs(&self) -> Vec<RoleSpec> {
self.roles
.iter()
.map(|role| RoleSpec {
role: Role(role.role.clone()),
kind: role.referent.ref_kind(),
})
.collect()
}
}
/// Why a bound grammar refuses an affordance entry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum GrammarRefusal {
KindNotInGrammar,
RolesDisagree,
SpeakNotConversation,
}
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
pub enum GrammarError {
#[error("grammar schema id is empty")]
EmptySchemaId,
#[error("grammar declares one verb kind twice")]
DuplicateVerb,
#[error("grammar digest does not match its verbs")]
DigestMismatch,
}
/// Which grammar a world is bound to: its schema id, revision and content
/// digest. What a consumer reads; the verb table stays in the binding.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GrammarIdentity {
pub schema_id: String,
pub revision: u32,
pub digest: String,
}
/// The grammar a world was created under. Immutable: the only constructor
/// derives the digest, and deserialisation re-derives it and refuses a mismatch.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(try_from = "RawBinding")]
pub struct GrammarBinding {
schema_id: String,
revision: u32,
digest: String,
verbs: BTreeMap<String, GrammarVerb>,
}
#[derive(Deserialize)]
struct RawBinding {
schema_id: String,
revision: u32,
digest: String,
verbs: BTreeMap<String, GrammarVerb>,
}
impl TryFrom<RawBinding> for GrammarBinding {
type Error = GrammarError;
fn try_from(raw: RawBinding) -> Result<Self, GrammarError> {
let bound = Self::new(raw.schema_id, raw.revision, raw.verbs)?;
if bound.digest != raw.digest {
return Err(GrammarError::DigestMismatch);
}
Ok(bound)
}
}
impl GrammarBinding {
/// The one constructor. Verbs arrive in any order and are keyed by kind;
/// the digest is the sha256 of the canonical encoding of the kind-sorted
/// verbs, so the same verbs bind to the same digest however they were listed.
pub fn new(
schema_id: impl Into<String>,
revision: u32,
verbs: impl IntoIterator<Item = (String, GrammarVerb)>,
) -> Result<Self, GrammarError> {
let schema_id = schema_id.into();
if schema_id.is_empty() {
return Err(GrammarError::EmptySchemaId);
}
let mut table = BTreeMap::new();
for (kind, verb) in verbs {
if table.insert(kind, verb).is_some() {
return Err(GrammarError::DuplicateVerb);
}
}
let encoded = rmp_serde::to_vec_named(&table).expect("a verb table encodes");
let digest = format!("sha256:{:x}", Sha256::digest(encoded));
Ok(Self {
schema_id,
revision,
digest,
verbs: table,
})
}
pub fn identity(&self) -> GrammarIdentity {
GrammarIdentity {
schema_id: self.schema_id.clone(),
revision: self.revision,
digest: self.digest.clone(),
}
}
/// Every verb, in kind order.
pub(crate) fn verbs(&self) -> impl Iterator<Item = (&str, &GrammarVerb)> {
self.verbs.iter().map(|(kind, verb)| (kind.as_str(), verb))
}
pub(crate) fn verb(&self, kind: &str) -> Option<&GrammarVerb> {
self.verbs.get(kind)
}
/// The one grammar check. The resolver turns a refusal into a mismatch and
/// `admit_resolved`, the only writer of the affordance catalog, into an
/// invariant error, so no path adds an entry without passing it.
pub(crate) fn refusal(
&self,
kind: &AffordanceKindName,
roles: &[RoleSpec],
) -> Option<GrammarRefusal> {
let Some(verb) = self.verb(&kind.0) else {
return Some(GrammarRefusal::KindNotInGrammar);
};
if !verb.admits_roles(roles) {
return Some(GrammarRefusal::RolesDisagree);
}
if *kind == kernel_speak_entry().kind && verb.render_path != RenderPath::Conversation {
return Some(GrammarRefusal::SpeakNotConversation);
}
None
}
}
#[cfg(test)]
mod tests;

View file

@ -1,745 +0,0 @@
use super::*;
use crate::patch::{
AffordanceDeclaration, AffordanceKindName, AudienceSpec, Declaration, DraftHandle, EntityKind,
Mismatch, OutcomeBand, Precondition, Role, RoleSpec,
};
use crate::tests::{auth_principal, command, creation, owner};
use crate::{
CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, SubmitReceipt,
WorldId, WorldKernel, WorldPatch,
};
fn verb(path: RenderPath, roles: &[(&str, GrammarReferentKind)]) -> GrammarVerb {
GrammarVerb {
render_path: path,
roles: roles
.iter()
.map(|(role, referent)| GrammarRole {
role: (*role).into(),
referent: *referent,
})
.collect(),
}
}
/// What the fixture world's genesis needs: the kernel speak entry and the
/// fixture's own `convene`. Anything else a test wants is added to it.
fn grammar_with(extra: &[(&str, GrammarVerb)]) -> GrammarBinding {
let mut verbs = vec![
("speak".to_owned(), verb(RenderPath::Conversation, &[])),
("convene".to_owned(), verb(RenderPath::Conversation, &[])),
];
verbs.extend(
extra
.iter()
.map(|(kind, v)| ((*kind).to_owned(), v.clone())),
);
GrammarBinding::new("aetheria.grammar", 3, verbs).unwrap()
}
fn bound(grammar: Option<GrammarBinding>, title: &str) -> CreateWorld {
let mut world = creation(CommandId::new(), title);
world.grammar = grammar;
world
}
fn declare(handle: &str, kind: &str, roles: &[(&str, RefKind)]) -> Declaration {
Declaration::Affordance(AffordanceDeclaration {
handle: DraftHandle::new(handle),
kind: AffordanceKindName(kind.into()),
roles: roles
.iter()
.map(|(role, kind)| RoleSpec {
role: Role((*role).into()),
kind: *kind,
})
.collect(),
// Speech with one audience is the smallest entry the resolver does
// not refuse as inert; the grammar check does not read it.
preconditions: vec![Precondition::CanBroadcast {
via: AudienceSpec::Colocated,
}],
effect_slots: Vec::new(),
outcome_bands: vec![OutcomeBand {
weight: 1,
effects: Vec::new(),
}],
carries_speech: true,
})
}
fn patch_of(declarations: Vec<Declaration>) -> WorldPatch {
WorldPatch {
declarations,
operations: Vec::new(),
evidence: Vec::new(),
}
}
fn rejected(result: Result<impl Sized, KernelError>) -> Vec<Mismatch> {
match result {
Err(KernelError::PatchRejected(set)) => set,
Err(other) => panic!("expected a patch refusal, got {other:?}"),
Ok(_) => panic!("expected a patch refusal, the command was admitted"),
}
}
/// Each call gets its own store path: kernels are created, not reopened.
fn create(world: CreateWorld) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) {
let directory = tempfile::tempdir().unwrap();
let result = WorldKernel::create(
directory.path().join("world.cc"),
world,
&auth_principal(owner()),
)
.map(|(kernel, _)| kernel);
(directory, result)
}
fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<SubmitReceipt, KernelError> {
let snapshot = kernel.snapshot().unwrap();
kernel.submit(
command(
&snapshot,
CommandId::new(),
CallerId::Principal(owner()),
CommandBody::AdmitPatch {
answers: None,
patch,
},
),
&auth_principal(owner()),
)
}
fn person() -> RefKind {
RefKind::Subject(Some(SubjectKind::Person))
}
fn place() -> RefKind {
RefKind::Entity(EntityKind::Place)
}
fn not_in_grammar(handle: &str) -> Vec<Mismatch> {
vec![Mismatch::AffordanceKindNotInGrammar {
handle: DraftHandle::new(handle),
}]
}
fn disagrees(handle: &str) -> Vec<Mismatch> {
vec![Mismatch::AffordanceRolesDisagreeWithGrammar {
handle: DraftHandle::new(handle),
}]
}
#[test]
fn grammar_world_refuses_an_affordance_kind_outside_the_grammar() {
// Genesis: a declared kind the binding lacks is refused.
let mut world = bound(Some(grammar_with(&[])), "Outside");
world.patch.declarations.push(declare("wave", "wave", &[]));
assert_eq!(rejected(create(world).1), not_in_grammar("wave"));
// A later AdmitPatch: the same kind is refused, and a verb the grammar
// does carry is admitted by the same path.
let extra = [("hail", verb(RenderPath::Conversation, &[]))];
let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Outside"));
let mut kernel = kernel.unwrap();
assert_eq!(
rejected(admit(
&mut kernel,
patch_of(vec![declare("wave", "wave", &[])])
)),
not_in_grammar("wave")
);
let receipt = admit(&mut kernel, patch_of(vec![declare("hail", "hail", &[])])).unwrap();
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
}
#[test]
fn grammar_world_refuses_a_role_signature_the_grammar_does_not_carry() {
let extra = [
(
"meet",
verb(
RenderPath::ShipAction,
&[
("who", GrammarReferentKind::Person),
("where_", GrammarReferentKind::Place),
],
),
),
("hail", verb(RenderPath::Conversation, &[])),
];
let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Signatures"));
let mut kernel = kernel.unwrap();
for (label, roles) in [
("renamed", vec![("whom", person()), ("where_", place())]),
("rekinded", vec![("who", person()), ("where_", person())]),
("swapped", vec![("where_", place()), ("who", person())]),
("short", vec![("who", person())]),
(
"long",
vec![("who", person()), ("where_", place()), ("why", person())],
),
] {
let set = rejected(admit(
&mut kernel,
patch_of(vec![declare(label, "meet", &roles)]),
));
assert_eq!(set, disagrees(label), "{label}");
}
// A role on a verb the grammar declares with none.
let set = rejected(admit(
&mut kernel,
patch_of(vec![declare("hail", "hail", &[("who", person())])]),
));
assert_eq!(set, disagrees("hail"));
// The exact signature is admitted.
let receipt = admit(
&mut kernel,
patch_of(vec![declare(
"meet",
"meet",
&[("who", person()), ("where_", place())],
)]),
)
.unwrap();
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
}
#[test]
fn each_grammar_referent_kind_admits_exactly_its_own_kernel_kind() {
let kinds = [
(GrammarReferentKind::Person, person()),
(
GrammarReferentKind::Faction,
RefKind::Subject(Some(SubjectKind::Institution)),
),
(
GrammarReferentKind::Population,
RefKind::Subject(Some(SubjectKind::Population)),
),
(GrammarReferentKind::Place, place()),
(
GrammarReferentKind::Cargo,
RefKind::Entity(EntityKind::Resource),
),
];
for (referent, own) in &kinds {
let extra = [("act", verb(RenderPath::ShipAction, &[("with", *referent)]))];
for (_, offered) in &kinds {
let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Referents"));
let mut kernel = kernel.unwrap();
let result = admit(
&mut kernel,
patch_of(vec![declare("act", "act", &[("with", *offered)])]),
);
if offered == own {
assert!(
matches!(result, Ok(SubmitReceipt::Applied(_))),
"{referent:?} refused its own kind"
);
} else {
assert_eq!(
rejected(result),
disagrees("act"),
"{referent:?} admitted {offered:?}"
);
}
}
}
}
#[test]
fn grammar_world_without_speak_refuses_the_kernel_speak_grant() {
let no_speak = GrammarBinding::new(
"aetheria.grammar",
1,
[("convene".to_owned(), verb(RenderPath::Conversation, &[]))],
)
.unwrap();
assert_eq!(
rejected(create(bound(Some(no_speak), "Mute")).1),
not_in_grammar(crate::patch::KERNEL_SPEAK_HANDLE)
);
// The kernel entry is held to the signature as well as the kind.
let loud = GrammarBinding::new(
"aetheria.grammar",
1,
[
(
"speak".to_owned(),
verb(
RenderPath::Conversation,
&[("to", GrammarReferentKind::Person)],
),
),
("convene".to_owned(), verb(RenderPath::Conversation, &[])),
],
)
.unwrap();
assert_eq!(
rejected(create(bound(Some(loud), "Loud")).1),
disagrees(crate::patch::KERNEL_SPEAK_HANDLE)
);
}
#[test]
fn unbound_world_keeps_the_open_catalog() {
let mut world = bound(None, "Open");
world
.patch
.declarations
.push(declare("wave", "wave", &[("at", person())]));
let (_dir, kernel) = create(world);
let mut kernel = kernel.unwrap();
let receipt = admit(
&mut kernel,
patch_of(vec![declare("beacon", "beacon", &[])]),
)
.unwrap();
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
let snapshot = kernel.snapshot().unwrap();
assert!(snapshot.grammar.is_none());
assert!(snapshot.affordances.len() >= 4);
assert!(snapshot.affordances.iter().all(|a| a.render_path.is_none()));
// The state row of a world with no grammar carries no grammar key, so its
// bytes and digests are those of a world written before grammars existed.
let encoded = rmp_serde::to_vec_named(&kernel.state).unwrap();
let keys: std::collections::BTreeMap<String, serde::de::IgnoredAny> =
rmp_serde::from_slice(&encoded).unwrap();
assert!(!keys.contains_key("grammar"));
assert!(keys.contains_key("brief"));
}
#[test]
fn a_bound_world_reports_its_grammar_and_derives_render_paths_from_it() {
let extra = [("dock", verb(RenderPath::ShipAction, &[]))];
let grammar = grammar_with(&extra);
let identity = grammar.identity();
let (_dir, kernel) = create(bound(Some(grammar), "Reports"));
let mut kernel = kernel.unwrap();
admit(&mut kernel, patch_of(vec![declare("dock", "dock", &[])])).unwrap();
let snapshot = kernel.snapshot().unwrap();
assert_eq!(snapshot.grammar, Some(identity));
let path_of = |kind: &str| {
snapshot
.affordances
.iter()
.find(|a| a.entry.kind.0 == kind)
.unwrap_or_else(|| panic!("{kind} is in the catalog"))
.render_path
};
assert_eq!(path_of("dock"), Some(RenderPath::ShipAction));
assert_eq!(path_of("convene"), Some(RenderPath::Conversation));
assert_eq!(path_of("speak"), Some(RenderPath::Conversation));
}
#[test]
fn a_reopened_grammar_world_still_holds_its_grammar() {
let grammar = grammar_with(&[]);
let identity = grammar.identity();
let (directory, kernel) = create(bound(Some(grammar), "Reopened"));
let kernel = kernel.unwrap();
let world_id = kernel.snapshot().unwrap().world_id;
drop(kernel);
let mut reopened = WorldKernel::open(directory.path().join("world.cc"), world_id).unwrap();
assert_eq!(reopened.snapshot().unwrap().grammar, Some(identity));
assert_eq!(
rejected(admit(
&mut reopened,
patch_of(vec![declare("wave", "wave", &[])])
)),
not_in_grammar("wave")
);
}
#[test]
fn the_bound_grammar_is_part_of_the_world_state_digest() {
let (_dir, kernel) = create(bound(Some(grammar_with(&[])), "Digested"));
let kernel = kernel.unwrap();
let bound_digest = crate::state_digest(&kernel.state).unwrap();
let mut state = kernel.state.clone();
state.grammar = None;
let open_digest = crate::state_digest(&state).unwrap();
state.grammar = Some(grammar_with(&[("dock", verb(RenderPath::ShipAction, &[]))]));
let other_digest = crate::state_digest(&state).unwrap();
assert_ne!(bound_digest, open_digest);
assert_ne!(bound_digest, other_digest);
}
#[test]
fn grammar_digest_is_derived_and_order_free() {
let forward = [
("alpha".to_owned(), verb(RenderPath::ShipAction, &[])),
(
"beta".to_owned(),
verb(
RenderPath::Conversation,
&[("to", GrammarReferentKind::Person)],
),
),
("gamma".to_owned(), verb(RenderPath::Conversation, &[])),
];
let mut reversed = forward.clone();
reversed.reverse();
let a = GrammarBinding::new("aetheria.grammar", 1, forward.clone()).unwrap();
let b = GrammarBinding::new("aetheria.grammar", 1, reversed).unwrap();
assert_eq!(a.digest, b.digest);
assert_eq!(a, b);
// Content-derived: each part of a verb moves the digest.
let changed = |edit: &dyn Fn(&mut Vec<(String, GrammarVerb)>)| {
let mut verbs = forward.to_vec();
edit(&mut verbs);
GrammarBinding::new("aetheria.grammar", 1, verbs)
.unwrap()
.digest
};
assert_ne!(
a.digest,
changed(&|v| v[0].1.render_path = RenderPath::Conversation)
);
assert_ne!(a.digest, changed(&|v| v[1].1.roles[0].role = "from".into()));
assert_ne!(
a.digest,
changed(&|v| v[1].1.roles[0].referent = GrammarReferentKind::Faction)
);
assert_ne!(a.digest, changed(&|v| v[2].0 = "delta".into()));
assert_ne!(
a.digest,
changed(&|v| {
v.pop();
})
);
// Role order is part of a verb.
let ordered = |roles: &[(&str, GrammarReferentKind)]| {
GrammarBinding::new(
"g",
1,
[("meet".to_owned(), verb(RenderPath::ShipAction, roles))],
)
.unwrap()
.digest
};
assert_ne!(
ordered(&[
("a", GrammarReferentKind::Person),
("b", GrammarReferentKind::Place)
]),
ordered(&[
("b", GrammarReferentKind::Place),
("a", GrammarReferentKind::Person)
])
);
// The identity reads the same fields back.
let identity = a.identity();
assert_eq!(identity.schema_id, "aetheria.grammar");
assert_eq!(identity.revision, 1);
assert_eq!(identity.digest, a.digest);
}
#[test]
fn a_tampered_grammar_digest_fails_to_deserialise() {
let binding = grammar_with(&[]);
let value = serde_json::to_value(&binding).unwrap();
// Untouched: the round trip holds.
let back: GrammarBinding = serde_json::from_value(value.clone()).unwrap();
assert_eq!(back, binding);
// A digest the verbs do not have.
let mut forged = value.clone();
forged["digest"] = "sha256:00".into();
assert!(serde_json::from_value::<GrammarBinding>(forged.clone()).is_err());
// A verb edited under the digest it already had.
let mut edited = value;
edited["verbs"]["convene"]["render_path"] = "ship_action".into();
assert!(serde_json::from_value::<GrammarBinding>(edited).is_err());
// The named encoding a state row uses refuses it the same way.
let bytes = rmp_serde::to_vec_named(&forged).unwrap();
assert!(rmp_serde::from_slice::<GrammarBinding>(&bytes).is_err());
}
#[test]
fn a_grammar_names_each_verb_once_and_has_a_schema() {
assert_eq!(
GrammarBinding::new("", 1, Vec::new()).unwrap_err(),
GrammarError::EmptySchemaId
);
assert_eq!(
GrammarBinding::new(
"g",
1,
[
("hail".to_owned(), verb(RenderPath::Conversation, &[])),
("hail".to_owned(), verb(RenderPath::ShipAction, &[])),
]
)
.unwrap_err(),
GrammarError::DuplicateVerb
);
}
/// The fixture world was written by the code at base 367e2eb, which has no
/// grammar field anywhere. Reopening it must reproduce the digests that code
/// recorded.
#[test]
fn existing_world_reopens_with_unchanged_digests() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("world.cc");
std::fs::write(&path, include_bytes!("../../tests/fixtures/base_world.cc")).unwrap();
let world_id: WorldId =
serde_json::from_str(include_str!("../../tests/fixtures/base_world.id").trim()).unwrap();
let kernel = WorldKernel::open(&path, world_id).expect("a base-written world reopens");
let snapshot = kernel.snapshot().unwrap();
let recorded = include_str!("../../tests/fixtures/base_world.digests");
let mut lines = recorded.lines();
assert_eq!(snapshot.revision.to_string(), lines.next().unwrap());
assert_eq!(snapshot.state_digest, lines.next().unwrap());
assert_eq!(
snapshot.last_commit_digest.as_deref(),
Some(lines.next().unwrap())
);
assert!(snapshot.grammar.is_none());
// Its state still derives the recorded digest from its bytes.
assert_eq!(
crate::state_digest(&kernel.state).unwrap(),
snapshot.state_digest
);
}
fn submit_as(
kernel: &mut WorldKernel,
caller: CallerId,
answers: Option<crate::PatchAnswer>,
patch: WorldPatch,
) -> Result<SubmitReceipt, KernelError> {
let snapshot = kernel.snapshot().unwrap();
kernel.submit(
command(
&snapshot,
CommandId::new(),
caller.clone(),
CommandBody::AdmitPatch { answers, patch },
),
&crate::AuthenticatedCaller::fixture(caller),
)
}
/// A bound Draft world whose revision has moved past genesis: one owner patch
/// that adds a dead-end place the elaborator can answer.
fn advanced_grammar_world() -> (tempfile::TempDir, WorldKernel, crate::EntityId) {
let extra = [("hail", verb(RenderPath::Conversation, &[]))];
let (dir, kernel) = create(bound(Some(grammar_with(&extra)), "Advanced"));
let mut kernel = kernel.unwrap();
let commons = *kernel.state.entities.keys().next().unwrap();
admit(
&mut kernel,
patch_of(vec![
Declaration::Entity(crate::patch::EntityDeclaration {
handle: DraftHandle::new("dead-end"),
label: "The Unwalked Road".into(),
kind: EntityKind::Place,
container: None,
}),
Declaration::Route(crate::patch::RouteDeclaration {
handle: DraftHandle::new("gate"),
label: "The Field Gate".into(),
from: crate::patch::Ref::Existing(commons),
to: crate::patch::Ref::Draft(DraftHandle::new("dead-end")),
access: crate::patch::AccessKind::Public,
cost: crate::patch::Cost(1),
}),
]),
)
.unwrap();
let dead_end = *kernel
.state
.entities
.iter()
.find(|(_, record)| record.label == "The Unwalked Road")
.map(|(id, _)| id)
.unwrap();
(dir, kernel, dead_end)
}
type Door = (&'static str, CallerId, Option<crate::PatchAnswer>);
/// Each door refuses an outside kind and a wrong role signature, typed, and the
/// refusal leaves the revision where it was. The owner and the consumer declare
/// unanswered only in Draft; Play and the elaborator act in Active.
fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec<Door>) {
for (door, caller, answers) in doors {
let revision = kernel.state.revision;
let kind = submit_as(
kernel,
caller.clone(),
answers.clone(),
patch_of(vec![declare("wave", "wave", &[])]),
);
assert_eq!(rejected(kind), not_in_grammar("wave"), "{door}");
let roles = submit_as(
kernel,
caller,
answers,
patch_of(vec![declare("hail", "hail", &[("who", person())])]),
);
assert_eq!(rejected(roles), disagrees("hail"), "{door}");
assert_eq!(
kernel.state.revision, revision,
"{door} refusal moved the world"
);
}
}
#[test]
fn every_admission_door_refuses_outside_the_grammar_after_the_revision_has_moved() {
let (_dir, mut kernel, dead_end) = advanced_grammar_world();
assert_eq!(kernel.state.revision, 1);
let draft_doors = vec![
("owner", CallerId::Principal(owner()), None),
(
"consumer",
CallerId::System(crate::SystemCapability::Consumer {
consumer: crate::ConsumerId::of_name("grammar-door"),
}),
None,
),
];
refuse_at_each_door(&mut kernel, draft_doors);
crate::tests::activate(&mut kernel);
assert!(
kernel.state.revision > 1,
"the world has moved past genesis"
);
let answer = crate::derive_boundaries(&kernel.state)
.unwrap()
.into_iter()
.find(|boundary| {
matches!(boundary, crate::CausalBoundary::UnelaboratedDestination { place, .. }
if *place == dead_end)
})
.expect("the dead end is an unelaborated destination");
let active_doors = vec![
(
"play",
CallerId::System(crate::SystemCapability::Play),
None,
),
(
"elaborator",
CallerId::System(crate::SystemCapability::Elaborator {
jurisdiction: crate::JurisdictionKey::PlaceSubtree(dead_end),
}),
Some(crate::PatchAnswer::Boundary(answer)),
),
];
refuse_at_each_door(&mut kernel, active_doors);
// The same path admits what the grammar carries, so the refusals above are
// the grammar's and not a closed door.
let receipt = submit_as(
&mut kernel,
CallerId::System(crate::SystemCapability::Play),
None,
patch_of(vec![declare("hail", "hail", &[])]),
)
.unwrap();
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
}
#[test]
fn a_grammar_that_binds_speak_as_anything_but_conversation_is_refused_at_bind() {
let ship = |roles: &[(&str, GrammarReferentKind)]| {
GrammarBinding::new(
"aetheria.grammar",
1,
[
("speak".to_owned(), verb(RenderPath::ShipAction, roles)),
("convene".to_owned(), verb(RenderPath::Conversation, &[])),
],
)
.unwrap()
};
assert_eq!(
rejected(create(bound(Some(ship(&[])), "Filmed speech")).1),
vec![Mismatch::SpeakRenderPathDisagreesWithGrammar {
handle: DraftHandle::new(crate::patch::KERNEL_SPEAK_HANDLE),
}]
);
// A ShipAction speak with a role fails on the signature first and is still
// refused: no variant of speak but zero roles, Conversation, is admitted.
assert_eq!(
rejected(
create(bound(
Some(ship(&[("to", GrammarReferentKind::Person)])),
"Loud"
))
.1
),
disagrees(crate::patch::KERNEL_SPEAK_HANDLE)
);
// The control: Conversation speak binds.
assert!(create(bound(Some(grammar_with(&[])), "Spoken")).1.is_ok());
}
/// `apply_effect` re-decides an effect it is handed. An effect resolved against
/// a world with no grammar must not install an entry the bound grammar lacks:
/// the catalog's only writer holds the grammar check itself.
#[test]
fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() {
let extra = [
(
"meet",
verb(
RenderPath::ShipAction,
&[("who", GrammarReferentKind::Person)],
),
),
("hail", verb(RenderPath::Conversation, &[])),
];
let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Forged"));
let kernel = kernel.unwrap();
let mut twin = kernel.state.clone();
twin.grammar = None;
let resolve = |kind: &str, roles: &[(&str, RefKind)]| {
crate::patch::resolve_patch(
&twin,
CommandId::new(),
&patch_of(vec![declare("probe", kind, roles)]),
None,
None,
)
.expect("the unbound twin admits any canonical kind")
};
for (label, resolved, admitted) in [
("outside kind", resolve("wave", &[]), false),
("wrong roles", resolve("meet", &[("whom", person())]), false),
("carried verb", resolve("hail", &[]), true),
] {
let mut state = kernel.state.clone();
let catalog = state.affordance_catalog.len();
let result = crate::apply_effect(
&mut state,
CommandId::new(),
&CallerId::Principal(owner()),
&crate::WorldEffect::PatchAdmitted {
answers: None,
resolved,
},
);
if admitted {
result.unwrap_or_else(|error| panic!("{label}: {error:?}"));
assert_eq!(state.affordance_catalog.len(), catalog + 1, "{label}");
} else {
assert!(
matches!(result, Err(KernelError::Invariant(_))),
"{label}: {result:?}"
);
assert_eq!(state.affordance_catalog.len(), catalog, "{label}");
}
}
}

View file

@ -1,752 +0,0 @@
//! One record, one subject: admission keeps the import-key mapping injective at
//! every door and at every revision, and a world nobody imported into is
//! byte-for-byte what it was before keys existed.
use crate::patch::{
AccessKind, ComponentOp, Cost, Declaration, DraftHandle, EntityDeclaration, EntityKind,
ImportKey, Mismatch, Ref, RouteDeclaration,
};
use crate::tests::{activate, auth_principal, command, creation, owner};
use crate::{
CallerId, CommandBody, CommandId, ConsumerId, CreateWorld, EntityId, JurisdictionKey,
KernelError, NewController, PatchAnswer, SubjectDeclaration, SubjectKind, SubmitReceipt,
SystemCapability, WorldKernel, WorldPatch,
};
use std::collections::BTreeSet;
fn key(schema: &str, record: &str) -> ImportKey {
ImportKey::new(schema, record)
}
fn alpha() -> ImportKey {
key("aetheria.ship", "Alpha")
}
/// The fixture genesis with its witness imported from `alpha()`.
fn keyed_creation(title: &str) -> CreateWorld {
let mut world = creation(CommandId::new(), title);
for declaration in &mut world.patch.declarations {
if let Declaration::Subject(subject) = declaration
&& subject.handle == DraftHandle::new("persona")
{
subject.import_key = Some(alpha());
}
}
world
}
fn create(world: CreateWorld) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) {
let directory = tempfile::tempdir().unwrap();
let result = WorldKernel::create(
directory.path().join("world.cc"),
world,
&auth_principal(owner()),
)
.map(|(kernel, _)| kernel);
(directory, result)
}
fn keyed_world() -> (tempfile::TempDir, WorldKernel) {
let (dir, kernel) = create(keyed_creation("Keyed"));
(dir, kernel.unwrap())
}
fn rejected(result: Result<impl Sized, KernelError>) -> Vec<Mismatch> {
match result {
Err(KernelError::PatchRejected(set)) => set,
Err(other) => panic!("expected a patch refusal, got {other:?}"),
Ok(_) => panic!("expected a patch refusal, the command was admitted"),
}
}
fn patch_of(declarations: Vec<Declaration>) -> WorldPatch {
WorldPatch {
declarations,
operations: Vec::new(),
evidence: Vec::new(),
}
}
fn submit_as(
kernel: &mut WorldKernel,
caller: CallerId,
answers: Option<PatchAnswer>,
patch: WorldPatch,
) -> Result<SubmitReceipt, KernelError> {
let snapshot = kernel.snapshot().unwrap();
kernel.submit(
command(
&snapshot,
CommandId::new(),
caller.clone(),
CommandBody::AdmitPatch { answers, patch },
),
&crate::AuthenticatedCaller::fixture(caller),
)
}
fn commons(kernel: &WorldKernel) -> EntityId {
*kernel.state.entities.keys().next().unwrap()
}
/// A mirror subject: the one shape every door may declare, since it needs no
/// catalog grant.
fn mirror(handle: &str, import_key: Option<ImportKey>, place: EntityId) -> Declaration {
Declaration::Subject(SubjectDeclaration {
handle: DraftHandle::new(handle),
label: format!("The {handle}"),
kind: SubjectKind::Person,
controller: NewController::External {
consumer: ConsumerId::of_name("import-key"),
},
affordances: BTreeSet::new(),
position: Some(Ref::Existing(place)),
import_key,
})
}
fn held(handle: &str) -> Mismatch {
Mismatch::ImportKeyHeld {
handle: DraftHandle::new(handle),
}
}
fn duplicate(handle: &str) -> Mismatch {
Mismatch::DuplicateImportKey {
handle: DraftHandle::new(handle),
}
}
fn malformed(handle: &str) -> Mismatch {
Mismatch::MalformedImportKey {
handle: DraftHandle::new(handle),
}
}
fn keys_in(kernel: &WorldKernel) -> Vec<ImportKey> {
kernel
.snapshot()
.unwrap()
.subjects
.into_iter()
.filter_map(|subject| subject.import_key)
.collect()
}
#[test]
fn one_patch_cannot_declare_two_subjects_with_one_import_key() {
// At genesis.
let mut world = creation(CommandId::new(), "Twins");
for declaration in &mut world.patch.declarations {
if let Declaration::Subject(subject) = declaration
&& (subject.handle == DraftHandle::new("persona")
|| subject.handle == DraftHandle::new("operator"))
{
subject.import_key = Some(alpha());
}
}
let (_dir, result) = create(world);
assert_eq!(rejected(result), vec![duplicate("operator")]);
// In a later patch, with the key unheld.
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let revision = kernel.state.revision;
let beta = Some(key("aetheria.ship", "Beta"));
let error = submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![
mirror("first", beta.clone(), place),
mirror("second", beta, place),
]),
);
assert_eq!(rejected(error), vec![duplicate("second")]);
assert_eq!(kernel.state.revision, revision, "a refusal moved the world");
}
/// The fixture world past genesis but still in Draft: the owner has added an
/// unwalked place the elaborator can later answer.
fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) {
let (dir, mut kernel) = keyed_world();
let place = commons(&kernel);
submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![
Declaration::Entity(EntityDeclaration {
handle: DraftHandle::new("dead-end"),
label: "The Unwalked Road".into(),
kind: EntityKind::Place,
container: None,
}),
Declaration::Route(RouteDeclaration {
handle: DraftHandle::new("gate"),
label: "The Field Gate".into(),
from: Ref::Existing(place),
to: Ref::Draft(DraftHandle::new("dead-end")),
access: AccessKind::Public,
cost: Cost(1),
}),
]),
)
.unwrap();
let dead_end = *kernel
.state
.entities
.iter()
.find(|(_, record)| record.label == "The Unwalked Road")
.map(|(id, _)| id)
.unwrap();
(dir, kernel, dead_end)
}
/// Each door names the held key, typed, and the refusal leaves the revision
/// where it was. The owner and the consumer declare in Draft only; Play and the
/// elaborator act in Active.
fn refuse_held_key_at_each_door(
kernel: &mut WorldKernel,
place: EntityId,
doors: Vec<(&str, CallerId, Option<PatchAnswer>)>,
) {
for (door, caller, answers) in doors {
let revision = kernel.state.revision;
let result = submit_as(
kernel,
caller,
answers,
patch_of(vec![mirror("copy", Some(alpha()), place)]),
);
assert_eq!(rejected(result), vec![held("copy")], "{door}");
assert_eq!(
kernel.state.revision, revision,
"{door} refusal moved the world"
);
}
}
fn consumer() -> CallerId {
CallerId::System(SystemCapability::Consumer {
consumer: ConsumerId::of_name("import-key"),
})
}
#[test]
fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() {
let (_dir, mut kernel, dead_end) = advanced_keyed_world();
assert!(kernel.state.revision > 0, "the world has moved past genesis");
refuse_held_key_at_each_door(
&mut kernel,
dead_end,
vec![
("owner", CallerId::Principal(owner()), None),
("consumer", consumer(), None),
],
);
activate(&mut kernel);
let answer = crate::derive_boundaries(&kernel.state)
.unwrap()
.into_iter()
.find(|boundary| {
matches!(boundary, crate::CausalBoundary::UnelaboratedDestination { place, .. }
if *place == dead_end)
})
.expect("the dead end is an unelaborated destination");
refuse_held_key_at_each_door(
&mut kernel,
dead_end,
vec![
("play", CallerId::System(SystemCapability::Play), None),
(
"elaborator",
CallerId::System(SystemCapability::Elaborator {
jurisdiction: JurisdictionKey::PlaceSubtree(dead_end),
}),
Some(PatchAnswer::Boundary(answer.clone())),
),
],
);
// The same doors admit an unheld key, so the refusals are the key's; and
// what a door admitted is held against every later door.
let fresh = key("aetheria.ship", "Gamma");
let receipt = submit_as(
&mut kernel,
CallerId::System(SystemCapability::Elaborator {
jurisdiction: JurisdictionKey::PlaceSubtree(dead_end),
}),
Some(PatchAnswer::Boundary(answer)),
patch_of(vec![mirror("fresh", Some(fresh.clone()), dead_end)]),
)
.unwrap();
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
let again = submit_as(
&mut kernel,
CallerId::System(SystemCapability::Play),
None,
patch_of(vec![mirror("fresh-again", Some(fresh), dead_end)]),
);
assert_eq!(rejected(again), vec![held("fresh-again")]);
}
#[test]
fn a_held_import_key_is_refused_in_a_later_patch() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let revision = kernel.state.revision;
let error = submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror("again", Some(alpha()), place)]),
);
assert_eq!(rejected(error), vec![held("again")]);
assert_eq!(kernel.state.revision, revision);
assert_eq!(keys_in(&kernel), vec![alpha()]);
}
#[test]
fn a_retired_subjects_import_key_is_never_reissued() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let witness = kernel
.snapshot()
.unwrap()
.subjects
.into_iter()
.find(|subject| subject.import_key.is_some())
.unwrap()
.id;
submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::Retire {
subject: Ref::Existing(witness),
}],
evidence: Vec::new(),
},
)
.unwrap();
let retired = kernel
.snapshot()
.unwrap()
.subjects
.into_iter()
.find(|subject| subject.id == witness)
.unwrap();
assert!(retired.retired, "the witness is retired");
assert_eq!(
retired.import_key,
Some(alpha()),
"a retired subject keeps its key"
);
let error = submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror("reborn", Some(alpha()), place)]),
);
assert_eq!(rejected(error), vec![held("reborn")]);
}
#[test]
fn keys_that_differ_in_any_way_are_distinct_records() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
// Same length, case, prefix, the same concatenation split elsewhere, and
// the parts swapped: none is the held key.
let forgeries = [
key("aetheria.ship", "Alphb"),
key("aetheria.ship", "alpha"),
key("aetheria.ship", "Alph"),
key("aetheria.ship", "Alpha2"),
key("aetheria.shipA", "lpha"),
key("aetheria.sh", "ipAlpha"),
key("Aetheria.ship", "Alpha"),
key("Alpha", "aetheria.ship"),
key("aetheria.ship2", "Alpha"),
];
let declarations = forgeries
.iter()
.enumerate()
.map(|(index, forged)| mirror(&format!("forged-{index}"), Some(forged.clone()), place))
.collect();
submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(declarations),
)
.expect("nine distinct keys beside the held one are admitted together");
let held_now: BTreeSet<ImportKey> = keys_in(&kernel).into_iter().collect();
assert_eq!(held_now.len(), forgeries.len() + 1);
// And each is then held exactly: repeating any one is refused.
for (index, forged) in forgeries.iter().enumerate() {
let again = submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror("repeat", Some(forged.clone()), place)]),
);
assert_eq!(rejected(again), vec![held("repeat")], "forgery {index}");
}
}
#[test]
fn a_malformed_import_key_is_refused_without_echoing_it() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let long = "x".repeat(201);
let wide = "é".repeat(101);
let cases = [
key("", "Delta"),
key("aetheria.ship", ""),
key("aetheria ship", "Delta"),
key("aetheria.ship", "Del\tta"),
key("aetheria.ship", "Del\u{a0}ta"),
key("aetheria.ship", " Delta"),
key("aetheria.ship", "Delta\n"),
key(&long, "Delta"),
key("aetheria.ship", &long),
key("aetheria.ship", &wide),
key(&wide, "Delta"),
];
for (index, bad) in cases.iter().enumerate() {
let set = rejected(submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror("bad", Some(bad.clone()), place)]),
));
assert_eq!(set, vec![malformed("bad")], "case {index}");
let spelled = format!("{set:?}");
assert!(
!spelled.contains("Delta") && !spelled.contains("aetheria"),
"case {index} echoed the key"
);
}
// The limit is 200 bytes per part, counted in bytes.
let edge = "é".repeat(100);
let at_limit = [
key(&"x".repeat(200), &edge),
key("aetheria.ship", &"y".repeat(200)),
];
let declarations = at_limit
.iter()
.enumerate()
.map(|(index, limit)| mirror(&format!("edge-{index}"), Some(limit.clone()), place))
.collect();
submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(declarations),
)
.expect("keys of exactly 200 bytes per part are admitted");
}
#[test]
fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_elsewhere() {
let (_dir, kernel) = keyed_world();
let place = commons(&kernel);
let resolve = |handle: &str| {
crate::patch::resolve_patch(
&kernel.state,
CommandId::new(),
&patch_of(vec![mirror(
handle,
Some(key("aetheria.ship", "Omega")),
place,
)]),
None,
None,
)
.expect("the key is unheld at the revision both were resolved against")
};
let (first, second) = (resolve("first"), resolve("second"));
let mut state = kernel.state.clone();
let before = state.subjects.len();
let effect = |resolved| crate::WorldEffect::PatchAdmitted {
answers: None,
resolved,
};
crate::apply_effect(
&mut state,
CommandId::new(),
&CallerId::Principal(owner()),
&effect(first),
)
.unwrap();
assert_eq!(state.subjects.len(), before + 1);
let result = crate::apply_effect(
&mut state,
CommandId::new(),
&CallerId::Principal(owner()),
&effect(second),
);
assert!(
matches!(result, Err(KernelError::Invariant(_))),
"{result:?}"
);
assert_eq!(
state.subjects.len(),
before + 1,
"the second subject was installed"
);
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
haystack.windows(needle.len()).any(|window| window == needle)
}
#[test]
fn keyless_world_digests_unchanged() {
// A subject nobody imported serialises without the field at all, so every
// digest written before keys existed is the digest of the same bytes.
let (_dir, kernel) = create(creation(CommandId::new(), "Keyless"));
let kernel = kernel.unwrap();
let state = rmp_serde::to_vec_named(&kernel.state).unwrap();
assert!(
!contains(&state, b"import_key"),
"a keyless world grew a field"
);
// A keyed world carries it, round-trips, and digests differently.
let (_dir, keyed) = keyed_world();
let keyed_state = rmp_serde::to_vec_named(&keyed.state).unwrap();
assert!(contains(&keyed_state, b"import_key"));
let back: crate::WorldState = rmp_serde::from_slice(&keyed_state).unwrap();
assert_eq!(
crate::state_digest(&back).unwrap(),
crate::state_digest(&keyed.state).unwrap()
);
assert_ne!(
crate::state_digest(&keyed.state).unwrap(),
crate::state_digest(&kernel.state).unwrap()
);
// And a pre-key state deserialises with every key absent.
let stripped: crate::WorldState = rmp_serde::from_slice(&state).unwrap();
assert!(stripped.subjects.values().all(|s| s.import_key.is_none()));
}
#[test]
fn a_keyed_world_reopens_with_its_keys_and_digests() {
let (dir, kernel) = keyed_world();
let snapshot = kernel.snapshot().unwrap();
let world_id = snapshot.world_id;
drop(kernel);
let reopened = WorldKernel::open(dir.path().join("world.cc"), world_id).unwrap();
let again = reopened.snapshot().unwrap();
assert_eq!(again.state_digest, snapshot.state_digest);
let keys = keys_in(&reopened);
assert_eq!(keys, vec![alpha()]);
// A reader of the snapshot gets both parts back, separately.
assert_eq!(keys[0].schema(), "aetheria.ship");
assert_eq!(keys[0].record(), "Alpha");
}
#[test]
fn a_record_key_is_one_canonical_spelling() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let nfc = "Caf\u{e9}";
let nfd = "Cafe\u{301}";
let submit = |kernel: &mut WorldKernel, handle: &str, record: &str| {
submit_as(
kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror(
handle,
Some(key("aetheria.ship", record)),
place,
)]),
)
};
submit(&mut kernel, "nfc", nfc).expect("the NFC spelling is admitted");
let refused = [
nfd,
"Alpha\u{200b}",
"Alpha\u{0}",
"\u{feff}Alpha",
"Alpha\u{202e}",
"Alpha\u{7}",
"Del ta",
"Del\tta",
"Del\u{a0}ta",
"Del\u{2003}ta",
"Del\nta",
// The violation sits deep in a long, real-shaped path, past any prefix.
"Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Cafe\u{301}",
"Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan\u{200b}Hart",
];
for (index, record) in refused.iter().enumerate() {
let set = rejected(submit(&mut kernel, "bad", record));
assert_eq!(set, vec![malformed("bad")], "spelling {index}");
assert!(
!format!("{set:?}").contains("Alpha"),
"spelling {index} echoed the key"
);
}
assert_eq!(
keys_in(&kernel).len(),
2,
"only the genesis key and the NFC key are held"
);
}
#[test]
fn a_lore_page_path_with_spaces_is_a_record_key() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let record = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart";
let declare = |kernel: &mut WorldKernel, handle: &str| {
submit_as(
kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror(
handle,
Some(key("aetheria.lore", record)),
place,
)]),
)
};
declare(&mut kernel, "ewan").expect("a path with interior spaces is admitted");
assert_eq!(rejected(declare(&mut kernel, "again")), vec![held("again")]);
}
#[test]
fn a_loaded_state_with_a_bad_import_key_is_refused() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror(
"beta",
Some(key("aetheria.ship", "Beta")),
place,
)]),
)
.unwrap();
assert!(crate::journal::verify_state_shape(&kernel.state).is_ok());
let corrupt = |edit: &dyn Fn(&mut ImportKey)| {
let mut state = kernel.state.clone();
for subject in state.subjects.values_mut() {
if let Some(held) = subject.import_key.as_mut() {
edit(held);
}
}
crate::journal::verify_state_shape(&state)
};
let shared = corrupt(&|held| *held = alpha());
assert!(
matches!(&shared, Err(crate::journal::JournalError::Corrupt(why)) if why.contains("import key")),
"two subjects sharing one key: {shared:?}"
);
assert!(
corrupt(&|held| *held = key("aetheria.ship", " Beta ")).is_err(),
"a key with edge spaces must not load"
);
assert!(
corrupt(&|held| *held = key("", "")).is_err(),
"an empty key must not load"
);
assert!(
corrupt(&|held| *held = key("aetheria.ship", "Be\u{200b}ta")).is_err(),
"a key with a format character must not load"
);
}
/// The admission backstop, reached with an effect resolution never produced: a
/// resolved patch whose two subjects carry one key. The control is the same
/// effect with distinct keys, admitted by the same function.
#[test]
fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() {
let (_dir, kernel) = keyed_world();
let place = commons(&kernel);
let resolve = || {
crate::patch::resolve_patch(
&kernel.state,
CommandId::new(),
&patch_of(vec![
mirror("first", Some(key("aetheria.ship", "Beta")), place),
mirror("second", Some(key("aetheria.ship", "Gamma")), place),
]),
None,
None,
)
.expect("two distinct keys resolve")
};
let resolves_to = crate::resolution_revision(&kernel.state).unwrap();
let mut control = kernel.state.clone();
crate::admit_resolved(&mut control, &resolve(), resolves_to)
.expect("distinct keys are admitted");
let mut twinned = resolve();
assert_eq!(twinned.subjects.len(), 2);
twinned.subjects[1].subject.import_key = twinned.subjects[0].subject.import_key.clone();
let mut state = kernel.state.clone();
let error = crate::admit_resolved(&mut state, &twinned, resolves_to)
.expect_err("one key on two resolved subjects is refused");
assert!(
matches!(&error, KernelError::Invariant(why) if why.contains("import key")),
"{error:?}"
);
assert!(!format!("{error:?}").contains("Beta"), "the refusal echoed the key");
}
/// A decomposable character at every position of a real-shaped key: the NFD
/// spelling is refused wherever it sits, the NFC spelling is admitted, so the
/// rule cannot be a prefix, suffix or first-character check.
#[test]
fn a_decomposable_character_is_refused_in_nfd_at_every_position() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let template: Vec<char> = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart"
.chars()
.collect();
let submit = |kernel: &mut WorldKernel, handle: &str, record: String| {
submit_as(
kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror(
handle,
Some(key("aetheria.lore", &record)),
place,
)]),
)
};
let spelled = |position: usize, inserted: &str| {
let mut record: String = template[..position].iter().collect();
record.push_str(inserted);
record.extend(&template[position..]);
record
};
for position in 0..=template.len() {
let nfd = spelled(position, "e\u{301}");
assert!(
!unicode_normalization::is_nfc(&nfd),
"position {position} is not NFD"
);
let set = rejected(submit(&mut kernel, "bad", nfd));
assert_eq!(set, vec![malformed("bad")], "NFD at position {position}");
}
for position in 0..=template.len() {
let nfc = spelled(position, "\u{e9}");
submit(&mut kernel, &format!("good{position}"), nfc)
.unwrap_or_else(|_| panic!("NFC at position {position} was refused"));
}
assert_eq!(
keys_in(&kernel).len(),
1 + template.len() + 1,
"the genesis key and one NFC key per position are held, no NFD key"
);
}

File diff suppressed because it is too large Load diff

View file

@ -1,379 +0,0 @@
//! The stock lenses. A lens is the flavor an elaborator session reaches for:
//! prompt emphasis over the one fixed tool catalog, never admission, authority,
//! or quota. This module owns the stock table, each lens's instruction text,
//! and the draw recipe; it reads no world state and writes nothing.
use super::{CommandId, KernelError, WorldId, digest};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// The sentence every lens's instructions begin with.
const ELABORATION_INSTRUCTIONS: &str = "Use only the supplied tools to author structure inside your jurisdiction. Answer the boundary or deficit you were given, then submit. Recording a gap changes nothing.";
/// The library's stock lens set. Serialized by snake_case name, so a name the
/// library does not know cannot be represented at any deserialization boundary.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Lens {
Patina,
Charter,
Ledger,
Hearth,
Tangle,
Veil,
Ember,
Numen,
}
impl Lens {
/// Every lens, in declaration order. The draw walks this order.
pub const ALL: [Lens; 8] = [
Lens::Patina,
Lens::Charter,
Lens::Ledger,
Lens::Hearth,
Lens::Tangle,
Lens::Veil,
Lens::Ember,
Lens::Numen,
];
pub fn name(self) -> &'static str {
match self {
Lens::Patina => "Patina",
Lens::Charter => "Charter",
Lens::Ledger => "Ledger",
Lens::Hearth => "Hearth",
Lens::Tangle => "Tangle",
Lens::Veil => "Veil",
Lens::Ember => "Ember",
Lens::Numen => "Numen",
}
}
/// What kind of structure the lens reaches for.
pub fn reaches_for(self) -> &'static str {
match self {
Lens::Patina => "ordinary objects, customs, nicknames, local jokes",
Lens::Charter => "government, law, offices, selection, succession, redress",
Lens::Ledger => "resources, labor, trade, infrastructure, scarcity, class pressure",
Lens::Hearth => "kinship, daily life, care, obligation, belonging",
Lens::Tangle => "factions, alliances, rivalries, leverage",
Lens::Veil => "secrets, rumors, misinformation, taboos, unevenly held knowledge",
Lens::Ember => "disputes, hazards, instability, escalation, urgent pressure",
Lens::Numen => "religion, magic, ritual, awe, cosmology, the genuinely strange",
}
}
/// Existing `PATCH_TOOLS` names in emphasis order. Emphasis is prompt text
/// only: the catalog, its order, and its schemas are the same for every lens.
pub(crate) fn leads_with(self) -> &'static [&'static str] {
match self {
Lens::Patina => &[
"set_persona_material",
"declare_affordance",
"declare_resource",
"declare_place",
],
Lens::Charter => &[
"grant_authority",
"open_office",
"install_incumbent",
"open_forum",
"declare_subject",
],
Lens::Ledger => &[
"transfer",
"bind",
"declare_resource",
"alter_cost",
"declare_route",
],
Lens::Hearth => &[
"create_commitment",
"set_persona_material",
"declare_subject",
],
Lens::Tangle => &[
"advance_pressure",
"create_commitment",
"grant_authority",
"declare_subject",
"bind",
],
Lens::Veil => &[
"acquire_knowledge",
"communicate",
"declare_channel",
"set_reach",
"declare_fact",
"forget",
],
Lens::Ember => &[
"advance_pressure",
"create_commitment",
"close_route",
"consume",
],
Lens::Numen => &[
"declare_fact",
"declare_affordance",
"set_persona_material",
"witness",
],
}
}
/// The elaborator's instructions under this lens: the shared sentence, then
/// the lens clause. Read once, when a session is first built; the session
/// then carries the text, and nothing rebuilds it from here.
pub(crate) fn instructions(self) -> String {
format!(
"{ELABORATION_INSTRUCTIONS} Lens: {}. Reach for {}. Lead with {}; every supplied tool remains available.",
self.name(),
self.reaches_for(),
self.leads_with().join(", "),
)
}
}
/// A world's lens weights. Validity is decided where weights are admitted;
/// `Default` is the empty map a world holds before genesis writes its weights,
/// and it never draws.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct LensWeights(BTreeMap<Lens, u32>);
impl LensWeights {
pub fn new(weights: BTreeMap<Lens, u32>) -> Self {
Self(weights)
}
/// A lens the map does not name weighs zero.
pub fn get(&self, lens: Lens) -> u32 {
self.0.get(&lens).copied().unwrap_or(0)
}
pub fn iter(&self) -> impl Iterator<Item = (Lens, u32)> + '_ {
self.0.iter().map(|(lens, weight)| (*lens, *weight))
}
/// Some weight is nonzero, so a draw has somewhere to land.
pub(crate) fn draws(&self) -> bool {
self.0.values().any(|weight| *weight > 0)
}
/// Every stock lens weighs the same in both sets. A lens a map does not
/// name weighs zero, so `{charter: 3}` and `{patina: 0, charter: 3}` are
/// one set spelled two ways: they draw identically and neither replaces
/// the other.
pub(crate) fn weighs_the_same_as(&self, other: &LensWeights) -> bool {
Lens::ALL
.into_iter()
.all(|lens| self.get(lens) == other.get(lens))
}
}
/// The draw's whole input: the world and the session's fixed identity. The
/// weights select over it; they are not part of it.
#[derive(Serialize)]
struct LensPreimage {
world_id: WorldId,
command_id: CommandId,
}
/// One digest, one modulo, one cumulative walk over `Lens::ALL` — the recipe
/// `select_band` uses, not a second entropy shape. The same world, session
/// identity, and weights draw the same lens. Modulo rather than rejection
/// sampling: the bias is bounded by `total_weight / 2^64`.
pub(crate) fn draw(
weights: &LensWeights,
world_id: WorldId,
command_id: CommandId,
) -> Result<Lens, KernelError> {
// The guard is on the divisor itself, as `select_band`'s is: no other
// statement of "these weights draw" can let the modulo below divide by zero.
let total: u128 = Lens::ALL
.iter()
.map(|lens| u128::from(weights.get(*lens)))
.sum();
if total == 0 {
return Err(KernelError::Invariant("lens weights never draw".into()));
}
let preimage = digest(&LensPreimage {
world_id,
command_id,
})?;
let head = preimage
.strip_prefix("sha256:")
.and_then(|hex| hex.get(..16))
.and_then(|head| u64::from_str_radix(head, 16).ok())
.ok_or_else(|| KernelError::Invariant("lens draw digest is not hex".into()))?;
let mut position = u128::from(head) % total;
for lens in Lens::ALL {
let weight = u128::from(weights.get(lens));
if position < weight {
return Ok(lens);
}
position -= weight;
}
Err(KernelError::Invariant(
"lens weights did not cover the draw".into(),
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::patch::PATCH_TOOLS;
use crate::tests::stock_weights;
use std::collections::BTreeSet;
fn ids() -> Vec<CommandId> {
(0..200)
.map(|i| CommandId::derived("l1-probe", &[&i.to_string()]))
.collect()
}
fn tally(weights: &LensWeights) -> BTreeMap<Lens, usize> {
let mut counts = BTreeMap::new();
for id in ids() {
let lens = draw(weights, WorldId::nil_for_test(), id).unwrap();
*counts.entry(lens).or_insert(0) += 1;
}
counts
}
#[test]
fn every_lead_names_a_patch_tool() {
let catalog: BTreeSet<&str> = PATCH_TOOLS.iter().map(|entry| entry.name).collect();
for lens in Lens::ALL {
let leads = lens.leads_with();
assert!(!leads.is_empty(), "{lens:?} leads with nothing");
let distinct: BTreeSet<&str> = leads.iter().copied().collect();
assert_eq!(distinct.len(), leads.len(), "{lens:?} repeats a lead");
for name in leads {
assert!(
catalog.contains(name),
"{lens:?} leads with unknown tool {name}"
);
}
}
}
#[test]
fn the_draw_is_a_function_of_world_and_session() {
let weights = stock_weights();
let world = WorldId::nil_for_test();
for id in ids() {
assert_eq!(
draw(&weights, world, id).unwrap(),
draw(&weights, world, id).unwrap()
);
}
let expected: BTreeMap<Lens, usize> = BTREE_STOCK_TALLY.into_iter().collect();
assert_eq!(tally(&weights), expected);
}
/// Computed at Cut 1 and pinned: the replay proof for 200 derived ids under
/// stock weights.
const BTREE_STOCK_TALLY: [(Lens, usize); 8] = [
(Lens::Patina, 22),
(Lens::Charter, 37),
(Lens::Ledger, 26),
(Lens::Hearth, 19),
(Lens::Tangle, 23),
(Lens::Veil, 29),
(Lens::Ember, 18),
(Lens::Numen, 26),
];
#[test]
fn a_zero_weight_never_draws() {
let weights = LensWeights::new(BTreeMap::from([
(Lens::Patina, 0),
(Lens::Charter, 3),
(Lens::Ledger, 1),
]));
let counts = tally(&weights);
assert_eq!(counts.get(&Lens::Patina), None, "a zero weight drew");
let expected: BTreeMap<Lens, usize> = ZERO_WEIGHT_TALLY.into_iter().collect();
assert_eq!(counts, expected);
}
/// Computed at Cut 1 and pinned; near 3:1 over the same 200 ids.
const ZERO_WEIGHT_TALLY: [(Lens, usize); 2] = [(Lens::Charter, 155), (Lens::Ledger, 45)];
#[test]
fn all_zero_weights_are_an_error() {
let world = WorldId::nil_for_test();
let id = CommandId::derived("l1-probe", &["0"]);
let all_zero = LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect());
assert_eq!(all_zero.iter().count(), 8);
for weights in [LensWeights::default(), all_zero] {
assert!(matches!(
draw(&weights, world, id),
Err(KernelError::Invariant(_))
));
}
}
#[test]
fn an_unknown_lens_name_does_not_deserialize() {
for refused in [
r#"{"Patina":1}"#,
r#"{"patina ":1}"#,
r#"{"patinaa":1}"#,
r#"{"patina":1,"tribunal":1}"#,
] {
assert!(
serde_json::from_str::<LensWeights>(refused).is_err(),
"{refused} deserialized"
);
}
let accepted = serde_json::from_str::<LensWeights>(r#"{"patina":1}"#).unwrap();
assert_eq!(accepted.get(Lens::Patina), 1);
assert_eq!(accepted.iter().count(), 1);
let stock = stock_weights();
let bytes = rmp_serde::to_vec_named(&stock).unwrap();
let back: LensWeights = rmp_serde::from_slice(&bytes).unwrap();
assert_eq!(back, stock);
assert_eq!(rmp_serde::to_vec_named(&back).unwrap(), bytes);
}
#[test]
fn each_lens_text_names_its_own_leads() {
let mut texts = BTreeSet::new();
for lens in Lens::ALL {
let text = lens.instructions();
assert!(text.contains(lens.name()), "{lens:?} text omits its name");
for name in lens.leads_with() {
assert!(text.contains(name), "{lens:?} text omits {name}");
}
texts.insert(text);
}
assert_eq!(texts.len(), 8, "two lenses share a text");
}
#[test]
fn lenses_serialize_as_snake_case_names() {
let names: Vec<String> = Lens::ALL
.iter()
.map(|lens| serde_json::to_string(lens).unwrap())
.collect();
assert_eq!(
names,
[
r#""patina""#,
r#""charter""#,
r#""ledger""#,
r#""hearth""#,
r#""tangle""#,
r#""veil""#,
r#""ember""#,
r#""numen""#,
]
);
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,196 +0,0 @@
//! The one emitter for every model-facing tool schema in the tree.
//!
//! Two catalogs sit above it and share nothing else: the action catalog
//! (`controllers::catalog_tools`) projects a world-state snapshot filtered by
//! grant, and the patch catalog (`patch::patch_tools`) projects the reducer's
//! own vocabulary. Both spell a property the same way because both spell it
//! here. Nothing in this module reads world state, a snapshot, or a config.
use model_connector::ToolDefinition;
use serde_json::{Value, json};
pub(super) fn tool(name: &str, description: &str, schema: Value) -> ToolDefinition {
ToolDefinition {
name: name.into(),
description: description.into(),
parameters_json: serde_json::to_string(&schema)
.expect("static tool schemas must serialize"),
}
}
pub(super) fn empty_schema() -> Value {
json!({"type":"object","additionalProperties":false,"properties":{}})
}
/// Every generated object is closed and total: `additionalProperties` is false
/// and every property is required. An optional argument is expressed as a
/// nullable property, never as an absent one, so the decoder and the schema
/// agree without a second rule about omission.
pub(super) fn object(properties: Vec<(String, Value)>) -> Value {
let required: Vec<Value> = properties
.iter()
.map(|(name, _)| Value::String(name.clone()))
.collect();
json!({
"type": "object",
"additionalProperties": false,
"required": required,
"properties": properties.into_iter().collect::<serde_json::Map<_, _>>(),
})
}
pub(super) fn canonical_string(description: &str) -> Value {
json!({"type": "string", "description": description})
}
pub(super) fn bounded_integer(min: u64, max: u64) -> Value {
json!({"type": "integer", "minimum": min, "maximum": max})
}
/// The same schema with the text the model reads beside it. Meaning that lives
/// only in a prompt paragraph is lost by the time the model fills the field.
pub(super) fn described(mut schema: Value, description: &str) -> Value {
if let Value::Object(fields) = &mut schema {
fields.insert("description".into(), Value::String(description.into()));
}
schema
}
pub(super) fn name_enum(values: &[&str]) -> Value {
json!({"type": "string", "enum": values})
}
/// A closed sum spelled as a tagged object. `tag` is the discriminator field
/// name; each variant carries its own closed object of content.
pub(super) fn variant(tag: &str, variants: Vec<(&str, Vec<(String, Value)>)>) -> Value {
let branches: Vec<Value> = variants
.into_iter()
.map(|(name, content)| {
let mut properties = vec![(tag.to_owned(), json!({"type": "string", "const": name}))];
properties.extend(content);
object(properties)
})
.collect();
json!({ "anyOf": branches })
}
pub(super) fn nullable(inner: Value) -> Value {
json!({ "anyOf": [inner, {"type": "null"}] })
}
pub(super) fn list(inner: Value) -> Value {
json!({"type": "array", "items": inner})
}
/// `{"ref": "draft"|"existing", "value": <handle text|canonical uuid>}` —
/// Invariant 1 rendered as a schema, and the only reference shape either
/// catalog emits.
pub(super) fn reference(referent: &str) -> Value {
json!({
"type": "object",
"additionalProperties": false,
"required": ["ref", "value"],
"properties": {
"ref": {"type": "string", "enum": ["draft", "existing"]},
"value": {
"type": "string",
"description": format!(
"a draft handle declared in this same patch, or the canonical id of an existing {referent}"
),
},
},
})
}
/// An adjacently tagged sum: `{"<tag>": "<variant>", "<content>": <payload>}`.
/// A variant with no payload (`None`) omits the content field entirely, which
/// is what serde emits for a unit variant in an adjacently tagged enum.
pub(super) fn variant_content(
tag: &str,
content: &str,
variants: Vec<(&str, Option<Value>)>,
) -> Value {
let branches: Vec<Value> = variants
.into_iter()
.map(|(name, payload)| {
let mut properties = vec![(tag.to_owned(), json!({"type": "string", "const": name}))];
if let Some(inner) = payload {
properties.push((content.to_owned(), inner));
}
object(properties)
})
.collect();
json!({ "anyOf": branches })
}
/// An externally tagged sum: a bare string for a unit variant, or a
/// single-key object for one that carries a payload.
pub(super) fn external_variant(variants: Vec<(&str, Option<Value>)>) -> Value {
let branches: Vec<Value> = variants
.into_iter()
.map(|(name, payload)| match payload {
None => json!({"type": "string", "const": name}),
Some(inner) => object(vec![(name.to_owned(), inner)]),
})
.collect();
json!({ "anyOf": branches })
}
/// The provider's strict function-schema rules, enforced offline so the
/// catalog cannot be refused on the road one keyword at a time: every
/// node names a `type` or is an `anyOf` of nodes that do; every object is
/// closed and lists every property as required; `oneOf`, `allOf`, and
/// `not` never appear. The first live seeded run failed on exactly these.
#[cfg(test)]
pub(super) fn assert_strict(schema: &Value, at: &str) {
for forbidden in ["oneOf", "allOf", "not"] {
assert!(
schema.get(forbidden).is_none(),
"{at}: `{forbidden}` is not permitted in a strict schema"
);
}
if let Some(branches) = schema.get("anyOf").and_then(Value::as_array) {
assert!(!branches.is_empty(), "{at}: empty anyOf");
for (index, branch) in branches.iter().enumerate() {
assert_strict(branch, &format!("{at}/anyOf/{index}"));
}
return;
}
let kind = schema
.get("type")
.and_then(Value::as_str)
.unwrap_or_else(|| panic!("{at}: schema must have a `type` key: {schema}"));
match kind {
"object" => {
assert_eq!(
schema.get("additionalProperties"),
Some(&Value::Bool(false)),
"{at}: object must be closed"
);
let properties = schema
.get("properties")
.and_then(Value::as_object)
.unwrap_or_else(|| panic!("{at}: object without properties"));
let mut names: Vec<&str> = properties.keys().map(String::as_str).collect();
names.sort_unstable();
let mut required: Vec<&str> = schema
.get("required")
.and_then(Value::as_array)
.map(|list| list.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
required.sort_unstable();
assert_eq!(names, required, "{at}: every property must be required");
for (name, property) in properties {
assert_strict(property, &format!("{at}/{name}"));
}
}
"array" => {
let items = schema
.get("items")
.unwrap_or_else(|| panic!("{at}: array without items"));
assert_strict(items, &format!("{at}/items"));
}
"string" | "integer" | "number" | "boolean" | "null" => {}
other => panic!("{at}: unexpected type {other}"),
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,747 +0,0 @@
//! Provider call records, the run's spend, and replay.
//!
//! `RecordingInferencePort` is the one owner of a run's spend. Before it
//! forwards a call it decides, from the request alone, whether the call could
//! pass the run's token cap; after the reply it charges what the call really
//! cost. Every reply is stored as a `ProviderCallRecord` before the output
//! returns to the lane, so `ReplayInferencePort` can serve the same run again
//! from the store with no provider behind it.
//!
//! Lanes and runners never count tokens. A request is held against the cap by
//! its bound: the serialized provider request's bytes (a token is at least one
//! byte, so bytes bound the prompt) plus the request's own output allowance.
//!
//! The run's spend is one persisted ledger row per run, owned by the store and
//! written where it is spent. A call reserves its bound in that row before the
//! provider is called; a reply settles the reservation to what it reported
//! (prompt plus completion, cached prompt tokens being part of the prompt; none
//! reported is charged the bound); a fault leaves the reservation charged. A
//! restart reads the row, so no restart returns budget. A reply that reports
//! more than the call's bound is charged in full and faults the call, so the
//! run's spend never passes the cap unnoticed. One port at a time owns a run.
use crate::controllers::{
InferenceEvent, InferenceFault, InferenceOutput, InferencePort, InferencePurpose,
InferenceRequest, PreparedInference, REQUEST_EXPIRY, TokenUsage, ToolResultOracle, unix_ms,
};
use async_trait::async_trait;
use chrono::Utc;
use model_connector::ProviderRequest;
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
collections::{BTreeMap, BTreeSet, VecDeque},
path::Path,
sync::{Arc, Mutex},
};
use thiserror::Error;
const CALL_RECORD_ROW: &str = "verse_provider_call.v1";
const RUN_LEDGER_ROW: &str = "verse_run_ledger.v1";
/// The run ledger document's schema.
const RUN_LEDGER_SCHEMA: &str = "ghostlight.verse_run_ledger.v1";
/// The call record document's schema. A store holding any other row type or
/// schema is refused at open: this store is not migrated from, or shared with,
/// another document.
pub const CALL_RECORD_SCHEMA: &str = "ghostlight.verse_provider_call.v1";
#[derive(Clone, Copy, Debug, Error, PartialEq, Eq)]
pub enum CallRecordError {
#[error("a run id is 1 to 64 characters of letters, digits, '-' and '_'")]
InvalidRunId,
#[error("the call record store could not be read or written")]
Store,
#[error("the call record store holds a row that is not a canonical call record")]
Corrupt,
#[error("a call record's sequence is not the next in its run")]
OutOfSequence,
#[error("replay needs one run's records in dense sequence from 1")]
NotReplayable,
#[error("another recording port already owns this run")]
RunInUse,
#[error("the call could pass the run's token cap")]
OverCap,
#[error("the run was recorded with a different {0}")]
RunMismatch(RunField),
}
/// What a run is bound to when it begins, named by the field a mismatch refuses.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunField {
/// The token cap the run was opened with.
Cap,
/// The identity of the world the run started from.
WorldId,
/// The state digest of the world the run started from.
StateDigest,
}
impl std::fmt::Display for RunField {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Cap => "token cap",
Self::WorldId => "world id",
Self::StateDigest => "world state digest",
})
}
}
/// The world a run began from: its identity and state digest. Replay is of a
/// restored copy of this world, so it takes the same two values.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunStart {
world_id: String,
state_digest: String,
}
impl RunStart {
pub fn of(world: &crate::WorldSnapshot) -> Self {
Self {
world_id: world.world_id.text(),
state_digest: world.state_digest.clone(),
}
}
}
/// A run's identity as a key segment.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct RunId(String);
impl RunId {
pub fn new(id: &str) -> Result<Self, CallRecordError> {
let valid = !id.is_empty()
&& id.len() <= 64
&& id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
if valid {
Ok(Self(id.to_owned()))
} else {
Err(CallRecordError::InvalidRunId)
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
/// One provider call of one run: the request's content digest (never its text, so no
/// prompt or credential is stored), the reply exactly as the lane received it,
/// and what the call was charged. Keyed (run id, sequence).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProviderCallRecord {
run_id: String,
sequence: u64,
purpose: InferencePurpose,
model: String,
content_sha256: String,
events: Vec<InferenceEvent>,
receipt_digest: String,
usage: Option<TokenUsage>,
charged: u64,
}
impl ProviderCallRecord {
pub fn run_id(&self) -> &str {
&self.run_id
}
pub fn sequence(&self) -> u64 {
self.sequence
}
pub fn purpose(&self) -> InferencePurpose {
self.purpose
}
pub fn model(&self) -> &str {
&self.model
}
/// Lowercase hex of the request's content digest (see `content_digest`).
pub fn content_sha256(&self) -> &str {
&self.content_sha256
}
pub fn usage(&self) -> Option<TokenUsage> {
self.usage
}
/// Tokens this call was charged against the run's cap.
pub fn charged(&self) -> u64 {
self.charged
}
/// The reply as the lane received it.
pub fn output(&self) -> InferenceOutput {
let output = InferenceOutput::new(self.events.clone(), self.receipt_digest.clone());
match self.usage {
Some(usage) => output.with_usage(usage),
None => output,
}
}
}
fn row_key(run: &str, sequence: u64) -> String {
format!("{run}/{sequence:020}")
}
fn hex(digest: &[u8]) -> String {
digest.iter().map(|byte| format!("{byte:02x}")).collect()
}
/// What a request asks of the provider, without the ids that name it. The
/// request and conversation ids are derived from the command id, and a command
/// id from the world it ran in, so keying on them would tie a recorded run to
/// one world's random identity. Everything else the provider is sent
/// (model, instructions, input, tools, shape) is in the digest.
fn content_digest(request: &ProviderRequest) -> Result<String, InferenceFault> {
// Exhaustive on purpose: a field added upstream must be placed in the key
// or left out here by name before this compiles.
let ProviderRequest {
schema_id,
request_id: _request_id, // names the call, not what it asks
conversation_id: _conversation_id, // names the call, not what it asks
model,
instructions,
input,
reasoning_effort,
cache_retention,
tools,
tool_choice,
parallel_tool_calls,
output_schema_json,
max_output_tokens,
} = request;
let bytes = rmp_serde::to_vec(&(
schema_id,
model,
instructions,
input,
reasoning_effort,
cache_retention,
tools,
tool_choice,
parallel_tool_calls,
output_schema_json,
max_output_tokens,
))
.map_err(|_| InferenceFault::new("a provider request could not be measured"))?;
Ok(hex(&Sha256::digest(bytes)))
}
/// A run's persisted ledger, the one owner of what the run began as: the cap
/// it was opened under, the world it started from, and the tokens reserved or
/// charged so far.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct RunLedger {
run_id: String,
cap: u64,
start: RunStart,
spent: u64,
}
enum DecodedRow {
Call(ProviderCallRecord),
Ledger(RunLedger),
}
pub(super) fn canonical<T: Serialize + for<'de> Deserialize<'de>>(
row: &CultCacheEnvelope,
) -> Result<T, CallRecordError> {
let value: T = rmp_serde::from_slice(&row.payload).map_err(|_| CallRecordError::Corrupt)?;
let again = rmp_serde::to_vec_named(&value).map_err(|_| CallRecordError::Corrupt)?;
if again == row.payload {
Ok(value)
} else {
Err(CallRecordError::Corrupt)
}
}
fn decode_row(row: &CultCacheEnvelope) -> Result<DecodedRow, CallRecordError> {
match (row.r#type.as_str(), row.schema_id.as_deref()) {
(CALL_RECORD_ROW, Some(CALL_RECORD_SCHEMA)) => {
let record: ProviderCallRecord = canonical(row)?;
// A run id that is no whole key segment would key into another
// run's records, and sequences count from 1.
if RunId::new(&record.run_id).is_err()
|| record.sequence == 0
|| row.key != row_key(&record.run_id, record.sequence)
{
return Err(CallRecordError::Corrupt);
}
Ok(DecodedRow::Call(record))
}
(RUN_LEDGER_ROW, Some(RUN_LEDGER_SCHEMA)) => {
let ledger: RunLedger = canonical(row)?;
if RunId::new(&ledger.run_id).is_err() || row.key != ledger.run_id {
return Err(CallRecordError::Corrupt);
}
Ok(DecodedRow::Ledger(ledger))
}
_ => Err(CallRecordError::Corrupt),
}
}
#[derive(Default)]
struct RunTally {
last_sequence: u64,
/// The persisted ledger, read at open and written where it is spent.
ledger: Option<RunLedger>,
}
struct StoreState {
store: OwnedRedbMessagePackBackingStore,
runs: BTreeMap<String, RunTally>,
/// Runs with a recording port alive; one ledger has one owner.
owned: BTreeSet<String>,
}
/// The call records and spend ledgers of every run in one CultCache file.
/// Records are appended and never changed; a run's sequence is dense from 1.
pub struct CallRecordStore {
state: Mutex<StoreState>,
}
impl CallRecordStore {
/// Opens the file, creating it empty when absent. Every row must be a
/// canonical call record or run ledger of this schema with its key, a
/// dense sequence, and a ledger that covers its records' charges; anything
/// else, an earlier or later schema version included, is refused and
/// nothing is migrated.
pub fn open(path: impl AsRef<Path>) -> Result<Self, CallRecordError> {
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())
.map_err(|_| CallRecordError::Store)?;
store
.validate_path_identity()
.map_err(|_| CallRecordError::Store)?;
let rows = store.pull_all().map_err(|_| CallRecordError::Store)?;
let mut runs: BTreeMap<String, RunTally> = BTreeMap::new();
let mut counts: BTreeMap<String, u64> = BTreeMap::new();
let mut charged: BTreeMap<String, u64> = BTreeMap::new();
for row in &rows {
match decode_row(row)? {
DecodedRow::Call(record) => {
*counts.entry(record.run_id.clone()).or_default() += 1;
let total = charged.entry(record.run_id.clone()).or_default();
*total = total.saturating_add(record.charged);
let tally = runs.entry(record.run_id).or_default();
tally.last_sequence = tally.last_sequence.max(record.sequence);
}
DecodedRow::Ledger(ledger) => {
let run = ledger.run_id.clone();
runs.entry(run).or_default().ledger = Some(ledger);
}
}
}
// Sequences start at 1 and keys are unique, so a run is dense exactly
// when its rows number its highest sequence. Every record was reserved
// in a ledger before it was made, so a run with records has a ledger
// that covers what they charged.
for (run, tally) in &runs {
let rows = counts.get(run).copied().unwrap_or(0);
let recorded = charged.get(run).copied().unwrap_or(0);
let covered = tally
.ledger
.as_ref()
.is_some_and(|ledger| ledger.spent >= recorded);
if rows != tally.last_sequence || !covered {
return Err(CallRecordError::Corrupt);
}
}
Ok(Self {
state: Mutex::new(StoreState {
store,
runs,
owned: BTreeSet::new(),
}),
})
}
fn lock(&self) -> Result<std::sync::MutexGuard<'_, StoreState>, CallRecordError> {
self.state.lock().map_err(|_| CallRecordError::Store)
}
/// The sequence the next record of this run must carry.
pub fn next_sequence(&self, run: &RunId) -> Result<u64, CallRecordError> {
Ok(self
.lock()?
.runs
.get(run.as_str())
.map_or(0, |tally| tally.last_sequence)
+ 1)
}
/// Tokens this run has reserved or been charged: its persisted ledger.
pub fn spent(&self, run: &RunId) -> Result<u64, CallRecordError> {
Ok(self
.lock()?
.runs
.get(run.as_str())
.and_then(|tally| tally.ledger.as_ref())
.map_or(0, |ledger| ledger.spent))
}
/// Takes the run's ledger for one port, or refuses when another holds it.
/// The first claim of a run writes its ledger: the cap it is opened under
/// and the world it starts from. A later claim must name the same cap; the
/// start is not compared, because a resumed world has moved on.
fn claim(&self, run: &RunId, cap: u64, start: &RunStart) -> Result<(), CallRecordError> {
let mut state = self.lock()?;
if !state.owned.insert(run.as_str().to_owned()) {
return Err(CallRecordError::RunInUse);
}
let begun = match state.runs.get(run.as_str()).and_then(|t| t.ledger.as_ref()) {
Some(ledger) if ledger.cap == cap => Ok(()),
Some(_) => Err(CallRecordError::RunMismatch(RunField::Cap)),
None => Self::write_ledger(
&mut state,
RunLedger {
run_id: run.as_str().to_owned(),
cap,
start: start.clone(),
spent: 0,
},
),
};
if begun.is_err() {
state.owned.remove(run.as_str());
}
begun
}
/// The world a run began from, when it has begun.
fn start_of(&self, run: &RunId) -> Result<Option<RunStart>, CallRecordError> {
Ok(self
.lock()?
.runs
.get(run.as_str())
.and_then(|tally| tally.ledger.as_ref())
.map(|ledger| ledger.start.clone()))
}
fn disown(&self, run: &RunId) {
if let Ok(mut state) = self.state.lock() {
state.owned.remove(run.as_str());
}
}
/// Persists the ledger, then adopts it in memory. A write that fails
/// leaves the previous ledger.
fn write_ledger(state: &mut StoreState, ledger: RunLedger) -> Result<(), CallRecordError> {
let row = CultCacheEnvelope {
key: ledger.run_id.clone(),
r#type: RUN_LEDGER_ROW.into(),
payload: rmp_serde::to_vec_named(&ledger).map_err(|_| CallRecordError::Store)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(RUN_LEDGER_SCHEMA.into()),
};
state.store.push(&row).map_err(|_| CallRecordError::Store)?;
let run = ledger.run_id.clone();
state.runs.entry(run).or_default().ledger = Some(ledger);
Ok(())
}
/// Persists `spent` as the run's spend; the run must have been claimed.
fn write_spent(state: &mut StoreState, run: &str, spent: u64) -> Result<(), CallRecordError> {
let mut ledger = state
.runs
.get(run)
.and_then(|tally| tally.ledger.clone())
.ok_or(CallRecordError::Store)?;
ledger.spent = spent;
Self::write_ledger(state, ledger)
}
fn held(state: &StoreState, run: &RunId) -> u64 {
state
.runs
.get(run.as_str())
.and_then(|tally| tally.ledger.as_ref())
.map_or(0, |ledger| ledger.spent)
}
/// Charges `bound` to the run's persisted ledger, or refuses with
/// `OverCap` when the ledger plus the bound would pass `cap`. The check and
/// the write hold one lock, so calls on the wire hold their bounds.
fn reserve(&self, run: &RunId, bound: u64, cap: u64) -> Result<(), CallRecordError> {
let mut state = self.lock()?;
let after = Self::held(&state, run).saturating_add(bound);
if after > cap {
return Err(CallRecordError::OverCap);
}
Self::write_spent(&mut state, run.as_str(), after)
}
/// Replaces a reservation of `bound` with what the call was charged. With
/// a record, the record is stored first, so a crash between the two writes
/// leaves the larger reservation charged.
fn settle(
&self,
run: &RunId,
bound: u64,
charged: u64,
record: Option<&ProviderCallRecord>,
) -> Result<(), CallRecordError> {
let mut state = self.lock()?;
if let Some(record) = record {
Self::push_record(&mut state, record)?;
}
let settled = Self::held(&state, run)
.saturating_sub(bound)
.saturating_add(charged);
Self::write_spent(&mut state, run.as_str(), settled)
}
fn append(&self, record: &ProviderCallRecord) -> Result<(), CallRecordError> {
let mut state = self.lock()?;
Self::push_record(&mut state, record)
}
fn push_record(
state: &mut StoreState,
record: &ProviderCallRecord,
) -> Result<(), CallRecordError> {
let last = state
.runs
.get(&record.run_id)
.map_or(0, |tally| tally.last_sequence);
if record.sequence != last + 1 {
return Err(CallRecordError::OutOfSequence);
}
let row = CultCacheEnvelope {
key: row_key(&record.run_id, record.sequence),
r#type: CALL_RECORD_ROW.into(),
payload: rmp_serde::to_vec_named(record).map_err(|_| CallRecordError::Store)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(CALL_RECORD_SCHEMA.into()),
};
state.store.push(&row).map_err(|_| CallRecordError::Store)?;
state
.runs
.entry(record.run_id.clone())
.or_default()
.last_sequence = record.sequence;
Ok(())
}
/// The run's records in sequence.
pub fn records(&self, run: &RunId) -> Result<Vec<ProviderCallRecord>, CallRecordError> {
let prefix = format!("{}/", run.as_str());
let rows = self
.lock()?
.store
.pull_all()
.map_err(|_| CallRecordError::Store)?;
let mut records = Vec::new();
for row in rows.iter().filter(|row| row.key.starts_with(&prefix)) {
if let DecodedRow::Call(record) = decode_row(row)? {
records.push(record);
}
}
records.sort_by_key(|record| record.sequence);
Ok(records)
}
}
/// Decorates a port for one run: reserves each call's bound in the run's
/// ledger before the provider is called, settles it to the real cost, and
/// stores every reply before returning it.
pub struct RecordingInferencePort {
inner: Arc<dyn InferencePort>,
store: Arc<CallRecordStore>,
run: RunId,
cap: u64,
}
impl RecordingInferencePort {
/// Takes ownership of the run's ledger, which resumes from the store. The
/// first open of a run records its cap and the world it starts from; a
/// reopen with another cap is refused with `RunMismatch(Cap)`. A second
/// port on a run whose first is alive is refused with `RunInUse`.
pub fn open(
inner: Arc<dyn InferencePort>,
store: Arc<CallRecordStore>,
run: RunId,
cap_tokens: u64,
start: &RunStart,
) -> Result<Self, CallRecordError> {
store.claim(&run, cap_tokens, start)?;
Ok(Self {
inner,
store,
run,
cap: cap_tokens,
})
}
/// The run this port records.
pub fn run_id(&self) -> &RunId {
&self.run
}
/// The token cap the run was opened under.
pub fn cap(&self) -> u64 {
self.cap
}
/// Tokens reserved or charged to the run so far.
pub fn spent(&self) -> u64 {
self.store.spent(&self.run).unwrap_or(u64::MAX)
}
/// The most this request can cost: its serialized bytes plus its output
/// allowance. The v4 request type cannot omit the allowance, so every
/// request has a bound.
fn bound(request: &PreparedInference) -> Result<u64, InferenceFault> {
let allowance = request.invocation.request.max_output_tokens;
let payload = serde_json::to_vec(&request.invocation.request)
.map_err(|_| InferenceFault::new("a provider request could not be measured"))?;
Ok((payload.len() as u64).saturating_add(u64::from(allowance)))
}
fn settle(
&self,
bound: u64,
identity: (InferencePurpose, String, String),
result: Result<InferenceOutput, InferenceFault>,
) -> Result<InferenceOutput, InferenceFault> {
// A fault leaves its reservation charged: the request may have run.
let output = result?;
let charged = match output.usage {
Some(usage) => usage.prompt.saturating_add(usage.completion),
None => bound,
};
if charged > bound {
self.store
.settle(&self.run, bound, charged, None)
.map_err(unrecorded)?;
return Err(InferenceFault::budget_exhausted());
}
let (purpose, model, content_sha256) = identity;
let record = ProviderCallRecord {
run_id: self.run.as_str().to_owned(),
sequence: self.store.next_sequence(&self.run).map_err(unrecorded)?,
purpose,
model,
content_sha256,
events: output.events.clone(),
receipt_digest: output.receipt_digest.clone(),
usage: output.usage,
charged,
};
self.store
.settle(&self.run, bound, charged, Some(&record))
.map_err(unrecorded)?;
Ok(output)
}
}
impl Drop for RecordingInferencePort {
fn drop(&mut self) {
self.store.disown(&self.run);
}
}
fn unrecorded(_: CallRecordError) -> InferenceFault {
InferenceFault::integrity_violation("a provider call could not be recorded")
}
#[async_trait]
impl InferencePort for RecordingInferencePort {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
self.inner.prepare(request)
}
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
let bound = Self::bound(&request)?;
let identity = (
request.purpose,
request.invocation.request.model.clone(),
content_digest(&request.invocation.request)?,
);
self.store
.reserve(&self.run, bound, self.cap)
.map_err(|error| match error {
CallRecordError::OverCap => InferenceFault::budget_exhausted(),
_ => unrecorded(error),
})?;
let result = self.inner.infer(request).await;
self.settle(bound, identity, result)
}
fn lend_tool_results(&self, prepared: &PreparedInference, oracle: Box<dyn ToolResultOracle>) {
self.inner.lend_tool_results(prepared, oracle);
}
}
/// Serves a run's stored replies, in sequence, to the same requests, matched
/// by what they ask of the provider and not by the ids that name them. It holds
/// no provider and makes no call: a request that is not the next recorded one
/// is a fault.
pub struct ReplayInferencePort {
caller_runtime_id: String,
pending: Mutex<VecDeque<ProviderCallRecord>>,
}
impl ReplayInferencePort {
/// Replays `run` from the store against `world`, a restored copy of the
/// world the run started from. Any other world is refused here, before a
/// call, with `RunMismatch` naming the field; a run the store never began
/// is `NotReplayable`.
pub fn new(
caller_runtime_id: impl Into<String>,
store: &CallRecordStore,
run: &RunId,
world: &RunStart,
) -> Result<Self, CallRecordError> {
let began = store.start_of(run)?.ok_or(CallRecordError::NotReplayable)?;
if began.world_id != world.world_id {
return Err(CallRecordError::RunMismatch(RunField::WorldId));
}
if began.state_digest != world.state_digest {
return Err(CallRecordError::RunMismatch(RunField::StateDigest));
}
Ok(Self {
caller_runtime_id: caller_runtime_id.into(),
pending: Mutex::new(store.records(run)?.into()),
})
}
}
#[async_trait]
impl InferencePort for ReplayInferencePort {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
PreparedInference::prepare(
&self.caller_runtime_id,
unix_ms()?.saturating_add(REQUEST_EXPIRY.as_millis() as u64),
request,
)
}
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
let mut pending = self
.pending
.lock()
.map_err(|_| InferenceFault::integrity_violation("the replay queue was poisoned"))?;
let digest = content_digest(&request.invocation.request)?;
let Some(next) = pending.front() else {
return Err(InferenceFault::integrity_violation(
"replay has no recorded call left",
));
};
if next.content_sha256 != digest {
return Err(InferenceFault::integrity_violation(
"the request is not the next recorded call",
));
}
let output = next.output();
pending.pop_front();
Ok(output)
}
}
#[cfg(test)]
mod tests;

File diff suppressed because it is too large Load diff

View file

@ -1,144 +0,0 @@
//! The canonical Aetheria verse world's genesis.
//!
//! One intent lowers to one `CreateWorld`: a commons, every grammar verb
//! declared as an affordance, and each Aetheria faction as an institution
//! imported by its record key. The world is bound to the catalog's grammar, so
//! the kernel refuses any affordance the grammar does not carry.
//!
//! Phase A verbs record the act and change no component: an outcome band with
//! no effects, and the act carried as the utterance that makes an entry
//! admissible. Ghostlight owns each verb's lowering to kernel effects (ruling
//! `verb-effects-ghostlight`), and those arrive with phase B.
use crate::aetheria::AetheriaCatalog;
use crate::mailbox::{MailboxError, commons_declaration, commons_ref};
use crate::patch::{
AffordanceDeclaration, AffordanceKindName, AudienceSpec, Declaration, DraftHandle, EvidenceRef,
FactDeclaration, FactStandingRef, OutcomeBand, Precondition, Ref, Statement, SubjectDeclaration,
kernel_speak_entry, kernel_speak_grant,
};
use crate::{
CommandId, CreateWorld, LensWeights, NewController, PrincipalId, SubjectKind,
WorldPatch, WorldScaleIntentRef,
};
use std::collections::BTreeMap;
const COMMIT_LEN: usize = 40;
/// What a caller states to create the canonical verse world. Everything else a
/// world needs (the commons, the subjects, the affordances, their grants and
/// the provenance of what is known) is derived from the catalog.
#[derive(Clone, Debug)]
pub struct CreateVerseWorldIntent {
pub id: CommandId,
pub title: String,
pub brief: String,
pub catalog: AetheriaCatalog,
/// The Aetheria commit the catalog was read at: 40 lower-case hex digits.
/// It is the provenance of every fact the world holds about a faction.
pub aetheria_commit: String,
pub lens_weights: LensWeights,
pub targets: BTreeMap<SubjectKind, u32>,
}
#[derive(Debug, thiserror::Error)]
pub enum VerseGenesisError {
#[error("aetheria_commit is not 40 lower-case hex digits")]
NotACommit,
#[error(transparent)]
Mailbox(#[from] MailboxError),
}
impl CreateVerseWorldIntent {
/// The one lowering. The kernel supplies the `speak` entry at genesis and
/// holds it to the grammar, so it is granted here and never declared.
pub(crate) fn lower(self, owner: PrincipalId) -> Result<CreateWorld, VerseGenesisError> {
let commit = &self.aetheria_commit;
if commit.len() != COMMIT_LEN
|| !commit
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
{
return Err(VerseGenesisError::NotACommit);
}
let speak = kernel_speak_entry().kind;
let mut grants = kernel_speak_grant();
let mut declarations = vec![commons_declaration()];
for (kind, verb) in self.catalog.grammar.verbs() {
if kind == speak.0 {
continue;
}
let handle = DraftHandle::new(format!("verb-{kind}"));
grants.insert(Ref::Draft(handle.clone()));
declarations.push(Declaration::Affordance(AffordanceDeclaration {
handle,
kind: AffordanceKindName(kind.to_owned()),
roles: verb.role_specs(),
preconditions: vec![Precondition::CanBroadcast {
via: AudienceSpec::Colocated,
}],
effect_slots: Vec::new(),
outcome_bands: vec![OutcomeBand {
weight: 1,
effects: Vec::new(),
}],
// The kernel refuses an entry that can neither change a
// component nor speak, and a speaking entry needs an audience,
// so a phase A verb is its own utterance to the room: the act
// is recorded as speech and nothing else changes.
carries_speech: true,
}));
}
let mut evidence = Vec::new();
for (position, faction) in self.catalog.factions.iter().enumerate() {
declarations.push(Declaration::Subject(SubjectDeclaration {
handle: DraftHandle::new(format!("faction-{position}")),
label: faction.name.trim().to_owned(),
kind: SubjectKind::Institution,
controller: NewController::OperationalAgent,
affordances: grants.clone(),
position: Some(commons_ref()),
import_key: Some(faction.key.clone()),
}));
// A faction with no description has nothing to state.
if let Some(statement) = Statement::new(faction.description.trim()) {
let receipt = EvidenceRef::new(format!(
"aetheria:{commit}:{}/{}",
faction.key.schema(),
faction.key.record()
));
evidence.push(receipt.clone());
declarations.push(Declaration::Fact(FactDeclaration {
handle: DraftHandle::new(format!("fact-{position}")),
label: faction.name.trim().to_owned(),
statement,
standing: FactStandingRef::Canonical { evidence: receipt },
}));
}
}
Ok(CreateWorld {
id: self.id,
owner,
title: self.title,
brief: self.brief,
patch: WorldPatch {
declarations,
operations: Vec::new(),
evidence,
},
scale_intent: WorldScaleIntentRef {
targets: self.targets,
jurisdictions: BTreeMap::new(),
},
lens_weights: self.lens_weights,
grammar: Some(self.catalog.grammar),
era: None,
})
}
}
#[cfg(test)]
mod tests;

View file

@ -1,477 +0,0 @@
use super::*;
use crate::aetheria::read_aetheria_catalog;
use crate::patch::{FactStanding, Mismatch};
use crate::tests::{auth_principal, owner, stock_weights};
use crate::{
CommandBody, ControllerMode, GrammarBinding, GrammarReferentKind, GrammarRole, GrammarVerb,
KernelError, PrincipalCommandIntent, RenderPath, VerifiedPrincipalEvidence, WorldKernel,
WorldMailbox, WorldPhase,
};
use chrono::{Duration, Utc};
use std::collections::BTreeSet;
/// Aetheria master when the fixture catalog was written.
const COMMIT: &str = "92b82e9aa5bb422c568c4bfc85a8f641426a41fc";
const OTHER_COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
const FIXTURE: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/aetheria-verse-catalog.cc"
);
fn catalog() -> AetheriaCatalog {
read_aetheria_catalog(FIXTURE).unwrap()
}
fn intent_of(catalog: AetheriaCatalog, commit: &str) -> CreateVerseWorldIntent {
CreateVerseWorldIntent {
id: CommandId::new(),
title: "The Verse".into(),
brief: "Aetheria.".into(),
catalog,
aetheria_commit: commit.into(),
lens_weights: stock_weights(),
targets: BTreeMap::new(),
}
}
/// A world created through the kernel from the lowering, for what the
/// snapshot hides: the facts' evidence.
fn kernel_of(intent: CreateVerseWorldIntent) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) {
let dir = tempfile::tempdir().unwrap();
let world = intent.lower(owner()).unwrap();
let result = WorldKernel::create(dir.path().join("world.cc"), world, &auth_principal(owner()))
.map(|(kernel, _)| kernel);
(dir, result)
}
struct Verse {
_dir: tempfile::TempDir,
_task: tokio::task::JoinHandle<()>,
mailbox: WorldMailbox,
principal: VerifiedPrincipalEvidence,
receipt: crate::CreationReceipt,
}
async fn verse(intent: CreateVerseWorldIntent) -> Verse {
let dir = tempfile::tempdir().unwrap();
let (mailbox, task) = WorldMailbox::open(dir.path().join("world.cc")).unwrap();
let principal =
VerifiedPrincipalEvidence::fixture("verse-owner", Utc::now() + Duration::hours(1));
let receipt = mailbox.create_verse(intent, &principal).await.unwrap();
Verse {
_dir: dir,
_task: task,
mailbox,
principal,
receipt,
}
}
#[tokio::test]
async fn verse_genesis_from_the_aetheria_fixture() {
let catalog = catalog();
let verse = verse(intent_of(catalog.clone(), COMMIT)).await;
let snapshot = verse.mailbox.snapshot().await.unwrap();
// One institution per faction, keyed by its record, named by its Name.
let mut factions: Vec<_> = snapshot
.subjects
.iter()
.map(|subject| {
(
subject.import_key.clone().unwrap(),
subject.label.clone(),
subject.kind,
subject.controller_mode,
)
})
.collect();
factions.sort_by(|a, b| a.0.cmp(&b.0));
let expected: Vec<_> = catalog
.factions
.iter()
.map(|faction| {
(
faction.key.clone(),
faction.name.clone(),
SubjectKind::Institution,
Some(ControllerMode::OperationalAgent),
)
})
.collect();
assert_eq!(factions.len(), 2);
assert_eq!(factions, expected);
// One fact per faction, carrying its description.
let statements: BTreeSet<_> = snapshot
.facts
.iter()
.map(|fact| fact.statement.as_str().to_owned())
.collect();
assert_eq!(
statements,
catalog
.factions
.iter()
.map(|faction| faction.description.clone())
.collect::<BTreeSet<_>>()
);
// The world is bound to the catalog's grammar.
assert_eq!(snapshot.grammar, Some(catalog.grammar.identity()));
assert_eq!(verse.receipt.world_id, snapshot.world_id);
// Every faction stands in the one commons.
let commons: Vec<_> = snapshot
.places
.iter()
.filter(|place| place.label == "The Commons")
.collect();
assert_eq!(commons.len(), 1);
assert!(
snapshot
.subjects
.iter()
.all(|subject| subject.position == Some(commons[0].id))
);
}
#[test]
fn each_fact_cites_its_faction_record_and_the_commit_it_was_read_at() {
for commit in [COMMIT, OTHER_COMMIT] {
let (_dir, kernel) = kernel_of(intent_of(catalog(), commit));
let kernel = kernel.unwrap();
let evidence: BTreeSet<String> = kernel
.state
.facts
.values()
.map(|fact| match &fact.standing {
FactStanding::Canonical { evidence } => evidence.text().to_owned(),
other => panic!("a verse fact is canonical, not {other:?}"),
})
.collect();
assert_eq!(
evidence,
catalog()
.factions
.iter()
.map(|faction| format!(
"aetheria:{commit}:aetheria.faction/{}",
faction.key.record()
))
.collect::<BTreeSet<_>>()
);
}
}
#[test]
fn a_commit_is_forty_lower_case_hex_digits() {
for bad in [
"",
&COMMIT[..39],
&format!("{COMMIT}0"),
&COMMIT.to_uppercase(),
&format!("{}g", &COMMIT[..39]),
] {
assert!(
matches!(
intent_of(catalog(), bad).lower(owner()),
Err(VerseGenesisError::NotACommit)
),
"{bad:?}"
);
}
assert!(intent_of(catalog(), COMMIT).lower(owner()).is_ok());
assert!(!VerseGenesisError::NotACommit.to_string().contains(COMMIT));
}
#[test]
fn verse_genesis_refuses_a_duplicate_faction_record() {
let mut twice = catalog();
let first = twice.factions[0].clone();
twice.factions.push(first);
// The lowering does not decide: it declares all three.
let world = intent_of(twice.clone(), COMMIT).lower(owner()).unwrap();
let subjects = world
.patch
.declarations
.iter()
.filter(|declaration| matches!(declaration, Declaration::Subject(_)))
.count();
assert_eq!(subjects, 3);
let (_dir, kernel) = kernel_of(intent_of(twice, COMMIT));
let Err(KernelError::PatchRejected(set)) = kernel else {
panic!("a second faction under one record key was admitted");
};
assert!(
set.iter()
.any(|mismatch| matches!(mismatch, Mismatch::DuplicateImportKey { .. })),
"{set:?}"
);
}
#[tokio::test]
async fn every_granted_affordance_is_a_grammar_verb() {
let catalog = catalog();
let verse = verse(intent_of(catalog.clone(), COMMIT)).await;
let snapshot = verse.mailbox.snapshot().await.unwrap();
let mut kinds: Vec<_> = snapshot
.affordances
.iter()
.map(|affordance| affordance.entry.kind.0.clone())
.collect();
kinds.sort();
// Each verb once: the kernel's speak is the grammar's speak.
assert_eq!(
kinds,
catalog
.grammar
.verbs()
.map(|(kind, _)| kind.to_owned())
.collect::<Vec<_>>()
);
assert!(kinds.contains(&"speak".to_owned()));
// Each has its render path from the grammar, and phase A changes nothing.
for affordance in &snapshot.affordances {
let verb = catalog.grammar.verb(&affordance.entry.kind.0).unwrap();
assert_eq!(affordance.render_path, Some(verb.render_path));
assert!(affordance.entry.effect_slots.is_empty());
assert_eq!(affordance.entry.outcome_bands.len(), 1);
assert!(affordance.entry.outcome_bands[0].effects.is_empty());
}
// Every faction is granted every verb.
let all: BTreeSet<_> = snapshot.affordances.iter().map(|a| a.id).collect();
for subject in &snapshot.subjects {
assert_eq!(subject.affordances, all);
}
}
#[tokio::test]
async fn factions_get_opportunities() {
let verse = verse(intent_of(catalog(), COMMIT)).await;
for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] {
let revision = verse.mailbox.snapshot().await.unwrap().revision;
verse
.mailbox
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: verse.receipt.world_id,
expected_revision: revision,
body,
},
&verse.principal,
)
.await
.unwrap();
}
let snapshot = verse.mailbox.snapshot().await.unwrap();
assert_eq!(snapshot.phase, WorldPhase::Active);
assert_eq!(snapshot.opportunities.len(), catalog().factions.len());
let scopes: BTreeSet<_> = snapshot.opportunities.iter().map(|o| o.scope).collect();
assert_eq!(scopes.len(), snapshot.opportunities.len());
for opportunity in &snapshot.opportunities {
assert_eq!(opportunity.controller_mode, ControllerMode::OperationalAgent);
assert_eq!(opportunity.affordance_ids.len(), snapshot.affordances.len());
}
}
#[test]
fn a_faction_without_a_description_holds_no_fact() {
let mut bare = catalog();
bare.factions[0].description = " ".into();
bare.factions[1].description = " Second. ".into();
let (_dir, kernel) = kernel_of(intent_of(bare, COMMIT));
let facts: Vec<_> = kernel
.unwrap()
.state
.facts
.values()
.map(|fact| fact.statement.as_str().to_owned())
.collect();
assert_eq!(facts, vec!["Second.".to_owned()]);
}
#[test]
fn a_grammar_the_kernel_speak_cannot_live_in_refuses_genesis() {
let mut mute = catalog();
mute.grammar = GrammarBinding::new(
"aetheria.verse_grammar",
1,
[(
"haul".to_owned(),
GrammarVerb {
render_path: RenderPath::ShipAction,
roles: vec![GrammarRole {
role: "cargo".into(),
referent: GrammarReferentKind::Cargo,
}],
},
)],
)
.unwrap();
let (_dir, kernel) = kernel_of(intent_of(mute, COMMIT));
let Err(KernelError::PatchRejected(set)) = kernel else {
panic!("a world whose grammar has no speak was admitted");
};
assert!(
set.iter()
.any(|mismatch| matches!(mismatch, Mismatch::AffordanceKindNotInGrammar { .. })),
"{set:?}"
);
}
#[tokio::test]
async fn the_dungeon_ingress_still_creates_an_unbound_world() {
let dir = tempfile::tempdir().unwrap();
let (mailbox, _task) = WorldMailbox::open(dir.path().join("world.cc")).unwrap();
let principal =
VerifiedPrincipalEvidence::fixture("dungeon-owner", Utc::now() + Duration::hours(1));
mailbox
.create(
crate::CreateWorldIntent {
id: CommandId::new(),
title: "Dungeon".into(),
brief: String::new(),
human_subject_label: "Player".into(),
narrative_persona_label: None,
operational_agent_label: None,
targets: BTreeMap::new(),
jurisdictions: Vec::new(),
lens_weights: stock_weights(),
era: None,
},
&principal,
)
.await
.unwrap();
let snapshot = mailbox.snapshot().await.unwrap();
assert_eq!(snapshot.grammar, None);
assert!(
snapshot
.places
.iter()
.any(|place| place.label == "The Commons")
);
}
#[tokio::test]
async fn a_faction_name_is_trimmed_into_its_institution_label() {
let mut padded = catalog();
let expected = padded.factions[0].name.trim().to_owned();
padded.factions[0].name = format!(" {expected}\t ");
let key = padded.factions[0].key.clone();
let verse = verse(intent_of(padded, COMMIT)).await;
let snapshot = verse.mailbox.snapshot().await.unwrap();
let subject = snapshot
.subjects
.iter()
.find(|subject| subject.import_key.as_ref() == Some(&key))
.expect("the padded faction was created");
assert_eq!(subject.label, expected);
}
#[tokio::test]
async fn genesis_twice_with_one_intent_is_one_creation() {
let dir = tempfile::tempdir().unwrap();
let (mailbox, _task) = WorldMailbox::open(dir.path().join("world.cc")).unwrap();
let principal =
VerifiedPrincipalEvidence::fixture("verse-owner", Utc::now() + Duration::hours(1));
let intent = intent_of(catalog(), COMMIT);
let first = mailbox.create_verse(intent.clone(), &principal).await.unwrap();
let before = mailbox.snapshot().await.unwrap();
let again = mailbox.create_verse(intent, &principal).await.unwrap();
let after = mailbox.snapshot().await.unwrap();
assert_eq!(again, first);
assert_eq!(after.revision, before.revision);
assert_eq!(after.state_digest, before.state_digest);
assert_eq!(after.subjects.len(), before.subjects.len());
}
#[tokio::test]
async fn genesis_under_another_command_id_finds_the_world_occupied() {
let verse = verse(intent_of(catalog(), COMMIT)).await;
let before = verse.mailbox.snapshot().await.unwrap();
let refused = verse
.mailbox
.create_verse(intent_of(catalog(), COMMIT), &verse.principal)
.await;
assert!(
matches!(
refused,
Err(VerseGenesisError::Mailbox(MailboxError::Kernel(
KernelError::CreationTargetOccupied
)))
),
"{refused:?}"
);
let after = verse.mailbox.snapshot().await.unwrap();
assert_eq!(after.revision, before.revision);
assert_eq!(after.state_digest, before.state_digest);
}
/// Pins the standing phase A behaviour (ruling `ship-acts-speech-shaped-phase-a`):
/// the lowering admits a ship verb only as an utterance,
/// and committing it asserts a claim fact the room hears.
#[test]
fn phase_a_ship_verbs_are_spoken_acts_in_the_room() {
use crate::tests::{command, opportunity_for, spoken, submit_owner};
use crate::{
AuthenticatedCaller, CallerId, DecisionInvocation, Role, RoleBinding, SubmitReceipt,
Target,
};
let (_scratch, kernel) = kernel_of(intent_of(catalog(), COMMIT));
let mut kernel = kernel.unwrap();
for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] {
let snapshot = kernel.snapshot().unwrap();
submit_owner(&mut kernel, &snapshot, body);
}
let active = kernel.snapshot().unwrap();
let attack = active
.affordances
.iter()
.find(|a| a.entry.kind.0 == "attack")
.unwrap()
.id;
let [first, second] = [&active.subjects[0], &active.subjects[1]];
let opportunity = opportunity_for(&active, first.id);
let caller = CallerId::Controller(opportunity.controller_id);
let invocation = |speech: Option<&str>| DecisionInvocation {
affordance: attack,
bindings: vec![RoleBinding {
role: Role("target".into()),
target: Target::Subject(second.id),
}],
proposed: Vec::new(),
speech: speech.map(|text| crate::patch::Statement::new(text).unwrap()),
display: None,
};
let try_it = |kernel: &mut WorldKernel, speech: Option<&str>| {
kernel.submit(
command(
&active,
CommandId::new(),
caller.clone(),
CommandBody::ExerciseDecision {
opportunity: opportunity.clone(),
invocation: invocation(speech),
},
),
&AuthenticatedCaller::fixture(caller.clone()),
)
};
// Without an utterance the act is refused: the verb has no other way in.
assert!(try_it(&mut kernel, None).is_err());
// With one, the act commits and its words are a claim fact.
let receipt = try_it(&mut kernel, Some("We strike.")).expect("the attack commits");
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
let event = kernel.state.events.last().unwrap();
assert_eq!(spoken(&kernel.state, event), Some("We strike."));
}

View file

@ -1,19 +0,0 @@
//! The Aetheria verse run's own organs. The verse binary sits above this
//! module; here sit the parts of a run that belong to the library: the record
//! of every provider call and the spend it implies, the genesis of the
//! canonical verse world, and the manual run that advances it with its record.
mod calls;
mod genesis;
mod run;
pub use genesis::{CreateVerseWorldIntent, VerseGenesisError};
pub use calls::{
CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, ProviderCallRecord,
RecordingInferencePort, ReplayInferencePort, RunField, RunId, RunStart,
};
pub use run::{
RUN_RECORD_SCHEMA, RecordedCoverBudget, Refusal, RefusalReason, RunClaim, RunOutcome, RunStatus,
TickCheckpoint, TickReport, UnattributedCall, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore,
call_run_id, run_manual,
};

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,757 +0,0 @@
//! Admission proofs for the kernel's seal, from outside the crate.
//!
//! The seal is unforgeable *admission*, not unconstructible values. External
//! code may hold a syntactically valid ID, digest, or `DecisionOpportunity` —
//! a consumer's own payloads carry these types over the wire, so they
//! deserialize — and the kernel must refuse every one it did not itself issue.
//! An integration test compiles as its own crate against the public API alone,
//! so these tests stand exactly where a consumer stands: every forged value
//! below is minted by `serde` from JSON, which is a path visibility does not
//! gate, and every rejection is asserted on the typed error rather than on a
//! message.
//!
//! Each rejection also asserts that nothing committed: revision, state digest,
//! last commit digest, and the operator log's length are unchanged. The
//! operator log is the widest committed-history surface a consumer can read;
//! the journal itself has no public accessor, so its length is proven only
//! through the digests and that log.
use chrono::{Duration, Utc};
use ghostlight::{
CommandBody, CommandId, ControllerMode, ControllerPort, CreateWorldIntent, DecisionInvocation,
DecisionOpportunity, KernelError, Lens, LensWeights, MailboxError, Mismatch, PlayPort,
PrincipalCommandIntent, Statement, SubjectId, SubmitReceipt, VerifiedPrincipalEvidence,
WorldMailbox, WorldPatch, WorldPhase, WorldSnapshot,
};
use serde_json::{Value, json};
use std::collections::BTreeMap;
/// A live world in Active phase, reached through the same public ingress a
/// consumer uses: create, approve, activate. Genesis grants speech to every
/// subject it declares, so the two model-controlled subjects each carry a live
/// opportunity with one granted affordance.
struct World {
_directory: tempfile::TempDir,
_owner: tokio::task::JoinHandle<()>,
mailbox: WorldMailbox,
principal: VerifiedPrincipalEvidence,
}
impl World {
async fn active() -> Self {
let directory = tempfile::tempdir().unwrap();
let (mailbox, owner) = WorldMailbox::open(directory.path().join("world.cc")).unwrap();
let principal =
VerifiedPrincipalEvidence::new("external-admission-account", Utc::now() + Duration::hours(1));
let receipt = mailbox
.create(
CreateWorldIntent {
id: CommandId::new(),
title: "External Admission".into(),
brief: String::new(),
human_subject_label: "Operator".into(),
narrative_persona_label: Some("Persona".into()),
operational_agent_label: Some("Operational Agent".into()),
targets: BTreeMap::new(),
jurisdictions: Vec::new(),
// An external crate has no library fixture; it states its
// own weights, as every consumer must.
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Patina, 1)])),
era: None,
},
&principal,
)
.await
.unwrap();
for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] {
let revision = mailbox.snapshot().await.unwrap().revision;
mailbox
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: revision,
body,
},
&principal,
)
.await
.unwrap();
}
let world = Self {
_directory: directory,
_owner: owner,
mailbox,
principal,
};
assert_eq!(world.snapshot().await.phase, WorldPhase::Active);
world
}
async fn snapshot(&self) -> WorldSnapshot {
self.mailbox.snapshot().await.unwrap()
}
fn port(&self) -> ControllerPort {
ControllerPort::new(self.mailbox.clone())
}
/// The first opportunity a model controller holds. The human subject's
/// opportunity is not one a controller port may exercise.
async fn controller_opportunity(&self) -> DecisionOpportunity {
self.snapshot()
.await
.opportunities
.into_iter()
.find(|opportunity| opportunity.controller_mode != ControllerMode::Human)
.expect("an activated world derives a model controller's opportunity")
}
/// Everything a commit would move, read through the public surface.
async fn committed(&self) -> (u64, String, Option<String>, usize) {
let snapshot = self.snapshot().await;
let log = self.mailbox.operator_log().await.unwrap();
(
snapshot.revision,
snapshot.state_digest,
snapshot.last_commit_digest,
log.len(),
)
}
}
/// Forging is a `serde` round trip: the value goes out as JSON, a field is
/// replaced, and it comes back as the sealed type. No field of
/// `DecisionOpportunity` needs to be nameable for this to work, which is the
/// whole reason the kernel cannot rely on visibility here.
fn forge(opportunity: &DecisionOpportunity, field: &str, value: Value) -> DecisionOpportunity {
let mut encoded = serde_json::to_value(opportunity).expect("a sealed opportunity serializes");
encoded[field] = value;
serde_json::from_value(encoded).expect("an external crate deserializes a sealed opportunity")
}
fn speak(affordance: ghostlight::AffordanceId, text: &str) -> DecisionInvocation {
DecisionInvocation {
affordance,
bindings: Vec::new(),
proposed: Vec::new(),
speech: Some(Statement::new(text).unwrap()),
display: None,
}
}
/// The control. Without it every rejection below could be an inert harness
/// rather than a refusal: this proves the same port, world, and invocation
/// shape do commit when the opportunity is one the kernel issued.
#[tokio::test]
async fn an_issued_opportunity_commits_through_the_same_port() {
let world = World::active().await;
let opportunity = world.controller_opportunity().await;
let (revision, _, _, events) = world.committed().await;
let receipt = world
.port()
.submit_controller(
CommandId::new(),
&opportunity,
speak(opportunity.affordance_ids[0], "The issued proposal stands."),
)
.await
.expect("an issued opportunity is admitted");
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
let after = world.committed().await;
assert_eq!(after.0, revision + 1);
assert_eq!(after.3, events + 1);
}
#[tokio::test]
async fn a_forged_scope_digest_is_refused_and_commits_nothing() {
let world = World::active().await;
let opportunity = world.controller_opportunity().await;
let before = world.committed().await;
let forged = forge(
&opportunity,
"scope_digest",
json!("sha256:forged-outside-the-crate"),
);
let result = world
.port()
.submit_controller(
CommandId::new(),
&forged,
speak(forged.affordance_ids[0], "Let me in."),
)
.await;
assert!(
matches!(
result,
Err(MailboxError::Kernel(KernelError::ScopeChanged { .. }))
),
"a forged scope digest was not refused: {result:?}"
);
assert_eq!(world.committed().await, before);
}
/// The value the crate's own deleted `ScopeDigest::fixture` used to produce.
/// A `ScopeDigest` is a transparent newtype over a string, so deserializing
/// that string is the whole of what the fixture did, and it is available to
/// any external crate whatever the type's visibility is. What it is not is
/// admission.
#[tokio::test]
async fn a_scope_digest_deserialized_from_a_string_commits_nothing() {
let world = World::active().await;
let opportunity = world.controller_opportunity().await;
let before = world.committed().await;
let forged = forge(&opportunity, "scope_digest", json!("sha256:not-a-scope"));
let result = world
.port()
.submit_controller(
CommandId::new(),
&forged,
speak(forged.affordance_ids[0], "A fixture digest is not a scope."),
)
.await;
assert!(
matches!(
result,
Err(MailboxError::Kernel(KernelError::ScopeChanged { .. }))
),
"a deserialized fixture digest was not refused: {result:?}"
);
assert_eq!(world.committed().await, before);
}
/// `ControllerId` is not even a nameable type outside the crate, and forging
/// one still needs no name: the field is a UUID on the wire. The port stamps
/// the caller from the opportunity it is handed, so a forged controller
/// speaks as itself — and the reducer refuses it because the scope's
/// assignment names someone else.
#[tokio::test]
async fn a_forged_controller_id_is_refused_and_commits_nothing() {
let world = World::active().await;
let opportunity = world.controller_opportunity().await;
let before = world.committed().await;
let forged = forge(
&opportunity,
"controller_id",
json!(uuid::Uuid::new_v4().to_string()),
);
let result = world
.port()
.submit_controller(
CommandId::new(),
&forged,
speak(forged.affordance_ids[0], "I say I am the controller."),
)
.await;
assert!(
matches!(
result,
Err(MailboxError::Kernel(KernelError::ControllerMismatch))
),
"a forged controller ID was not refused: {result:?}"
);
assert_eq!(world.committed().await, before);
}
/// A `SubjectId` minted by deserialization — the kernel's `issue()` is
/// private, and this needs it no more than the wire does. The world derives
/// no opportunity for a subject it never declared.
#[tokio::test]
async fn a_command_naming_a_minted_subject_id_is_refused_and_commits_nothing() {
let world = World::active().await;
let opportunity = world.controller_opportunity().await;
let before = world.committed().await;
let minted: SubjectId = serde_json::from_value(json!(uuid::Uuid::new_v4().to_string()))
.expect("an external crate mints a syntactically valid SubjectId");
let forged = forge(&opportunity, "scope", json!({ "subject_id": minted }));
let result = world
.port()
.submit_controller(
CommandId::new(),
&forged,
speak(forged.affordance_ids[0], "A subject who was never declared."),
)
.await;
assert!(
matches!(
result,
Err(MailboxError::Kernel(KernelError::OpportunityMismatch))
),
"a minted subject ID was not refused: {result:?}"
);
assert_eq!(world.committed().await, before);
}
/// The same for an `AffordanceId`: the opportunity here is entirely genuine,
/// so the forgery is only the affordance the invocation names. Admission is
/// checked against what the world granted, not against what the command
/// claims.
#[tokio::test]
async fn a_command_naming_a_minted_affordance_id_is_refused_and_commits_nothing() {
let world = World::active().await;
let opportunity = world.controller_opportunity().await;
let before = world.committed().await;
let minted: ghostlight::AffordanceId =
serde_json::from_value(json!(uuid::Uuid::new_v4().to_string()))
.expect("an external crate mints a syntactically valid AffordanceId");
assert!(!opportunity.affordance_ids.contains(&minted));
let result = world
.port()
.submit_controller(
CommandId::new(),
&opportunity,
speak(minted, "An affordance nobody granted."),
)
.await;
assert!(
matches!(
result,
Err(MailboxError::Kernel(KernelError::AffordanceDenied))
),
"a minted affordance ID was not refused: {result:?}"
);
assert_eq!(world.committed().await, before);
}
/// A whole opportunity built from JSON alone, naming a world, a scope, a
/// controller and an affordance the kernel never issued. This is the shape
/// the seal's wording is about: the value exists, and admission does not.
#[tokio::test]
async fn a_wholly_deserialized_opportunity_is_refused_and_commits_nothing() {
let world = World::active().await;
let before = world.committed().await;
let uuid = || json!(uuid::Uuid::new_v4().to_string());
let affordance = uuid();
let forged: DecisionOpportunity = serde_json::from_value(json!({
"world_id": uuid(),
"revision": 0,
"scope_digest": "sha256:not-a-scope",
"scope": { "subject_id": uuid() },
"controller_id": uuid(),
"controller_mode": "operational_agent",
"affordance_ids": [affordance],
}))
.expect("an external crate deserializes a whole opportunity");
let result = world
.port()
.submit_controller(
CommandId::new(),
&forged,
speak(forged.affordance_ids[0], "Wholly invented."),
)
.await;
assert!(
matches!(
result,
Err(MailboxError::Kernel(KernelError::OpportunityMismatch))
),
"a wholly forged opportunity was not refused: {result:?}"
);
assert_eq!(world.committed().await, before);
}
/// A forgery indistinguishable in shape from a real digest, because it is a
/// real digest: one the kernel genuinely issued for this scope, gone stale
/// when the world moved under it. Only an exact comparison of the whole
/// digest refuses it; a check of its length or of any prefix would admit it.
/// A stale digest still differs early, so the test also submits the current
/// digest changed in one way each that a weaker comparison would admit: its
/// last digit changed (suffix skipped), one hex letter uppercased (case
/// ignored), and its hex bare or under another label (label ignored).
///
/// Genesis places every subject in one commons, so one controller's speech
/// lands as knowledge on the others, and knowledge is a scope component: the
/// listener's digest moves, the speaker's does not.
#[tokio::test]
async fn a_stale_issued_scope_digest_is_refused_and_commits_nothing() {
let world = World::active().await;
let controllers: Vec<_> = world
.snapshot()
.await
.opportunities
.into_iter()
.filter(|opportunity| opportunity.controller_mode != ControllerMode::Human)
.collect();
let [speaker, stale] = <[DecisionOpportunity; 2]>::try_from(controllers)
.expect("the world declares two model-controlled subjects");
world
.port()
.submit_controller(
CommandId::new(),
&speaker,
speak(speaker.affordance_ids[0], "Everyone in the commons hears this."),
)
.await
.expect("an issued opportunity is admitted");
let current = world
.snapshot()
.await
.opportunities
.into_iter()
.find(|opportunity| opportunity.scope == stale.scope)
.expect("the listener still holds an opportunity");
// The digest is not a public field; it is read the way a consumer reads
// it, off the wire.
let digest_of = |opportunity: &DecisionOpportunity| {
serde_json::to_value(opportunity).unwrap()["scope_digest"]
.as_str()
.expect("a scope digest is a string on the wire")
.to_owned()
};
let (stale_digest, current_digest) = (digest_of(&stale), digest_of(&current));
assert_ne!(
stale_digest, current_digest,
"the speech did not move the listener's scope digest"
);
assert_eq!(stale_digest.len(), current_digest.len());
let before = world.committed().await;
let result = world
.port()
.submit_controller(
CommandId::new(),
&stale,
speak(stale.affordance_ids[0], "Against a scope that has moved."),
)
.await;
assert!(
matches!(
result,
Err(MailboxError::Kernel(KernelError::ScopeChanged { .. }))
),
"a stale issued scope digest was not refused: {result:?}"
);
assert_eq!(world.committed().await, before);
// A stale digest differs from the current one almost everywhere, so it
// cannot tell a whole-digest comparison from one that compares less. Each
// forgery below is the current digest changed in exactly one way that a
// weaker comparison would admit; each asserts that premise first.
let (label, hex) = current_digest
.split_once(':')
.expect("an issued digest is algorithm:hex");
assert_eq!(label, "sha256");
assert_eq!(hex.len(), 64);
assert!(hex.bytes().all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')));
// Only the final hex digit changed: a comparison that skips a suffix.
let mut near = current_digest.clone();
let last = near.pop().expect("a digest is not empty");
near.push(if last == '0' { '1' } else { '0' });
assert_eq!(near.len(), current_digest.len());
assert_ne!(near, current_digest);
// One hex letter uppercased: a case-insensitive comparison.
let letter = hex
.find(|c: char| matches!(c, 'a'..='f'))
.expect("the issued digest has a hex letter to uppercase");
let mut upper = hex.to_owned();
upper.replace_range(letter..=letter, &hex[letter..=letter].to_ascii_uppercase());
let upper = format!("{label}:{upper}");
assert_ne!(upper, current_digest);
assert!(upper.eq_ignore_ascii_case(&current_digest));
// The same hex without its label, and under another label: a comparison of
// the hex alone.
let bare = hex.to_owned();
let relabeled = format!("blake3:{hex}");
for forgery in [&bare, &relabeled] {
assert_ne!(forgery, &current_digest);
assert_eq!(forgery.rsplit(':').next(), Some(hex));
}
for (forgery, what) in [
(near, "one digit from"),
(upper, "one letter's case from"),
(bare, "the unlabeled hex of"),
(relabeled, "the hex under another label of"),
] {
let forged = forge(&current, "scope_digest", json!(forgery));
let result = world
.port()
.submit_controller(
CommandId::new(),
&forged,
speak(forged.affordance_ids[0], "Nearly the real scope."),
)
.await;
assert!(
matches!(
result,
Err(MailboxError::Kernel(KernelError::ScopeChanged { .. }))
),
"a digest {what} the current scope was not refused: {result:?}"
);
assert_eq!(world.committed().await, before, "{what}");
}
}
/// Every stock lens named, with real weights: the shape a consumer's weight
/// control produces, so a refusal below is about the caller and not the value.
fn real_weights() -> LensWeights {
LensWeights::new(BTreeMap::from([
(Lens::Patina, 3),
(Lens::Charter, 1),
(Lens::Ledger, 0),
(Lens::Hearth, 2),
(Lens::Tangle, 1),
(Lens::Veil, 1),
(Lens::Ember, 1),
(Lens::Numen, 1),
]))
}
/// A second verified principal holds a live session and valid weights and is
/// not the owner. The kernel refuses it and nothing commits; the same body
/// from the owner then commits, so the refusal is not an inert harness.
#[tokio::test]
async fn set_lens_weights_from_a_non_owner_is_refused_and_commits_nothing() {
let world = World::active().await;
let snapshot = world.snapshot().await;
let stranger =
VerifiedPrincipalEvidence::new("external-admission-stranger", Utc::now() + Duration::hours(1));
let before = world.committed().await;
let result = world
.mailbox
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: snapshot.world_id,
expected_revision: snapshot.revision,
body: CommandBody::SetLensWeights {
weights: real_weights(),
},
},
&stranger,
)
.await;
assert!(
matches!(
result,
Err(MailboxError::Kernel(KernelError::Unauthorized))
),
"a non-owner replaced the lens weights: {result:?}"
);
assert_eq!(world.committed().await, before);
assert_ne!(world.snapshot().await.lens_weights, real_weights());
let receipt = world
.mailbox
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: snapshot.world_id,
expected_revision: snapshot.revision,
body: CommandBody::SetLensWeights {
weights: real_weights(),
},
},
&world.principal,
)
.await
.expect("the owner replaces the lens weights");
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
let after = world.snapshot().await;
assert_eq!(after.revision, before.0 + 1);
assert_eq!(after.lens_weights, real_weights());
}
/// The owner resubmitting the world's current weights changes nothing
/// canonical, so the kernel refuses it as `NoCanonicalChange` and nothing
/// commits. Admission runs first: the same identical set from a non-owner is
/// `Unauthorized`. A different set from the owner then commits, so neither
/// refusal is an inert harness.
#[tokio::test]
async fn identical_lens_weights_from_the_owner_commit_nothing() {
let world = World::active().await;
let current = world.snapshot().await.lens_weights;
let before = world.committed().await;
let intent = |snapshot: &WorldSnapshot, weights: LensWeights| PrincipalCommandIntent {
id: CommandId::new(),
world_id: snapshot.world_id,
expected_revision: snapshot.revision,
body: CommandBody::SetLensWeights { weights },
};
let snapshot = world.snapshot().await;
let result = world
.mailbox
.submit_principal(intent(&snapshot, current.clone()), &world.principal)
.await;
let Err(MailboxError::Kernel(KernelError::PatchRejected(mismatches))) = &result else {
panic!("the owner's identical lens weights were not refused as no change: {result:?}");
};
assert_eq!(mismatches, &vec![Mismatch::NoCanonicalChange]);
assert_eq!(world.committed().await, before);
let stranger =
VerifiedPrincipalEvidence::new("external-admission-stranger", Utc::now() + Duration::hours(1));
let result = world
.mailbox
.submit_principal(intent(&snapshot, current.clone()), &stranger)
.await;
assert!(
matches!(
result,
Err(MailboxError::Kernel(KernelError::Unauthorized))
),
"a non-owner's identical lens weights were not refused as unauthorized: {result:?}"
);
assert_eq!(world.committed().await, before);
assert_ne!(current, real_weights());
let receipt = world
.mailbox
.submit_principal(intent(&snapshot, real_weights()), &world.principal)
.await
.expect("the owner replaces the lens weights with a different set");
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
let after = world.committed().await;
assert_eq!(after.0, before.0 + 1);
assert_ne!(after.1, before.1);
assert_ne!(after.2, before.2);
assert_eq!(world.snapshot().await.lens_weights, real_weights());
}
/// A lens a weight map does not name weighs zero, so padding a set with zero
/// weights, or dropping its zero weights, spells the same set. Through the
/// public mailbox, in both directions: the world's set is sparse and a padded
/// twin is refused as `NoCanonicalChange`; the world's set is padded and a
/// sparse twin is refused the same way. Each refusal leaves revision, digests
/// and operator log unchanged and the stored spelling as it was. A set that
/// really moves a weight then commits, so the refusals are not an inert harness.
#[tokio::test]
async fn a_lens_set_spelled_with_or_without_its_zero_weights_commits_nothing() {
let world = World::active().await;
let set = |entries: &[(Lens, u32)]| LensWeights::new(entries.iter().copied().collect());
let submit = |weights: LensWeights| {
let world = &world;
async move {
let snapshot = world.snapshot().await;
world
.mailbox
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: snapshot.world_id,
expected_revision: snapshot.revision,
body: CommandBody::SetLensWeights { weights },
},
&world.principal,
)
.await
}
};
let refused_as_no_change = |weights: LensWeights, stored: LensWeights| {
let world = &world;
let submit = &submit;
async move {
let before = world.committed().await;
let result = submit(weights.clone()).await;
let Err(MailboxError::Kernel(KernelError::PatchRejected(mismatches))) = &result else {
panic!("{weights:?} over {stored:?} was not refused as no change: {result:?}");
};
assert_eq!(mismatches, &vec![Mismatch::NoCanonicalChange]);
assert_eq!(world.committed().await, before, "{weights:?} committed");
assert_eq!(world.snapshot().await.lens_weights, stored);
}
};
// Sparse on the world, padded in the command. The world was created with
// `{patina: 1}`.
let sparse = set(&[(Lens::Patina, 1)]);
assert_eq!(world.snapshot().await.lens_weights, sparse);
refused_as_no_change(set(&[(Lens::Patina, 1), (Lens::Charter, 0)]), sparse.clone()).await;
let every = LensWeights::new(
Lens::ALL
.into_iter()
.map(|lens| (lens, u32::from(lens == Lens::Patina)))
.collect(),
);
assert_eq!(every.iter().count(), 8);
refused_as_no_change(every, sparse.clone()).await;
// A real change commits, and stores its own spelling: padded.
let before = world.committed().await;
let padded = set(&[(Lens::Patina, 0), (Lens::Charter, 3)]);
let receipt = submit(padded.clone()).await.expect("moving weight from patina to charter commits");
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
assert_eq!(world.committed().await.0, before.0 + 1);
assert_eq!(world.snapshot().await.lens_weights, padded);
// Padded on the world, sparse in the command.
refused_as_no_change(set(&[(Lens::Charter, 3)]), padded.clone()).await;
refused_as_no_change(
set(&[(Lens::Charter, 3), (Lens::Veil, 0), (Lens::Numen, 0)]),
padded.clone(),
)
.await;
// A set that moves one weight by one is a change.
let before = world.committed().await;
let moved = set(&[(Lens::Charter, 3), (Lens::Numen, 1)]);
submit(moved.clone()).await.expect("adding weight to numen commits");
assert_eq!(world.committed().await.0, before.0 + 1);
assert_eq!(world.snapshot().await.lens_weights, moved);
}
/// Cut 3: `PlayPort` is the play authority's only door, and it is a public,
/// externally constructible type — Dungeon mints exactly one of these in its
/// `AppState`. This is a compile-pass use of the port from outside the crate:
/// it mints quantity through `Mint`, the spelling only `Play` may write, on a
/// resource it declares in the same patch, unconfined and with no answer.
#[tokio::test]
async fn play_port_is_the_only_play_minter() {
let world = World::active().await;
let play = PlayPort::new(world.mailbox.clone());
let holder = world
.snapshot()
.await
.subjects
.first()
.expect("genesis declares at least one subject")
.id;
let patch: WorldPatch = serde_json::from_value(json!({
"declarations": [
{
"type": "entity",
"handle": "loot",
"label": "Ruled Loot",
"kind": "resource",
"container": null,
},
],
"operations": [
{
"op": "mint",
"holder": {"ref": "existing", "value": holder},
"resource": {"ref": "draft", "value": "loot"},
"qty": 5,
},
],
"evidence": [],
}))
.expect("a mint operation, off the wire, decodes into a WorldPatch");
let receipt = play
.submit_patch(CommandId::new(), patch)
.await
.expect("the play authority mints with no answer, unconfined");
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
}
/// A lens name the library does not know cannot be decoded into a command
/// body, beside names it does. This is a serde limit, stated as one: the body
/// never exists, so no kernel admission is being proven here.
#[test]
fn set_lens_weights_with_an_unknown_lens_does_not_decode() {
let refused = serde_json::from_value::<CommandBody>(json!({
"type": "set_lens_weights",
"weights": {"patina": 1, "veil ": 1},
}));
assert!(refused.is_err(), "an unknown lens decoded: {refused:?}");
let accepted = serde_json::from_value::<CommandBody>(json!({
"type": "set_lens_weights",
"weights": {"patina": 1, "veil": 1},
}))
.expect("known lens names decode");
assert!(matches!(accepted, CommandBody::SetLensWeights { .. }));
}

View file

@ -1,16 +0,0 @@
aetheria-verse-catalog.cc was written by Aetheria's own types, not by hand and not by Ghostlight.
Writer: tests/Aetheria.Shared.Tests/VerseGrammarTests.cs, WriteFixture (xunit test
Fixture_writer_is_deterministic_and_emits_what_the_grammar_reader_needs),
which authors VerseGrammar, three VerseVerb and two Faction records through
Aetheria's CultCache types and leaves the file at AETHERIA_VERSE_FIXTURE_PATH.
Aetheria: GameCult/Aetheria origin/master 92b82e9aa5bb422c568c4bfc85a8f641426a41fc
(contains aetheria-release cut verse-grammar, merged at 35af2930).
Command: AETHERIA_VERSE_FIXTURE_PATH=/tmp/aetheria-verse-catalog.cc
dotnet test tests/Aetheria.Shared.Tests
-p:CultLibRoot=<CultLib 45c2f40 clone> -p:CultMathRoot=<CultLib 252e226c clone>
--filter "FullyQualifiedName~Fixture_writer_is_deterministic"
run on Yggdrasil through the verify stopgap (dotnet/sdk:10.0), 2026-10-10.
Content: six records; two writes of the writer agree on content, though not bytes
(CultCache stamps storedAt from the wall clock). Regenerate and diff on content,
never hand-edit.

Binary file not shown.

View file

@ -1,3 +0,0 @@
3
sha256:b706f57cb417603366a1f47a5dd099fbf68bfecc5b2e8d61d281630791d1d76d
sha256:2039956a26c3d5b073d101e5898ac5a60a9eb63a3b93f447b2d8f78ef4caf979

View file

@ -1 +0,0 @@
"a534b32a-4d00-429c-bf6c-ce1d55385380"

View file

@ -1,121 +0,0 @@
schema = "gamecult.idunn.target_declaration.v1"
target = "ghostlight"
source_stamp_environment = "GHOSTLIGHT_BUILD_COMMIT"
# The Dungeon is one binary: the page is compiled into it, so there is no
# adjacent artifact. The connector key is not declared here: the operator
# binding's [workload.secret_files] entry GHOSTLIGHT_CONNECTOR_KEY_FILE is what
# Idunn loads as a systemd credential, and the recipe only names the variable
# that then holds the credential's path.
[[steps]]
id = "test-dungeon"
phase = "test"
runner = "rust-build"
required_environment = ["CARGO_HOME", "HOME"]
argv = ["cargo", "test", "--locked", "-p", "ghostlight-dungeon", "--bin", "ghostlight-dungeon"]
[[steps]]
id = "build-daemon"
phase = "build"
runner = "rust-build"
required_environment = ["CARGO_HOME", "HOME"]
argv = ["cargo", "build", "--locked", "--release", "-p", "ghostlight-dungeon", "--bin", "ghostlight-dungeon"]
[[artifacts]]
id = "ghostlight-dungeon"
source_kind = "runner-output"
runner = "rust-build"
source = "target/release/ghostlight-dungeon"
destination = "ghostlight-dungeon"
executable = true
[service]
executable_artifact = "ghostlight-dungeon"
arguments = [
{ kind = "literal", value = "--state-root" },
{ kind = "binding", name = "state_root" },
]
transport = "http"
route_required = true
required_environment = [
"GAMECULT_IDUNN_CANDIDATE_BIND",
"GAMECULT_IDUNN_PROCESS_WRITE_LEASE",
"GAMECULT_IDUNN_RUNTIME_BUNDLE",
"GHOSTLIGHT_CONNECTOR_ADDR",
"GHOSTLIGHT_CONNECTOR_KEY_FILE",
"GHOSTLIGHT_HEIMDALL_APP_SECRET_FILE",
"GHOSTLIGHT_HEIMDALL_BASE_URL",
"GHOSTLIGHT_ODIN_RUDP",
"GHOSTLIGHT_PUBLIC_APP_URL",
"GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE",
]
optional_environment = [
"GHOSTLIGHT_AUTH_PROVIDERS",
"GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL",
"GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL",
"GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT",
"GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL",
"GHOSTLIGHT_CONTROLLER_PERSONA_MODEL",
"GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL",
"GHOSTLIGHT_PLAY_MODEL",
"RUST_LOG",
]
[service.health]
contract = "ghostlight.cultnet-rudp-service-health"
# Idunn's state kinds are files. The snapshots and timelines slots are
# directories the daemon owns; they are declared as opaque process-owned paths
# (external-file), which Idunn preserves and never interprets.
[state]
schema_generation = "dungeon-v1"
[[state.slots]]
id = "catalog"
relative_path = "catalog.cc"
kind = "cultcache-file"
schema = "ghostlight.dungeon_catalog.v1"
writer = "process-bound-single-writer"
recovery = "preserve"
startup = "create-or-open-after-write-lease"
[[state.slots]]
id = "app-sessions"
relative_path = "service/app-sessions-v2.cc"
kind = "cultcache-file"
schema = "ghostlight.app_session_store.v2"
writer = "process-bound-single-writer"
recovery = "preserve"
startup = "create-or-open-after-write-lease"
[[state.slots]]
id = "snapshots"
relative_path = "snapshots"
kind = "external-file"
schema = "ghostlight.vault_snapshot.v1"
writer = "process-bound-single-writer"
recovery = "rebuildable"
startup = "create-or-open-after-write-lease"
[[state.slots]]
id = "timelines"
relative_path = "timelines"
kind = "external-file"
schema = "ghostlight.world_state.consumer.v6"
writer = "process-bound-single-writer"
recovery = "preserve"
startup = "create-or-open-after-write-lease"
[[provides]]
capability = "ghostlight.world-service"
schema = "ghostlight.world_state.consumer.v6"
compatibility = "consumer-v6"
# Heimdall is found through Odin at use, not declared as an Idunn dependency.
[[dependencies]]
kind = "shared-infrastructure"
capability = "odin.verse-rendezvous"
schema = "odin.verse-topology.v1"
compatibility = "v1"
startup = "before-promotion"

View file

@ -0,0 +1,169 @@
# Call Of The Void Brainstorm
Source: https://docs.google.com/document/d/1YWn5RWsciBxuaQ4l5TN2lAEz4okaQes-aiyx1E9NAxA/edit?tab=t.0
This is a local plaintext import of the scattered Call of the Void brainstorming doc. Treat it as raw source material, not canon. The current compact design note remains E:\Projects\AetheriaLore\Aetheria\Game Design\Call of the Void.md.
## Current Canon Correction
This brainstorm predates a major Aetheria timeline migration.
The old version assumes a colony fleet or exploratory force was shunted into
Elysium and slowly discovers that nobody is going home. That is no longer the
live premise.
Current canon, summarized in
`E:\Projects\AetheriaLore\Aetheria\Worldbuilding\Pre-Elysium\From Sol to Elysium.md`,
is that the FTL trigger sequestered the whole Solar system, with its fleets,
institutions, corporate blocs, uploaded minds, labor systems, histories, and
unresolved social machinery. Elysium is not a remote elsewhere that a fleet
cannot leave. It is the sealed domain into which Sol itself was displaced.
So the useful dramatic pressure is not "can the expedition return home?"
because home came with them. The better pressure is:
- there is no clean outside to return to
- the systems people hoped to escape are trapped in Elysium too
- the old order can no longer rely on the old universe remaining stable around
it
- every faction is trying to define what survival, legitimacy, personhood, and
ownership mean now that Sol's whole inheritance has been exported into the
sealed domain
- Cat's story should turn on the realization that starting over is not escape
when the machinery you fled arrived in the same disaster
The raw notes below remain useful for cases, characters, tones, and comic
cruelty. Treat their old "return home" twist as obsolete pressure, not active
continuity.
---
Potential ideas here, feel free to discuss/deplore/detour in comments.
Protagonist: Catastrophe “Cat” Marrigan, an out of work private investigator, driving a particularly failure-prone space taxi to make ends meet
Overarching plot: Episodic PI cases/random space taxi fares which lead, somewhat circuitously, towards the discovery/revelation that the “exploratory force” had better get used to being “locals”, because the universe is not offering return tickets, and all that follows from that.
What’s Cat’s role in this? And are we going to have alternate endings based on choices made? Ideas, in no particular order:
* She's the original founder/inspiration for the frontier renegades who reject corporate rule and live low-tech and tiny to avoid being crushed.
* The more noir-esque ending, where the disillusioned protagonist sees the way things are going and kills themselves/goes out in a blaze of explosive glory in a futile attempt to change the course of society.
* The out-for-what-you-can-get ending, where she allies with an up and coming power to become a behind the scenes force in future aetheria.
* The really unsatisfying but realistic ending, where the corps take over and life just goes on.
* I sort of like the idea of heading towards a “you can’t win against the capitalist machine, but it’s worth fighting anyway” theme. Thoughts?
case/fares/conversations that exemplify the different ways people react to the point of no return, so to speak, ie: denial, determination to find a way to get back, culty doomsdays types, the “we’re all doomed so let’s party” people, the ones who see great opportunity without old earth holding them back, the people who are determined to do things better this time around (in the ‘we royally screwed up earth, let’s not do it again” sense), etc.
Accidental AI ship whose buggy programming makes them the worst autopilot ever orrrrr…the inciting incident is that in one of her cases/fares gone wrong Cat gets mind-melded with said slightly buggy AI, and that’s how she finds out all those juicy government secrets. Some of them may be inaccurate (see: bad code/failsafes/sabotage), but there’s no way of knowing which without going digging. Plus AI is a one of a kind experimental prototype, which sets all kinds of interesting people on their tail. Also could give us some fun things to do with ship control and actual gameplay quests.
Over the course of the story, one way to show people’s reactions to events could be to have some dialogued characters talking about what they plan to do when they get back home, then use it as a major stress point once the truth is revealed.
Maybe Cat works for a small, kind of terrible PI company, in which case we could get some of our quests from a dispatcher/boss/whatever. I think it’d be a little funny if in true noir fashion, boss was a hard-drinking dude in a trenchcoat, only he’s a really giggly drunk/can’t hold his liquor.
First quest for PI company: find where the boss left a random object after drinking himself to the floor. Find out he left a whole-ass ship somewhere in his drunken stupor.
Another PI quest: investigate the disappearing foodstuffs of a concerned homeowner and find out that a whole nother person was living in the crawlspace above their home and stealing their food. Decide how to deal with Mr Crawlspace.
PI quest: Investigate “ghost” sightings in an old part of a station that’s been shut down. Find out a whole town’s worth of people are living there out of the station’s control slowly siphoning off resources so as not to be noticed. Get some slightly culty vibes from them.
A short quest from an old lady who just wants to have someone over for tea. Turns out if you tolerate her long enough she’ll come in handy during a critical time. Could be she’s either rich or well-connected.
A botanist looking for his daughter. Turns out instead of some sorta protomolecule conspiracy, she’s just wandered off and is being looked after by a kind lady who’s found her.
Get a quest from a mysterious person who is only contacting Cat online, find out eventually the quest giver is some sort of AI who’s either seeking the sweet release of deletion, is looking to find another AI, or is trying to steal some sort of drone so it can go around freely.
Possibly a character who we only see as a remote-controlled drone who helps out at times but we never see the person behind the drone because they use the drone as their public avatar or something. Could be someone who might not otherwise get the chance to go out and about in public because of reasons. This does give them a limited sphere of helpfulness since the drone has to be close enough to the controller to work effectively. Could have Cat mistake the drone for the character, believing it’s some sort of self-sufficient AI driven drone and be sad when it “dies” only to meet it again once it’s re-built and realise there’s a person behind it. Bit like the “pay no attention to the man behind the curtain” bit, could call the drone “Oz”.
Cat is tasked with investigating a mysterious and aggressive band of pirates. Upon finding them it is revealed that they are actually a community of rogue AIs who have no option but to loot technology transports in order to keep themselves alive.
Cat stumbles into a friendship with a shady character, earning the attention of the even shadier Space CIA, which recruits her as a potential double agent with instructions to infiltrate the organization.
Cat is sent to investigate a series of mysterious disappearances of ships sent to mine a gas giant’s belt. Locals consider the place haunted. Turns out it is, by a sentient particle system which considers itself the embodied spirit of the planet.
DLC Area: Cat falls afoul of some sort of anomaly which sends her into a parallel universe with an alternative history. Somehow despite a very different timeline and political situation, everyone she meets is a bizarro mirror of the people she knows from her dimension, and somehow the exact same cast of characters are present despite having very different roles (listen, we can’t afford any extra actors so we’re just gonna use the cast we already have)
Finch is destructively scanning recently deceased human brains and then performing extensive virtual surgery on emulated instances of them in order to create and sell packaged “AI” servitors for specific tasks to compete on the market against AGI products from competitors. The Crew manages to rescue one of the program’s victims while still mostly human, before the process is complete, who [joins the party / is installed on Cat’s ship].
Character: Reginald Moneybags III, inheritor of a massive family fortune, is looking to become a patron of the arts in order to impress his old-money friends. Perhaps they’re the one giving the player their ship?
Might could explore some of Cat’s motivations for taking the ship to Elysium in the first place. Was it by choice? Who has she left behind, if anyone? It would put her in a more conflicted position regarding her role as a double-agent.
* Seems natural that she would be escaping a maze of debt and obligation, only to end up terrifyingly close to falling into the same trap again. I kinda like this idea of completely dumping her whole life and trying to start over somewhere completely different.
* She was caught committing some felony/is railroaded/scapegoated for same/investigated someone way too powerful and was given a choice between prison and joining the colonists.
* Or combine both and bring back the idea of debtor’s prisons/workhouses and have the ship to Elysium be offered as a way out
* So, was she indentured when she arrived only to recently gain the freedom to make her own way, or has she been doing what she’s currently doing since arrival?
The faceless man: a guy? maybe. Wearing a spacesuit or some other obscuring disguise that pops up a little too often for random chance. Is he a red herring? Or is he 10 red herrings in a spacesuit pretending to be a guy? If he has any dialogue let it just be *splashing noises*.
Cat is sent to investigate an urban legend on one other stations--the simply and slightly erroneously historically named “Ripper Lee” who lives in the air vents and steals children. It actually turns out that the missing kids are just exploring the vents as children will and getting macheted by fans or getting stuck or getting pulled into the inertial compensator. [an act II continuation of this quest sees Cat investigating her suspicions that the kids didn’t necessarily go into the dangerous areas of their own impetus, but were lured there. The third act reveals an alien intelligence--though an animal one--a being of energy or something stranger who finds the particular pitch of childrens’ laughter unbearable. Maybe it destructively interferes with its phase, who knows]
The one perpetual drunk who always needs a lift to a different space bar. Cat can go on
a bender with him as a quest, and then have to figure out exactly what the hell happened and why there’s a crash test dummy in the front seat of her taxi.
The person who jumps into Cat’s cab and yells “follow that ship!”. A high octane space chase follows, at the end of which it is revealed they’ve been following the wrong ship, and the Minister of such and such is *very* displeased that he missed his Very Important Meeting for what turns out to be not even an actual assassination attempt.
A carjacking with several different options for resolution
Something strange is going on in the mining operation on PXR 6937, and Cat is sent to find out what: suggestions: the drilling released a substance from the rock that causes hallucinations and paranoia in human brains. Someone is deliberately sabotaging the operation as an environmental protest/act of general rebellion/the mining operation killed someone they cared about and now everyone must feel the same misery
Cat is forced to navigate the pointless bureaucracy of space offices to uncover an embezzlement scheme that conceals something much bigger. What is it? Fuck if I know.
* A furniture selling operation that appears to cover some financial wizardry but turns out to be a human trafficking operation where the names of the items are actually those of missing children OW MY HEART
* A fiendish plan to utilize the combined computing power of thousands of office servers to...mine future bitcoin? Solve something the megas don’t want solved?
Cat’s taxi breaks down somewhere off the beaten path, so to speak, and she finds herself drawn into an ongoing and very brutal feud between two families.
Have a random cab passenger speak in Nemsk and never explain it.
An entire district of a certain station orbiting a strange ocean planet begin to complain of seeing people who could logically never be there. Cat is asked to do a cursory look into it and remains sceptical until one day she starts seeing a person shaped figure always walking just barely out of her line of sight. We could either go full Lem, or subvert this reference by having the reveal be that the air or water are contaminated with a hallucinogenic compound.
A Captain Nemo like figure who flies his rather unusual ship on the far edges of the system. His purpose is unclear, and his identity more so.
Silica storage ruptured, spilling into common area. Now we’re doing the obligatory beach episode! Sand got into the gears of the docking bay so now everyone has to sit back for an afternoon and do anime tropes while it's getting repaired.
What organization is Cat infiltrating?
* People who are trying to go home, even if it costs them the ship or other people’s lives
* Believe the Megas are withholding research on the return trip, trapping everyone in Elysium for profit
* Name ideas
* Home (nice and simple; is it an acronym: H.O.M.E.?)
* A nickname could be the “homies” lmao love it “wassup homie?”
* Terra
* The Terra-rists or Terrists (like a hick would say) Get out no.
* Could be a media nickname (and everyone is really tired of explaining that “no, no, we’re the Alliance for Returning Swiftly Earthward, really” really? Butt jokes? I have never pretended to be above them. Neither have I.
* The Earth-Bound
* The Regressionists
* The Returners (sounds like a ya novel title) true
* The Retrograde Alliance
* Earthers
* The Genesis Project (Project Genesis? Sounds better.) Genesis Faction?
* Alliance for Returning Swiftly Earthward
* Gaia-ists possibly too many vowels
* The Followers of Gaia? Get that good greek mythology I kind of like this one. The Gaia Cult lmao
* Cult of Gaiains, but also yeah, the GaiaCult
* Hades (if we’re going Greek mythology, normal people go to Hades while demigods go to Elysium) Erebus
* Has the bonus “evil” connotation
* Hadesians Perhaps? Like people from there...Hadesites?
* Fits into the sentence “The CIA needs you to infiltrate Hades”
* Though if we’re going for the greek theme, Odysseans might be more apropos with the whole ‘returning home’ I like this for greek references
How do we handle double agent shenanigans?
* Cat grows to sympathise with their goals and philosophy, ends up rejecting the CIA
* Cat comes clean with her new friends, who begin reciting the typical cliche, only to have someone start to read a page that semi-describes events later in the story, like it's a script.

View file

@ -0,0 +1,386 @@
# Aetheria Agent Population Model
This note explains how a socially dense Aetheria region can feel inhabited
without simulating every implied person as a fully persistent agent.
The short answer is that population and agency are not the same thing.
A corridor can imply hundreds of thousands or millions of people while only a
few dozen individuals need to exist as full long-lived social nodes.
## Design Goal
We want a region that feels:
- crowded
- economically alive
- politically pressured
- socially stratified
- full of rumor, labor, traffic, and institutional drag
We do **not** want:
- ten thousand expensive little chatbots idling in a warehouse
- fake scale achieved by silent cardboard extras
- a world where only named characters seem to exist
So the population model needs to separate:
- who exists as a persistent social mind
- who exists as a grouped social force
- who exists only as local scene color
- how offscreen population pressure becomes visible
## Four Population Layers
The MVP should use four layers.
### 1. Persistent Agents
These are the full agents.
They have:
- identity
- memory
- relationships
- goals
- obligations
- changing stance toward institutions and people
These are the characters who accumulate history and can plausibly remember what
happened last week, who lied to them, who saved them, and which institution
just humiliated them.
Examples in an Aetheria content-generation slice:
- a faction liaison
- a ship officer
- a labor organizer
- a corporate handler
- a sanctuary coordinator
- a black-market broker
- a cutout vendor
- a technical specialist with inconvenient loyalties
These are not the population. They are the pressure points where
population-scale systems become legible.
### 2. Cohorts
Cohorts are grouped social bodies that matter but do not need full individual
cognition.
They should represent classes of people whose collective condition can change
over time.
Examples:
- dock labor shifts
- convoy deck crews
- insurer back-office clerks
- sanctuary residents
- clinic queues
- pirate route crews
- private security contractors
- debt pilgrims
- repair-bay technicians
- refugee transit waves
Each cohort should have state such as:
- size
- location
- stress
- trust in institutions
- rumor exposure
- faction sympathy
- fatigue
- scarcity pressure
- protest potential
- desertion / mutiny risk
This is how the world gets to have labor, crowds, queues, shortages, and
unrest without pretending every forklift operator needs a hundred memories and
a private speech cadence.
### 3. Ephemeral Scene Actors
These are temporary people instantiated only when a scene needs bodies,
witnesses, clerks, mechanics, medics, bystanders, or small bits of friction.
They should have:
- a role
- a scene goal
- local awareness of current events
- a little voice
- minimal short-term memory
They should **not** be treated as deep persistent minds by default.
Examples:
- a berth marshal waving traffic through a panic checkpoint
- a frightened passenger arguing with a clerk
- a dockhand spreading a fresh rumor
- a medic triaging one more body than the shift can really handle
- a sanctimonious insurer junior who disappears once the scene ends
If an ephemeral keeps mattering, the system can promote them into a persistent
agent later.
### 4. Ambient Population Pressure
This is the layer that makes the world feel bigger than the visible cast.
It is not represented by people at all. It is represented by signals.
Examples:
- berth queues growing or shrinking
- cargo backlogs
- corridor delay maps
- sanctuary occupancy
- clinic wait times
- food prices
- insurance repricing
- labor slowdown notices
- protest bulletins
- casualty lists
- rescue requests
- media chatter
- tribunal rulings
- route closures
This is where the implied millions live in practice.
## How The Layers Interact
The model should feel like this:
- ambient pressure changes cohort state
- cohort state changes the incentives around persistent agents
- persistent agents make decisions that alter ambient pressure
- ephemeral actors express the local scene consequences
That loop lets a single adjudicator decision or pirate rescue cascade outward
into visible population-level effects without simulating every single person
affected.
## Why A Few Dozen Persistent Agents Is Enough
Because the simulation is not trying to create a census. It is trying to create
a socially legible machine.
In a dense Aetheria slice, one persistent agent can sit at the hinge point for
a great many people:
- one dispatcher affects dozens of ships and hundreds of crew
- one sanctuary coordinator gates a network under pressure from thousands of vulnerable lives
- one corporate official can reshape access, risk, and reputation
- one faction delegate can legitimize or delegitimize a compromise
- one broker can redirect shadow traffic across many dependent cells
The persistent cast is therefore best understood as:
- decision-makers
- bottlenecks
- brokers
- organizers
- interpreters of institutional rules
- people with unusual leverage over larger flows
They are the knots in the rope, not every fiber.
## Cohort Model
Cohorts should be tractable and opinionated.
Each cohort record should include:
- `cohortId`
- `type`
- `sizeBand`
- `region`
- `factionAffinity`
- `currentPressures`
- `resourceDependency`
- `confidence`
- `grievance`
- `discipline`
- `mobilizationPotential`
- `recentIncidents`
Useful cohort types for Aetheria story and content generation:
- dock labor
- ship crews
- sanctuary residents
- corporate workforce
- shadow-market crews
- repair-yard workers
- shadow clinic clients
- private security detachments
- local merchant bodies
- transient passenger pools
Cohorts do not need rich dialogue. They need believable collective reactions.
## Ephemeral Actor Rules
Ephemeral actors should be generated from:
- scene location
- cohort state
- current world pressures
- factional tone
- time of day / shift
That means the same dock concourse can produce different incidental people
depending on whether the corridor is calm, panicking, starving, over-inspected,
or politically inflamed.
Ephemerals should support:
- local exposition
- scene texture
- small moral friction
- witness testimony
- short disputes
- visible consequences
They should expire cheaply unless the world keeps pulling them back into
relevance.
## Promotion Rules
Some ephemerals should be promoted into persistent agents when:
- a player or major agent forms an ongoing relationship with them
- they become central to repeated incidents
- they accumulate leverage or notoriety
- they are the surviving witness to something politically explosive
- they become the face of a cohort-level shift
Promotion is how the world grows specific people organically instead of
requiring the whole cast to be authored up front.
## Population Signals That Make A Place Feel Busy
If the corridor is meant to feel inhabited, the system should constantly
surface signs of offscreen life.
That means scenes, dashboards, and local UI should be fed with things like:
- arrivals and departures
- route advisories
- late manifests
- dockside rumor digests
- occupancy warnings
- strike whispers
- inspection delays
- tribunal alerts
- debt-claim notices
- casualty and rescue numbers
- commodity shocks
- public feeds and scandal bursts
The player does not need to meet everyone. They need to feel surrounded by
consequences.
## Content-Generation Population Recipe
For the first authoring slice, a sensible starting mix is:
- **20-40 persistent agents**
- **10-25 cohorts**
- **0-20 ephemerals per active scene**, generated on demand
Persistent clusters should be chosen from the story context, but the useful
categories are:
- primary faction representatives
- ship or station operators
- labor and logistics figures
- care, sanctuary, or rights workers
- criminal or deniable-economy brokers
- corporate cutouts
- technical specialists
- witnesses with leverage
Cohorts:
- dock labor
- crews
- sanctuary or civilian overflow
- clinic queues
- administrative or inspection staff
- security contractors
- shadow-market cells
- repair techs
- cargo handlers
- passengers / transients
That is enough to make generated scenes feel socially populated without turning
the authoring runtime into a screaming furnace.
## Simulation Tier Mapping
The population layers should map onto the simulation tiers cleanly.
### Tier 0
- dormant persistent agents
- slowly changing cohorts
- coarse ambient indicators
### Tier 1
- active persistent agents making strategic moves
- cohorts shifting under pressure
- route, labor, and sanctuary state updating
### Tier 2
- a handful of persistent agents in scene
- relevant ephemerals generated for the local moment
- cohort state informing mood, risk, and crowd behavior
### Tier 3
- full interactive dialogue for the most relevant persistent agents
- ephemerals only as needed for texture or interruption
- world pressure visible through feeds, queues, alerts, and consequences
This keeps expensive cognition focused where it matters.
## What Not To Do
Do not:
- simulate every resident as a full agent
- let cohorts become inert statistical wallpaper
- use ephemerals as consequence-free decoration
- make named agents behave as if the rest of the world does not exist
- make ambient scale purely visual with no mechanical pressure
That path leads to a world that looks crowded and feels dead.
## Success Criteria
The model is working if:
- the player can feel institutional pressure without being told about it in lore prose
- small decisions by key agents visibly affect larger populations
- cohorts can become restless, relieved, fearful, or politically active
- scenes feel crowded when they should
- the same corridor can feel different under calm, panic, shortage, scandal, or repression
- the named cast feels embedded in a larger society rather than posed in a diorama
The real test is simple:
If the player leaves the room, do they still believe thousands of people are
having a bad day because of what just happened?
If yes, the world is inhabited.

View file

@ -0,0 +1,206 @@
# Aetheria Content Generation Targets
This is the first concrete target note for applying Ghostlight to Aetheria.
The build target is not a standalone corridor simulation or local crisis game
slice. That older shape was fertile story terrain, but it is not the current
product direction. Do not let it shape the runtime unless the user explicitly
revives it.
Ghostlight should first serve two Aetheria uses:
1. content generation inside the **Call of the Void** slice described in the
`AetheriaLore` repository
2. dialogue scaffolding and procedural drama for narrated stories across the
Aetheria timeline
The goal is a story and content-generation organ: a machine that can hold
characters, factions, pressures, memories, masks, and conflict arcs in explicit
state, then project that state into usable scenes, dialogue beats, outlines,
and dramatic complications.
That organ must also hold tone. Aetheria should not be flattened into one dry
technical crisis register. The setting can carry Adams/Pratchett-style
wit-with-stakes, domestic comedy, noir suspicion, horror, wonder, dour poetry,
romance, workplace absurdity, and procedural systems prose, often inside the
same broad canon. The common rule is not "be grim." The common rule is that
tone must reveal character, setting, and consequence.
## Why This Helps Dialogue
Ghostlight should not ask one LLM prompt to "write good character drama" from
vibes. That path produces clever paste: fluent, energetic, and usually a little
dead behind the eyes.
The useful split is:
- Ghostlight builds the drama, narrative pressure, scene setup, and state.
- The dialogue renderer gives each character a constrained local context.
- The character speaks from who they are, what they have endured, what they
want, what they are feeling, what they are hiding, and how they perceive the
person in front of them.
This does not mean every line should sound like emergency procedure. Characters
also speak from routine, fatigue, affection, boredom, private jokes, little
status games, cultural rituals, and ordinary work. Those are not filler; they
are what make later pressure legible.
That means dialogue prompts should be character-local rather than omniscient.
They should include only the state that character plausibly has access to:
- identity and role
- current mood and pressure
- relevant memories
- active goals
- relationship stance toward the listener
- perceived stakes
- cultural or factional scripts
- mask, concealment, or presentation strategy
This lets characters breathe and act inside the scene instead of serving as
mouthpieces for a single plot-generating agent. The agent can shape the drama.
The character projection should preserve subjectivity.
## Primary Use: Call Of The Void Content
Call of the Void should be treated as the first consumer context for Ghostlight,
not as an excuse to build a full social MMO simulation immediately.
The local source of truth is:
- `E:\Projects\AetheriaLore\Aetheria\Game Design\Call of the Void.md`
- `docs/aetheria/call-of-the-void-brainstorm.md` for raw imported brainstorm
material
The slice is a story-first Aetheria scope cut about Catastrophe "Cat" Marrigan:
an out-of-work private investigator making ends meet with a failure-prone space
taxi inside the aftermath of Sol's sequestration into Elysium.
The older brainstorm frames the core twist as a colony fleet or exploratory
force discovering that nobody is going home. That premise is obsolete. Current
Aetheria canon says the FTL trigger displaced the whole Solar system into the
sealed spacetime domain later called Elysium. Home did not stay behind. Home,
with every corporate bloc, labor regime, upload abuse, political failure, and
unresolved compromise, came through too.
So the active Call of the Void pressure should be refactored from "there is no
return ticket" into something meaner and more useful: there is no outside, no
clean restart, and no frontier innocent of Sol's history. Cat can still try to
outrun debt, coercion, legal pressure, or institutional rot, but Elysium proves
that escape exported the machinery instead of dissolving it.
Its useful shape is authored density:
- episodic investigations
- taxi fares as social x-rays
- station districts
- recurring characters
- faction contacts
- campaign consequence
- the social aftermath of realizing Sol's old failures are now Elysium's local
weather
Ghostlight should help generate and manage:
- character dossiers
- faction stances
- relationship tensions
- tonal mode and style targets
- ordinary-life texture before conflict
- scene premises
- dialogue scaffolds
- procedural complications
- continuity-aware reactions
- memory-shaped follow-up scenes
- local cultural and institutional pressure
- case premises and clue chains
- passenger encounters that reveal denial, opportunism, homesickness, fear, or reckless celebration
- continuity pressure from the sealed-domain premise
- cases that expose how old Sol institutions mutate when there is no larger
outside to appeal to
The important thing is that generated content should emerge from structured
state instead of a prompt asking for "dramatic dialogue" and hoping the machine
does not start juggling knives in the pantry.
## Secondary Use: Narrated Timeline Stories
Ghostlight should also support story generation across Aetheria's broader
timeline.
The existing Aetheria stories are tonal evidence. `When We Get Home` makes the
setting legible through jokes, domestic longing, debt, delays, and the slow
recognition that home has moved. `Rain` makes the setting legible through
ritual, memory, sensory repetition, and a patient reversal from wonder to
horror. Future fixtures should be able to choose similarly varied modes instead
of filing every event into one stern technical drawer.
That means it should be able to produce:
- scene outlines
- relationship escalation chains
- factional pressure maps
- alternate dialogue passes
- conflict beats
- character-specific reactions to historical events
- continuity summaries for later story work
This does not require every story to run as a live simulation. Some outputs can
be generated as authoring scaffolds: structured suggestions, scene cards,
argument maps, motive webs, and dialogue skeletons for a human author to shape.
## What Ghostlight Should Build For This
The first useful organs are:
1. canonical agent state schema
2. perceived-state overlay schema
3. relationship and faction stance records
4. event and scene records
5. prompt projection renderer for content generation
6. coordinator/story runtime driven by goals, values, pressure, memory,
continuity, branch flags, and author constraints
7. branch compiler that turns reviewed branch plans into Ink, sidecars,
callbacks, consequence variables, and visual prompt handles
8. IF artifact reviewer that catches decorative choices, fake folds, unused
variables, and missing consequence callbacks
9. dialogue scaffold renderer that preserves stance, mask, and relationship
asymmetry
10. character-local dialogue context packs that restrict each generated voice to
what that character knows, feels, wants, fears, and perceives
The output should be inspectable. The author should be able to see why the
machine thinks a character would deflect, confess, threaten, soften, bargain,
lie, leave, spend a resource, conceal evidence, or make a choice that changes a
later scene.
## What This Is Not
This is not yet:
- a standalone corridor crisis game
- a persistent corridor simulator
- a full MMO social runtime
- a requirement to simulate every offscreen person
- a replacement for authorial judgment
Ghostlight is an authoring and social-state engine first. The live game-shaped
organs can come later if they earn the trouble.
## Success Criteria
The first implementation is useful if it can:
- keep character state distinct from prompt prose
- render dialogue from character-local context rather than global plot vibes
- generate branching dialogue/action scaffolds that reflect relationship history
- create procedural drama from incompatible goals instead of random hostility
- preserve cultural and factional pressure without making clones
- produce story beats a human author can actually use
- make branch choices matter through later affordances, callbacks, visual
modifiers, costs, risks, and endings
- explain its choices in state terms rather than vibes in a rented coat
The real test is not whether the system can improvise a cool scene once. The
real test is whether it can help generate the tenth scene without forgetting
what the first nine did to everyone involved.

View file

@ -0,0 +1,386 @@
# Aetheria Lore Grounding Architecture
Ghostlight needs three different Aetheria modes:
- grounded historical training
- post-Rupture procedural future training
- procedural Elysium generation
Do not blur them. That is how a useful mystery becomes a filing cabinet full of
branch facts with the labels scraped off.
## Core Boundary
Planned Aetheria gameplay takes place in Elysium. What happens there is
intentionally not fully fixed in the lore vault because discovering and shaping
that history is part of the games themselves.
The Aetheria timeline begins when humanity is transplanted into Elysium. It can
restart when humanity destroys itself again through negligence, greed,
institutional capture, civilizational momentum, and the familiar psychological
trash fire wearing a crown.
That means Elysium-era gameplay scenes are not the best first source for
grounded Ghostlight training data. They are downstream procedural territory.
For grounded training data, Ghostlight should start from the authored historical
archive: late Sol, Pre-Elysium institutions, factional flashpoints, personhood
conflicts, labor regimes, political collapse, and the FTL trigger.
That does not mean Ghostlight should avoid Elysium futures. The trained models
will need to handle post-Rupture concepts: Aether, pseudospace, temporal
nonlinearity, spirits, altered substrates, necrotech, mutable bodies, and all
the new ways power learns to monetize miracles while pretending it found ethics
in a drawer.
Elysium future data belongs in a separate lane because its canon is conditional,
not because it is fake. Sol history is a single artifact. Elysium history is a
branching state-space: every possible future is canon inside the branch whose
prior conditions produced it. A generated future must therefore carry branch
lineage, dependencies, and local truth boundaries instead of being treated as
scratch material waiting for permission to matter.
## Revised Architecture
Grounded historical training flow:
```text
Aetheria authored historical lore
-> lore grounding digest
-> historical scene fixture
-> agent-state fixture
-> speaker-local input slice
-> projection artifact
-> prompt_text
-> generated dialogue or drama
-> reviewed training example
```
Procedural Elysium flow:
```text
grounded pre-Elysium priors
-> procedural Elysium branch state
-> Ghostlight agents and institutions
-> projected dialogue and drama
-> simulated branch history
-> branch-local canonical state
```
Post-Rupture future training flow:
```text
authored Elysium concepts and constraints
-> possible future premise
-> procedural branch fixture
-> coordinator plan and projected local contexts
-> generated action, dialogue, and event consequences
-> reviewed future-branch training artifact
-> branch-local canonical history indexed by lineage
```
The first flow teaches the machine what grounded social pressure looks like.
The second and third flows teach it how those pressures mutate under Elysium's
stranger conditions while keeping branch-local canon separate from the Sol
artifact and from sibling Elysium branches.
## Source Priority
For projection training, prefer sources in this order:
1. Authored historical lore with explicit institutional, social, and political
context.
2. Grounded transition material around the FTL trigger and displacement.
3. Historical fiction or scene fragments that remain canon-compatible.
4. Authored post-Elysium concept documents that define altered conditions,
technologies, species, metaphysics, or social pressures.
5. Elysium-era procedural fixtures marked with explicit branch lineage and
conditional truth boundaries.
Call of the Void and Cat/Oz can remain useful for testing projection mechanics,
speaker-local boundaries, and prompt shape. They should not be treated as the
primary linear-history training corpus because their facts belong to Elysium's
conditional branch space.
## Historical Flashpoint Candidates
Good first fixtures should come from parts of Aetheria that are already
pressure-dense and source-grounded:
- contract citizenship and debt regimes
- labor-system enforcement and infrastructure dependency
- upload abuse and contested personhood
- uplift or nonhuman personhood conflicts
- algorithmic governance and predictive policing
- corporate blocs turning infrastructure into leverage
- the FTL program as a political escape hatch from Sol's failure
- the moment around the FTL trigger, where institutions and people discover
that escape did not mean absolution
The best scenes are small, local, and socially loaded:
- a worker negotiating dangerous contract terms
- an upload arguing over continuity, ownership, or service denial
- a technician asked to sign off on an unsafe FTL dependency
- a debtor deciding whether help is relief or capture
- an institutional agent performing compassion while enforcing a machine
- a family, crew, or workplace discovering that political collapse has become
intimate
## Lore Grounding Digests
Before producing training projection examples from a historical flashpoint,
create a lore grounding digest.
The digest format is defined in:
- `docs/architecture/lore-grounding-digest-format.md`
- `schemas/lore-grounding-digest.schema.json`
- `examples/lore-grounding/historical-flashpoint.template.json`
A digest should include:
- source files and relevant line or section notes
- time period
- location or institution
- involved factions, classes, and roles
- material constraints
- local norms, taboos, and scripts
- vocabulary or speech-register cues
- what each speaker plausibly knows
- what each speaker misreads
- author-only context that must not enter prompt text
- open questions needing lore elaboration
It should also include cultural and factional pressure fields:
- internal virtues
- internal shames
- prestige markers
- taboo triggers
- emotional display norms
- trust defaults
- speech register cues
- outsider stereotypes
- factional misread patterns
- role obligations and failure modes
The digest is not a replacement for the lore vault. It is a compiled working
slice for one fixture, so projection examples can cite grounded pressure
without dragging the whole archive into every prompt.
## Fixture Types
Use explicit fixture status:
- `historical_grounded`
- `transition_grounded`
- `procedural_branch`
- `future_branch`
- `branch_lineage_canon`
`historical_grounded` and `transition_grounded` examples can become primary
single-history training data.
`procedural_branch` and `future_branch` examples are canonical inside their own
branch lineage. They are useful for testing, generation, responder training,
coordinator training, and post-Rupture concept coverage, but must not be treated
as facts that also apply to sibling branches or to the Sol artifact.
`branch_lineage_canon` examples are reviewed branch histories whose lineage,
prior conditions, and local state have been made explicit enough to serve as
stable training or gameplay continuity.
Use `future_branch` when the point of the fixture is to explore possible
post-Rupture Elysium outcomes and weird-concept behavior. Use
`procedural_branch` for ordinary gameplay-era branch fixtures whose main job is
scene/runtime testing.
## Projection Rules
Grounded projection examples should prove:
- the prompt text is self-sufficient for the dialogue model
- setting and institutional context are speaker-local
- historical pressure appears as lived constraint, not exposition paste
- the speaker does not know author-only future outcomes
- the generated behavior follows from state, culture, memory, relationship, and
material pressure
If the lore source is too vague for a convincing scene, stop and elaborate the
lore slice first. Do not train the model to pave over missing social reality
with confident fog.
## Post-Rupture Future Branches
Future-branch generation should be deliberate, not a slush pile of glittering
possibilities with no handles.
Each possible future fixture should declare:
- which authored post-Elysium concepts it exercises
- which facts are fixed source constraints
- which facts are generated branch assumptions
- which branch facts are local to this possible future
- which prior conditions make this branch true
- which facts belong to this branch lineage and not to sibling branches
- which generated facts must not leak back into single-history Sol training
- what new social pressure the weird concept creates
- what old pre-Elysium pressure is returning in a new costume
## Attractors, Rails, And Injections
Elysium is a branching state-space, not an undifferentiated fog. Some events may
happen in most branches because the pressures almost always produce them. Some
events may be authored constraints because the game needs a stable enough world
to design around. Some events may be injected by quests or scenario logic when
an active branch reaches a compatible shape.
Use separate labels:
- `branch_attractor`
- `fated_event`
- `tech_order_constraint`
- `quest_injection`
- `branch_local_event`
`branch_attractor` means an event is highly likely under broad pressures but
not absolutely forced. The founding of a faction born inside Elysium may start
here if the social, economic, metaphysical, and institutional gradients make it
show up again and again with local variation.
`fated_event` means the authorial hand is on the scale. The event should occur
unless the branch has explicitly disabled it. Use this sparingly, because too
much fate turns the quantum superposition back into a hallway with rude
wallpaper.
`tech_order_constraint` means discovery order matters. Some technologies,
metaphysical practices, industrial dependencies, or social adaptations should be
unavailable until their prerequisites exist. This is not merely lore flavor; it
is a runtime gate for what quests, economies, factions, and character actions
can plausibly do.
`quest_injection` means authored content enters the active timeline at a branch
point. A quest may require prerequisites, forbid certain prior states, create
new local facts, or push an attractor toward one concrete manifestation.
`branch_local_event` means the event is canonical inside its lineage but has no
special pull across other branches.
Future branch fixtures should record:
- event type from the labels above
- probability or pull strength, for attractors
- required branch prerequisites
- excluded branch states
- technology prerequisites
- faction or institution prerequisites
- quest ids or content hooks, if injected
- local variation allowed
- hard facts created
- branch facts that remain conditional
Future branch fixtures should also emit technology and item manifest candidates
when exploration changes the material economy:
- new item families
- new item variants
- component and subassembly breakdowns
- assembly upgrade surfaces
- technology prerequisites
- faction or manufacturer access
- supply bottlenecks
- salvage, counterfeit, maintenance, and substitution paths
- quest hooks created by scarcity or discovery
See `docs/architecture/technology-item-manifest-plan.md`.
Factions born in Elysium should be modeled through this lens. Adrasteia or Miss
Terri's Sugarrific Snack Company can be represented as pressure-born attractors,
fated institutions, quest-injected branch content, or some combination. The
point is not to decide that once in prose and hope the game remembers. The point
is to make the founding mechanism explicit enough for Ghostlight, the active
timeline, and later game systems to agree on what kind of inevitability they are
dealing with.
Good future branches should stress the model with conditions it cannot learn
from late-Sol history alone:
- Aether as infrastructure, ecology, religion, weapon, medicine, or status good
- pseudospace as transit, concealment, displacement, exile, or labor terrain
- temporal nonlinearity as memory, debt, evidence, grief, insurance, or law
- spirits as persons, tools, contaminants, witnesses, ancestors, or frauds
- necrotech as care, extraction, continuity, punishment, or labor capture
- mutable bodies and species boundaries as liberation, class marker, liability,
taboo, or supply chain
- post-Rupture institutions rebuilding old hierarchies with new miracles
These branches should feed:
- Aetheria responder training, so the model learns post-Rupture assumptions
- coordinator training, so the story runtime can handle weird scene premises
- appraiser and relationship training, so characters misread new phenomena in
socially grounded ways
- institution/faction/consumer training, so economic and political behavior can
respond to miracles as markets, threats, privileges, and dependencies
Keep source provenance strict. A branch can invent a local future, but it should
say what it invented and what branch conditions make it true. The machine may
generate futures under supervision; it does not get to erase the branch index
while everyone is looking at the shiny ghost.
## Operating Doctrine
Ghostlight will generate a lot of Aetheria dialogue, branching scenes, and
training data. That means it will also be the first tool to stress-test many
timeline details at room scale. Treat that as part of the job, not an
exception.
Before writing an Aetheria scene or generating data from one, do a source pass:
1. Check AetheriaLore for the factions, social movements, institutions, species
or body types, location, and time period present in the scene.
2. Extract the material constraints that shape behavior: habitat form,
infrastructure, law, money, route access, labor pressure, class position,
surveillance, body affordances, communication channels, and local failure
costs.
3. Distill those details into the lore grounding digest, agent-state fixture,
projected local context, or Ink sidecar before prompting a response model.
4. Keep the prompt character-local. Source grounding tells Ghostlight what the
room and culture make possible; it does not grant characters omniscience.
5. If the lore does not support a needed concrete detail, do not fill the gap
with confident furniture. Mark the gap, elaborate the AetheriaLore source,
then regenerate or revise the Ghostlight artifact from the patched source.
6. Commit the lore patch in AetheriaLore and cite the source path from
Ghostlight so the training artifact has a clean provenance trail.
The output goal is not only clean training data. It is also playable, readable,
fun interactive fiction that discovers where the worldbuilding is thin by
leaning on it. If Ghostlight needs to know what a sanctuary intake board looks
like to a cetacean Navigator, that is not trivia. That is worldbuilding under
load.
## Lore Gap Policy
When a gap appears, classify it before writing:
- `blocking`: generation would produce wrong bodies, wrong institutions, wrong
authority, or wrong material constraints without the missing detail.
- `safe_to_stub`: the scene can proceed with a clearly marked provisional
detail that does not affect canon-critical behavior.
- `defer`: the detail is decorative and should not enter the prompt yet.
Blocking gaps should be patched in AetheriaLore first. Safe stubs must be
tracked in the digest or sidecar and revisited before promotion. Deferred gaps
should stay out of prompt text so they do not harden by accident.
## Training Boundary
Ground the machine in the past, then generate possible futures under
supervision with branch labels sharp enough that infinity does not show up
wearing one nametag.
Historical fixtures teach single-history social pressure. Future-branch
fixtures teach conditional canon. Cat/Oz-style procedural fixtures teach
runtime mechanics. Those lanes can compare against each other, but they should
not collapse into one unlabeled corpus.

View file

@ -0,0 +1,586 @@
# Aetheria Persistent Agent Architecture
This is the companion document to
[Things To Steal](../research/things-to-steal.md).
For the first concrete target, see
[Aetheria Content Generation Targets](./aetheria-content-generation-targets.md).
For the scaling model that explains how a crowded region can be simulated with
a relatively small persistent cast, see
[Aetheria Agent Population Model](./aetheria-agent-population-model.md).
For the deeper note on how culture, personality distributions, memory, and
perceived state should project into prompts, see
[Agent State Distributions And Prompt Projection](./agent-state-distributions-and-prompt-projection.md).
That document is the theft list. This one is the machine we are trying to build
out of the stolen parts.
The long-horizon target is a persistent world full of in-universe agents who:
- remember what happened
- want different things
- collide with each other because their values and interests do not line up
- interact with humans without collapsing into quest dispensers or therapy plushies
The important bit is that the world should not exist solely to flatter the
player. Humans are participants, not the sun around which every synthetic
little bastard must orbit.
## Design Goals
The near-term target is content generation and story scaffolding, not a
standalone game slice. Ghostlight should first help Aetheria authors generate
dialogue, scene pressure, procedural drama, and character reactions from
explicit social state.
We want a world where:
- agents persist across sessions
- relationships evolve over time
- off-screen life continues
- conflict emerges from incentives
- the same character remains recognizably themselves under pressure
- human intervention can redirect events without erasing everyone else's agency
We do **not** want:
- a thin layer of LLM chat stapled onto static NPC behavior
- every character becoming a slightly differently dressed assistant
- a world that only animates when a human looks at it
- fake drama generated by random hostility instead of meaningful friction
## World Model
The world should be represented as a persistent simulation with five main state
layers:
1. **Canonical world state**
- locations
- factions
- resources
- institutions
- active conflicts
- world-level events
2. **Agent identity state**
- role
- background
- loyalties
- values
- aversions
- appetites
- speech style
3. **Agent dynamic state**
- current location
- current obligations
- current mood / pressure / fatigue
- current social exposure
- short-horizon plans
4. **Relationship state**
- trust
- respect
- resentment
- fascination
- fear
- obligation
- debt
5. **Memory state**
- episodic incidents
- scene summaries
- semantic profile conclusions
- relationship summaries
- active inferred goals and concerns
## Agent Stack
Each agent should be built from explicit layers instead of one giant persona
prompt.
### 1. Identity Layer
Relatively stable facts:
- who they are
- what they believe
- what they want to be seen as
- what they cannot tolerate
- what they are drawn toward
This should be treated as durable but revisable. Identity is not immutable, but
neither should it drift because the model got bored.
### 2. Relationship Layer
Every important other should have a relationship record, including:
- another agent
- a human player
- a group or faction
The record should track:
- trust
- respect
- resentment
- dependence
- attraction or fascination where relevant
- leverage
- recent unresolved incidents
The point is not to create one friendship slider like a life sim from 2004. The
point is to track the actual shape of a social bond.
### 3. Goal Layer
Agents need active goals, not just a biography.
Goals should be:
- private or public
- immediate or long-range
- strategic or emotional
- revisable in response to new information
A goal object should include:
- description
- priority
- time horizon
- emotional stake
- blockers
- dependencies
- known rivals
- likely next moves
### 4. Memory Layer
Memory should be split into:
- **working memory**
- current scene
- immediate context
- active inferences
- **episodic memory**
- timestamped incidents
- where, who, what, consequence
- **scene memory**
- distilled summaries of interactions
- **semantic memory**
- generalized beliefs about self, others, and world
- **relationship memory**
- remembered incidents and inferred patterns tied to a specific other
This is where the current interaction-memory work is directly useful.
### 5. Theory-of-Mind Layer
Each active interaction should have a lightweight scratchpad:
- what the other party likely wants
- what they fear
- what they think is happening
- what they are trying to get from me
- how confident we are about those guesses
This should be ephemeral and revisable. First impressions are useful, but
worshipping them is how systems become smug and stupid.
## Simulation Tiers
A persistent world cannot run every agent at full dialogue fidelity all the
time unless we want to immolate the hardware.
So the world should run on tiers.
### Tier 0: Dormant Persistence
For agents far away from any relevant action:
- maintain location, obligations, and long-horizon goals
- advance the clock coarsely
- update minimal state
### Tier 1: Strategic Tick
For agents in active regions but not in a live scene:
- update goals
- choose broad actions
- move, trade, coordinate, prepare, avoid, investigate
- write compact event records
### Tier 2: Scene Simulation
For agents inside a socially or narratively relevant scene:
- model who is present
- what each actor knows
- what each actor wants
- who is hiding what
- who is under pressure
- resolve short exchanges, negotiations, or conflicts
### Tier 3: Live Interactive Presence
For agents currently engaged with a human or central dramatic scene:
- full dialogue generation
- richer perception and recall
- fine-grained ToM updates
- explicit action selection tied to the live interaction
This tiered model is how we get a world that feels alive without paying for a
small national grid.
## Core Loop
At a high level, each active agent loop looks like:
1. Perceive
- scene state
- nearby actors
- new events
- human input
2. Interpret
- what matters
- what changed
- what this implies for goals and relationships
3. Update internal state
- working memory
- ToM scratchpad
- emotional pressure / stance
4. Retrieve memory
- relevant episodes
- relationship incidents
- semantic conclusions
5. Evaluate goals
- what is threatened
- what is newly possible
- what should take precedence now
6. Choose action
- speech
- movement
- trade
- alliance
- concealment
- refusal
- violence
- delay
7. Commit result
- world state update
- event log
- memory writes
8. Reflect later
- consolidate incidents
- revise relationship state
- revise semantic beliefs
- revise goals
## Relationship Engine
The relationship system should be treated as first-class infrastructure, not
decorative metadata.
Each relationship record should have:
- scores or categorical state for trust, respect, resentment, obligation, fear, fascination
- a short summary of the current relationship
- the unresolved incidents driving that summary
- known pressure points
- current access level
Example consequences:
- low trust + high obligation = brittle alliance
- low respect + high dependence = contemptuous reliance
- high fascination + high fear = unstable orbit
- high resentment + high access = sabotage risk
That is where drama comes from.
## Goal Engine
Goals should be generated and updated from:
- identity
- current needs
- memory
- faction context
- scene opportunities
- rival actions
We should distinguish between:
- **maintenance goals**
- survive
- maintain station
- avoid exposure
- **strategic goals**
- secure influence
- gain a resource
- undermine a rival
- **emotional goals**
- seek vindication
- restore dignity
- protect someone
- punish betrayal
Emotional goals matter because otherwise every character becomes a boring little
optimization engine with no pulse.
## Scene Engine
A scene should be an explicit object, not just "some chat happened."
A scene record should contain:
- location
- participants
- public stakes
- hidden stakes
- triggering event
- current tension axes
- known facts by actor
- unknown facts by actor
- scene outcome
Useful tension axes:
- status
- safety
- secrecy
- leverage
- affection
- ideology
- scarcity
The scene engine should decide:
- whether to escalate
- whether to de-escalate
- whether to fork into violence, bargain, confession, retreat, or deception
## Human Participation
Humans should be one force in the world, not the privileged audience every
character was born to adore.
That means:
- agents should remember human actions
- agents should form durable impressions of specific humans
- agents should change how much they reveal, trust, or tolerate
- agents should be willing to refuse or redirect
- agents should sometimes try to use the human for their own ends
Humans should be able to:
- build alliances
- ruin them
- become symbols
- become liabilities
- become prey
- become confidants
That is much more interesting than "click NPC, receive lore paragraph."
## Narrative Layer
We should not hard-script drama, but we should summarize it.
The narrative layer should:
- generate personal chronicles from actual events
- generate regional or faction news from high-impact changes
- generate rumor propagation when information is partial or distorted
The crucial rule:
- narrative is downstream of simulation
- not a replacement for simulation
## How The Current Supporting Stack Maps To This
The nice part is that some useful scaffolding already exists elsewhere.
Current useful pieces:
- Postgres-backed persistent state
- Qdrant-backed semantic retrieval
- interaction memory with behavioral dimensions
- source and lore indexing
- provider-side tool use
- owner-safe MCP patterns
What needs to be added:
- multi-agent world state store
- relationship graph
- explicit goal objects
- scene scheduler
- reflection/consolidation jobs for cast state
- tiered simulation runtime
- world-facing tools for observation and action
In other words, the existing conversational stack is already halfway to being a
mind-and-memory service. What it lacks is the world model and the cast
scheduler.
## Suggested Data Model
At minimum, the persistent store should grow tables or equivalents for:
- `world_regions`
- `world_events`
- `agents`
- `agent_identity_snapshots`
- `agent_dynamic_state`
- `agent_goals`
- `agent_relationships`
- `agent_memories_episodic`
- `agent_memories_scene`
- `agent_memories_semantic`
- `scene_instances`
- `scene_participants`
- `human_agent_interactions`
- `rumors`
Qdrant or equivalent can remain the retrieval layer for:
- episodic recall
- lore retrieval
- source grounding
- scene similarity
But the canonical social and world state should stay relational and
inspectable.
## Suggested Runtime Services
The world runtime should likely split into:
- **world scheduler**
- advances ticks
- activates scenes
- downgrades inactive agents
- **agent executor**
- runs an agent turn
- retrieves memory
- updates goals and relationships
- **scene resolver**
- handles active multi-party interactions
- **reflection worker**
- consolidates events into longer-term memory
- **narrative worker**
- writes chronicles and reports
That keeps the system legible instead of letting one monstrous worker do all
the thinking and all the plumbing at once.
## Failure Modes To Watch For
### 1. Everyone Becomes The Same Person
The agent voices flatten and all conflict becomes cosmetic.
Countermeasure:
- strong identity layer
- explicit value hierarchy
- personality consistency evaluation
### 2. Memory Becomes Sludge
Everything is stored, nothing is distinguished, retrieval turns to soup.
Countermeasure:
- tiered memory
- write-path filtering
- periodic consolidation
- clear forgetting policy
### 3. Drama Becomes Random Meanness
Characters feel chaotic rather than motivated.
Countermeasure:
- tie conflict to values, history, incentives, and pressure
### 4. Humans Break The World By Existing
Every character over-orients around the nearest player.
Countermeasure:
- keep off-screen goals live
- preserve non-human social gravity
- let humans matter without becoming the axis mundi
### 5. Sycophancy Wears A Costume
The bot sounds spicier but still validates whatever frame the user wants.
Countermeasure:
- explicit anti-sycophancy evaluation
- persistent relationship memory
- boundary-aware response guidance
## Build Order
### Phase 1: Authoring Cast Spine
- explicit agent identity dossiers
- explicit goal objects
- explicit relationship objects
- episodic + semantic memory split
### Phase 2: Dialogue And Drama Scaffolding
- prompt projection for scene and dialogue drafts
- relationship-aware dialogue skeletons
- conflict beat generation from incompatible goals
- author-visible rationale for generated moves
### Phase 3: Social Simulation
- scene objects
- scene scheduler
- relationship updates from scenes
- goal revision from scenes
### Phase 4: Persistent World
- region state
- off-screen strategic ticking
- rumor/news propagation
- faction and economy hooks
### Phase 5: Human Integration
- live player-facing interactions
- persistent human reputation
- access, trust, and consequence systems
### Phase 6: Rich Narrative Surface
- chronicles
- regional reports
- replay and spectator tooling
## The Real Ambition
The ambition here is not "better NPC dialogue."
It is:
- a world with inhabitants
- inhabitants with memory
- memory that changes what they want
- wants that collide
- collisions that produce story
That is the actual prize. Everything else is just wiring and smoke.

View file

@ -0,0 +1,461 @@
# Agent State Distributions And Prompt Projection
This note describes how personality, culture, memory, and social context should
be represented in structured state, and how that state should be projected into
prompts for dialogue generation.
The central rule is simple:
- the prompt is not the source of truth
- the prompt is a temporary projection of deeper state for one turn or one scene
If we try to store the whole person in prompt prose, the system turns back into
theatrical mush. The real machine has to live in explicit state.
For the related notes on personality structure and dialogue classification, see:
- [Personality Model Roadmap](../research/personality-model-roadmap.md)
- [Personality Signal Classifier](../research/personality-signal-classifier.md)
## Core Principle
We should model agents through:
1. canonical latent state
2. perceived state for each agent
3. prompt projection from perceived state into live generation
That gives us:
- stable world truth
- subjective misunderstanding
- efficient live prompting without pretending the prompt is the database
## State Families
Each agent should have explicit state families, not one giant personality blob.
### 1. Underlying Organization
These are deep structural variables:
- self-coherence
- contingent worth
- shame sensitivity
- reciprocity capacity
- mentalization quality
- authenticity tolerance
- mask rigidity
- external-regulation dependence
These are slow-changing and often heavily shaped by early development and
repeated relational history.
### 2. Stable Dispositions
These are relatively persistent tendencies:
- novelty-seeking
- conformity
- status hunger
- risk tolerance
- sociability
- baseline threat sensitivity
- aesthetic appetite
- ideological rigidity
### 3. Behavioral Dimensions
These are first-class, not optional garnish. They belong in the rebuild from
the start:
- interpersonal warmth
- drive
- grandiosity
- validation-seeking
- anxiety
- control pressure
- hostility
- suspicion
- rigidity
- withdrawal
- volatility
- attachment-seeking
- distance-seeking
These are the main handles for social behavior, institutional pressure, and
consumer or factional drift.
### 4. Presentation Strategy
These describe how the self is performed:
- charm
- compliance
- superiority
- detachment
- seductiveness
- competence theater
- moral theater
- strategic opacity
- cultivated harmlessness
- abrasive boundary
- ironic distance
These are not just decorative style. In some agents they are survival
machinery.
### 5. Voice Style
These describe how the performed self comes out in language:
- dryness
- verbal warmth
- formality
- verbosity
- pace
- plainspoken directness
- lexical precision
- technical density
- technical compression
- figurative language
- lyricism
- narrative detail
- emotional explicitness
- pointedness
- self disclosure
- hedging
- certainty marking
- politeness
- coded politeness
- ritualized address
- register switching
- dialect marking
- theatricality
- humor
- conversational dominance
- listening responsiveness
- question asking
- profanity
### 6. Derived Verbal Responses
Defensive verbal moves are derived during projection. The canonical state stores
the pressures and speech mechanics that make those moves likely.
Target emergent behaviors:
- sarcastic deflection can emerge from shame sensitivity, ironic distance,
exposure pressure, suspicion, and a dry or pointed voice
- sincerity evasion can emerge from mask rigidity, low authenticity tolerance,
strategic opacity, and low emotional explicitness
- emotional evasion can emerge from distance-seeking, withdrawal, acute shame,
or control pressure with low self-disclosure
- banter as boundary can emerge from humor, ironic distance, attachment
pressure, and distance-seeking
- verbal aggression can emerge from hostility, perceived status threat,
grievance activation, and abrasive boundary
These are behaviors Ghostlight should be able to produce and test for without
storing them as authored canonical traits.
### 7. Situational State
These are transient activations:
- exhaustion
- scarcity pressure
- humiliation
- panic
- triumph
- grief
- overstimulation
- grievance activation
- acute shame
- perceived status threat
### 8. Relationship State
Per target person, faction, group, product domain, or institution:
- trust
- resentment
- dependence
- fear
- fascination
- obligation
- envy
- moral disgust
- perceived status gap
- expectation of care
- expectation of betrayal
### 9. Goals And Values
- active goals
- protected values
- emotional stakes
- tradeoffs
- unforgivables
## How To Represent Variables
Do not represent most of these as naked scalars if we want culture and history
to shape them properly.
A practical representation is:
- `mean`
- `plasticity`
- `current_activation`
So instead of:
- `status_hunger = 0.72`
use something like:
- `status_hunger.mean = 0.72`
- `status_hunger.plasticity = 0.22`
- `status_hunger.current_activation = 0.89`
This gives us:
- stable baseline personality
- different rates of change
- scene-sensitive activation without rewriting the whole person every turn
Canonical authored state should not include epistemic uncertainty about itself.
If a value is only an observer's read, store it as perceived state rather than
canonical state. Perceived dimensions should not expose canonical `mean` or
`plasticity`; they should track observed activation, attributed disposition,
and confidence. This lets the model represent
fundamental attribution bias: someone can behave a certain way under pressure
and be perceived as simply being that way.
## Culture As A Prior Field
Culture should not create clones. Culture should shape distributions.
For each culture, faction, class stratum, or institution, define:
- prior means over variables
- covariance structure
- reward gradients
- penalty gradients
- preferred masks
- taboo map
- prestige map
- default relationship posture to insiders, outsiders, rivals, inferiors, and superiors
- favored narrative scripts
This means a culture is not "people here are high in trait X."
It is more like:
- this culture rewards controlled presentation
- penalizes spontaneous vulnerability
- elevates status anxiety
- normalizes suspicion of low-status outsiders
- attaches prestige to procedural fluency and emotional composure
That is how a Dominion or Lucent style environment should work: as a field that
shapes what people become profitable or safe enough to be.
## Personal History As A Transform Layer
Culture is only the starting pressure.
Then the prior is transformed by:
- attachment history
- class position
- faction indoctrination
- educational shaping
- labor regime
- remembered humiliations
- remembered betrayals
- remembered rescue, admiration, abandonment, and obligation
So agent state should be read as:
- cultural prior
- transformed by developmental history
- transformed by remembered episodes
- currently activated by scene pressure
## Cohorts And Populations
The same representation can be lifted from individuals to populations.
A colony, district, labor bloc, or consumer cohort can have:
- shared priors
- institutional conditioning
- repeated collective incidents
- relationship state toward factions, employers, media ecosystems, and product classes
This is much better than Big Five-style population sliders because it lets us
model things like:
- prestige hunger
- fear-state compliance
- grievance accumulation
- attachment to institutions
- validation loops induced by media
- suspicion induced by audit or betrayal
That is much closer to Aetheria than a broad trait scaffold alone.
## Canonical State Vs Perceived State
The world should not only track what is true. It should track what each agent
thinks is true.
So we need:
- canonical world state
- canonical agent state
- per-agent perceived state
Perceived state includes:
- what this agent believes about others
- what motives they attribute
- what traits they think they are seeing
- what mask they think someone is wearing
- what threats or opportunities they think are present
This is where emotional intelligence, suspicion, attachment hunger, status
anxiety, and cultural priors distort interpretation.
The acting agent should mostly be prompted from perceived state, not canonical
truth. That is how misunderstanding becomes organic instead of hand-authored.
## Prompt Projection
Prompt rendering should be treated as projection, not storage.
For a live scene, build the prompt from:
### 1. Identity And Role
- who the agent is
- what role they occupy
- what they want to be seen as
### 2. Cultural Default Frame
- prestige rules
- taboo zones
- expected forms of control or intimacy
- factional posture
### 3. Current Presentation Strategy
- how they are trying to appear right now
- what they are concealing
- what they must not look like
### 4. Current Situation
- scene pressure
- public exposure
- scarcity
- humiliation risk
- safety risk
### 5. Relationship Context
- what they think of the other party
- what they need from them
- what wounds or debts are active
- what status relation they perceive
### 6. Relevant Memory
Not full history. Only:
- the few most relevant episodes
- relationship summaries
- current active fears, loyalties, or grievances
- currently salient cultural scripts
### 7. Goals And Constraints
- what they are trying to achieve in this scene
- what they cannot afford
- what values they will not betray
### 8. Listener Model
If the scene involves another agent, include:
- what this agent thinks the other wants
- what they fear the other is doing
- where they may be misreading them
## What The Prompt Should Not Do
Do not make the prompt:
- the sole canonical store of identity
- a full dump of all memories
- a taxonomy recital
- a fake omniscient summary that erases subjective misreading
The prompt should be compact, selective, and scene-bound. The state store
carries the rest.
## Economic Consequences
This model gives us much more useful demand and cultural behavior than old
trait-only systems.
For example:
- high status hunger plus validation-seeking plus fragile self-worth leads toward prestige goods, symbolic upgrades, and visible luxury
- high threat sensitivity plus conformity plus shame reactivity leads toward safety goods, procedural systems, insurance, and respectable signaling
- high drive plus novelty-seeking plus low institutional attachment leads toward frontier gear, gray-market experimentation, and risky migration
- high mask rigidity plus high impression-management intensity leads toward corrective aesthetics, social camouflage, and reputation-maintenance consumption
That is how culture, labor, media, and institutions become market-shaping
forces instead of mere flavor text.
## Recommended Implementation Path
1. Define the state schema with first-class support for:
- underlying organization
- stable dispositions
- all core behavioral dimensions, including `volatility`, `attachment-seeking`, and `distance-seeking`
- presentation strategies
- voice styles
- situational state
- relationship state
- goals and values
2. Represent those variables as priors plus activation, not just fixed scalars.
3. Define cultural and institutional prior templates.
4. Add history transforms from remembered episodes.
5. Add per-agent perceived state overlays.
6. Build prompt renderers that project perceived state into live generation.
7. Keep canonical state, perceived state, and prompt projection cleanly separated.
## Bottom Line
The right machine is not:
- a persona prompt with some adjectives taped to it
- a canonical trait sheet with no cultural shaping
- a direct line from "personality value" to dialogue
The right machine is:
- latent state distributions
- shaped by culture
- reshaped by history
- distorted by perception
- projected into prompts for one scene at a time
That gives us agents who can feel culturally situated, personally scarred,
socially biased, and dynamically alive without making the prompt carry the
whole civilization on its back.

View file

@ -0,0 +1,273 @@
# Agent State Variable Glossary
This document explains the current v0 Ghostlight state variables. It is the
human-facing companion to:
- `schemas/agent-state.schema.json`
- `schemas/agent-state.required-fields.json`
- `examples/agent-state.call-of-the-void.json`
The schema is not pretending this vocabulary is final. It is a first stable
core: enough shared axes to compare characters, build prompt projection, and
avoid turning every new scene into a bespoke little fog machine.
## Variable Components
Canonical scalar-like state variables use three numeric components.
| Field | Meaning |
| --- | --- |
| `mean` | The baseline tendency or long-run level for this variable. A high `mean` means this trait, strategy, pressure, or stance is normally strong for the agent. |
| `plasticity` | How easily this variable can change. High plasticity means the value can move quickly under events, relationships, culture, or scene pressure. Low plasticity means it is entrenched. |
| `current_activation` | How active the variable is right now, in this scene or current state. This can spike above or fall below the baseline without rewriting the agent. |
Example:
```json
{
"mean": 0.35,
"plasticity": 0.2,
"current_activation": 0.9
}
```
This means the agent is not generally high in the variable, the baseline is not
very easy to change, but the variable is strongly activated right now.
Translation: this is a situation, not a personality transplant.
Canonical character state does not include `certainty`. If a generated or
imported profile is provisional, track that in workflow provenance, draft
status, imported-source notes, or review status.
Perceived state uses a different shape because observers do not know canonical
baseline or plasticity. They see behavior, then often treat that behavior as
evidence of what the target is like.
```json
{
"observed_activation": 0.9,
"attributed_disposition": 0.7,
"confidence": 0.4
}
```
| Field | Meaning |
| --- | --- |
| `observed_activation` | How strongly the observer thinks the target expressed the dimension in the observed event or scene. |
| `attributed_disposition` | How much the observer generalizes from the observed behavior into "this is what the target is like." |
| `confidence` | How strongly the observer trusts this read. This is where evidence strength, emotional investment, prejudice, relationship stakes, prior memory, and social reinforcement show up. |
This models fundamental attribution bias directly. A character can see someone
behave coldly during a crisis and conclude "they are cold," not "they were
activated toward distance under exceptional pressure." Correcting that
impression takes work because the observer's confidence is supported by memory,
emotion, stakes, prior assumptions, and social reinforcement.
Perceived overlays may use structured belief metadata such as subject, claim
type, evidence events, visibility, and emotional charge. That metadata is not
canonical certainty. It describes why a specific observer trusts a specific
read.
## Label Set Policy
The labels in `agent-state.required-fields.json` are the required v0 core,
not per-character tags. They cover the axes Ghostlight currently treats as
first-class.
The validator requires each canonical agent fixture to include the full core
set so agents can be compared on the same axes. That means Cat's example does
not contain only labels that apply strongly to Cat. It contains all required
labels, with low values for weak or inactive axes and high values for strong or
activated axes.
Variable maps may still grow extra labels where a character, culture, or story
needs them. Do not promote a new label into the required core until it has
proved broadly useful across multiple characters or scenes. Otherwise the
schema becomes a junk drawer with a badge.
## Underlying Organization
| Label | Meaning |
| --- | --- |
| `self_coherence` | How integrated and stable the agent's sense of self is under pressure. |
| `contingent_worth` | How much the agent's felt worth depends on approval, utility, status, purity, or external validation. |
| `shame_sensitivity` | How painful exposure, correction, failure, or diminishment feels. |
| `reciprocity_capacity` | Ability to recognize and sustain mutual obligations rather than purely extractive or avoidant relations. |
| `mentalization_quality` | Ability to model other minds with nuance instead of flattening them into crude threat, need, or utility categories. |
| `authenticity_tolerance` | Capacity to be known without immediately retreating into performance, control, or concealment. |
| `mask_rigidity` | How necessary and inflexible the performed self is. High values mean the mask is load-bearing. |
| `external_regulation_dependence` | How much emotional stability depends on other people, institutions, substances, scripts, or external structures. |
## Stable Dispositions
| Label | Meaning |
| --- | --- |
| `novelty_seeking` | Attraction to new experience, strange opportunities, and unproven paths. |
| `conformity` | Preference for accepted norms, procedures, and group expectations. |
| `status_hunger` | Desire for rank, recognition, prestige, or visible superiority. |
| `risk_tolerance` | Willingness to accept danger, uncertainty, or loss for gain or freedom. |
| `sociability` | Baseline draw toward company, conversation, networks, and social energy. |
| `baseline_threat_sensitivity` | Default readiness to detect danger, exploitation, betrayal, or humiliation. |
| `aesthetic_appetite` | Sensitivity to beauty, style, taste, symbolic form, or expressive environment. |
| `ideological_rigidity` | Resistance to revising beliefs, myths, doctrines, or explanatory frames. |
## Behavioral Dimensions
| Label | Meaning |
| --- | --- |
| `interpersonal_warmth` | Tendency to express care, friendliness, affection, or social welcome. |
| `drive` | Goal pressure, persistence, ambition, and forward force. |
| `grandiosity` | Inflated self-importance, entitlement, exceptionalism, or self-mythologizing. |
| `validation_seeking` | Need for reassurance, approval, recognition, or confirmation of worth. |
| `anxiety` | Anticipatory fear, worry, nervous vigilance, or instability under uncertainty. |
| `control_pressure` | Urge to manage people, situations, information, or outcomes tightly. |
| `hostility` | Readiness toward anger, contempt, attack, punishment, or antagonism. |
| `suspicion` | Expectation that others hide motives, threats, traps, or bad faith. |
| `rigidity` | Difficulty adapting behavior, interpretation, or plans under new evidence. |
| `withdrawal` | Tendency to disengage, retreat, shut down, or reduce availability. |
| `volatility` | Speed and intensity of emotional swings or escalation. |
| `attachment_seeking` | Pull toward closeness, reassurance, fusion, privileged access, or being chosen. |
| `distance_seeking` | Push toward space, opacity, autonomy, and reduced emotional claim from others. |
## Presentation Strategy
Presentation strategy describes the self being performed. This is not identical
to voice style. It is the social face, mask, posture, or survival presentation
the agent is trying to maintain.
| Label | Meaning |
| --- | --- |
| `charm` | Performs warmth, ease, charisma, or pleasantness to influence or smooth contact. |
| `compliance` | Performs agreement, submission, helpfulness, or nonthreatening cooperation. |
| `superiority` | Performs being above others, more competent, more refined, or less vulnerable. |
| `detachment` | Performs cool distance, emotional unavailability, or not-needing. |
| `seductiveness` | Performs desirability, invitation, or intimate leverage. |
| `competence_theater` | Performs capability and control, sometimes beyond what is actually secure. |
| `moral_theater` | Performs righteousness, purity, sacrifice, or ethical authority. |
| `strategic_opacity` | Controls what others can know; hides motives, pain, dependency, or plans. |
| `cultivated_harmlessness` | Performs being safe, small, useful, cute, or beneath concern. |
| `abrasive_boundary` | Performs difficulty, bite, or unpleasantness to keep others from pressing closer. |
| `ironic_distance` | Performs irony, detachment, or joking distance to avoid naked sincerity. |
## Voice Style
Voice style describes how the performed self comes out in language. The v0
required vector covers broad communication mechanics, not only the most obvious
quirks in the current examples.
| Label | Meaning |
| --- | --- |
| `dryness` | Understated, deadpan, low-sentiment phrasing. |
| `verbal_warmth` | Inviting, affectionate, reassuring, or socially soft phrasing. |
| `formality` | Uses formal structure, titles, careful address, or institutionally correct phrasing. |
| `verbosity` | Tends toward longer turns, elaboration, qualification, or verbal sprawl. |
| `pace` | Moves quickly through turns, interruptions, replies, or topic shifts. |
| `plainspoken_directness` | Speaks plainly, concretely, or bluntly rather than ornamenting or obscuring. |
| `lexical_precision` | Chooses exact words, distinctions, definitions, or careful terms. |
| `technical_density` | Packs speech with specialist terms, systems language, procedure, or analysis. |
| `technical_compression` | Compresses technical meaning into terse expert shorthand. |
| `figurative_language` | Uses metaphor, image, analogy, poetic compression, or symbolic framing. |
| `lyricism` | Uses musical, poetic, sensuous, or rhythmically heightened language. |
| `narrative_detail` | Explains through context, sequence, anecdote, or concrete scene detail. |
| `emotional_explicitness` | Names feelings, needs, wounds, affection, fear, or attachment directly. |
| `pointedness` | Cuts directly, sharply, or with barbed precision. |
| `self_disclosure` | Volunteers personal history, inner state, motives, or private stakes. |
| `hedging` | Softens claims with uncertainty markers, caveats, deference, or exits. |
| `certainty_marking` | Signals confidence, finality, authority, or refusal to leave claims open. |
| `politeness` | Uses courtesy, mitigation, face-saving language, or social smoothing. |
| `coded_politeness` | Uses polite phrasing to imply criticism, threat, refusal, hierarchy, or hidden meaning. |
| `ritualized_address` | Uses formulaic greetings, titles, honorifics, oaths, prayers, or ceremonial phrases. |
| `register_switching` | Shifts between speech registers depending on audience, status, danger, or role. |
| `dialect_marking` | Shows regional, class, occupational, subcultural, or community-specific speech markers. |
| `theatricality` | Performs speech with heightened drama, staging, persona, flourish, or rhetorical display. |
| `humor` | Uses jokes, wit, absurdity, teasing, or comic framing as a regular speech tool. |
| `conversational_dominance` | Takes, holds, redirects, or controls conversational floor and agenda. |
| `listening_responsiveness` | Reflects, tracks, validates, or adapts to what the other person just said. |
| `question_asking` | Uses questions to probe, invite, corner, teach, test, or keep the other person talking. |
| `profanity` | Uses taboo, vulgar, sacred, or deliberately coarse language. |
## Derived Verbal Responses
Defensive verbal moves are projection outcomes, not canonical labels. A renderer
can derive sarcasm, sincerity evasion, emotional evasion, banter-as-boundary, or
verbal aggression from the interaction between active state families.
Examples:
| Response | Common active-state pattern |
| --- | --- |
| Sarcastic deflection | High shame sensitivity, ironic distance, threat sensitivity, and exposure pressure through a dry or pointed voice. |
| Sincerity evasion | Low authenticity tolerance, high mask rigidity, strategic opacity, and low emotional explicitness. |
| Emotional evasion | High distance-seeking, withdrawal, acute shame, or control pressure with low self-disclosure. |
| Banter as boundary | High ironic distance, humor, attachment pressure, and distance-seeking in the same scene. |
| Verbal aggression | High hostility, perceived status threat, grievance activation, and abrasive boundary. |
Treat these as target emergent behaviors for projection tests. They are useful
because the system should produce them under the right pressures, not because
they deserve their own canonical storage slot.
## Situational State
| Label | Meaning |
| --- | --- |
| `exhaustion` | Current depletion, fatigue, overuse, or low reserve. |
| `scarcity_pressure` | Pressure from money, supplies, access, time, space, safety, or opportunity being scarce. |
| `humiliation` | Current felt diminishment, exposure, embarrassment, or status wound. |
| `panic` | Acute fear, urgency, overwhelm, or threat response. |
| `triumph` | Current victory, vindication, high confidence, or emotional lift. |
| `grief` | Active loss, mourning, sorrow, or ache. |
| `overstimulation` | Current sensory, social, cognitive, or emotional overload. |
| `grievance_activation` | Active resentment, injustice memory, or retaliatory moral charge. |
| `acute_shame` | Immediate shame flare, exposure pain, or self-disgust. |
| `perceived_status_threat` | Current sense that rank, dignity, competence, or face is under threat. |
## Relationship Stance
Relationship stance is directional. A `source_id -> target_id` record describes
how the source feels and predicts the target, not a shared relationship object.
Reciprocal records can disagree.
| Label | Meaning |
| --- | --- |
| `trust` | Expectation that the target will not exploit vulnerability or act in bad faith. |
| `respect` | Recognition of competence, integrity, status, or seriousness. |
| `resentment` | Accumulated grievance, bitterness, or unpaid emotional debt. |
| `dependence` | Need for the target's resources, care, access, protection, or recognition. |
| `fear` | Expectation that the target can or will cause harm. |
| `fascination` | Captivation, curiosity, attraction, fixation, or unresolved interest. |
| `obligation` | Felt debt, duty, promise, or responsibility toward the target. |
| `envy` | Pain around what the target has, is, receives, or represents. |
| `moral_disgust` | Aversion rooted in perceived violation, corruption, cruelty, or wrongness. |
| `perceived_status_gap` | Felt difference in rank, leverage, dignity, or social position. |
| `expectation_of_care` | Belief that the target may protect, soothe, support, or choose the source. |
| `expectation_of_betrayal` | Belief that the target may abandon, expose, exploit, or turn. |
## Cat Fixture Policy
Cat's example fixture currently includes all required core labels for Cat and
Oz. It is not a sparse profile of only traits that apply to them.
That is deliberate for v0:
- complete vectors make comparison and validation easier
- low `mean` values are meaningful
- low `current_activation` values tell the renderer not to emphasize a variable
Later, Ghostlight may support sparse authoring overlays for convenience. The
canonical fixture should remain explicit until we have enough tooling to avoid
silent defaults becoming accidental canon.
## Event Interpretation
Events may carry three optional interpretation layers:
| Field | Meaning |
| --- | --- |
| `observed_exchange` | What was externally observable: who acted or spoke, what they seemed to do, and the visible cues. |
| `private_interpretations` | How each participant appraised the event from their own partial state. |
| `event_effects` | The proposed consequences: state deltas, new beliefs, or memory updates caused by the event. |
These fields are immediate scaffolding for projection. They do not yet define a
complete transition engine. For now, they make important scene history legible
enough that a prompt projector can explain why a later line bends toward trust,
evasion, curiosity, fear, or repair.

View file

@ -0,0 +1,244 @@
# Canonical Agent State Schema
Ghostlight's first runtime organ is a state contract, not a generator.
The schema lives in:
- `schemas/agent-state.schema.json`
- `schemas/agent-state.required-fields.json`
The first example lives in:
- `examples/agent-state.call-of-the-void.json`
The label and numeric glossary lives in:
- `docs/architecture/agent-state-variable-glossary.md`
## Objective
The schema defines the minimum state Ghostlight needs before it can safely build
prompt projection, dialogue scaffolding, classifier records, or procedural
drama.
The core rule is unchanged:
- canonical state is what the world treats as true
- perceived state is what a specific observer thinks is true
- dialogue context packs are character-local projections for one speaker in one
scene
If these layers collapse into each other, the machine turns back into one
omniscient narrator with a pocket full of vibes. This is a known industrial
hazard. We are wearing goggles now.
## State Families
Each agent has:
- `identity`
- `canonical_state`
- `goals`
- `memories`
- `perceived_state_overlays`
`canonical_state` is split into:
- `underlying_organization`
- `stable_dispositions`
- `behavioral_dimensions`
- `presentation_strategy`
- `voice_style`
- `situational_state`
- `values`
Each canonical scalar-like dimension is represented as:
```json
{
"mean": 0.5,
"plasticity": 0.5,
"current_activation": 0.5
}
```
This keeps baseline, change rate, and scene activation separate.
A person can be dispositionally suspicious without being maximally suspicious
in every scene. A person can be highly activated right now without rewriting
their whole soul because someone coughed near a status wound.
Canonical variables do not include confidence or certainty. Perceived variables
do not expose canonical `mean` or `plasticity`; they store observed activation,
attributed disposition, and confidence.
For full meanings of canonical `mean`, `plasticity`, `current_activation`,
perceived attribution fields, and every required v0 label, see
`docs/architecture/agent-state-variable-glossary.md`.
## Required First-Class Dimensions
`schemas/agent-state.required-fields.json` names the required core variable
families. The validator enforces those fields for canonical agent state and
relationship stance.
The required core is not exhaustive. It is the shared comparison surface. A
character fixture currently includes all required labels, even when many are low
or inactive, so downstream tooling can compare agents without guessing whether a
missing value means "not applicable," "forgotten," or "quietly eating the
floorboards."
The behavioral dimensions include the known must-not-drop set:
- `volatility`
- `attachment_seeking`
- `distance_seeking`
Those are not garnish. They are load-bearing social handles.
## Presentation, Voice, And Response
`presentation_strategy` describes the self being performed.
That can include charm, detachment, competence theater, cultivated
harmlessness, or deliberately performing someone who is abrasive or difficult.
Sometimes that abrasive performance is not random meanness. It is a boundary,
a threat display, a way to prevent intimacy, or a test to see who flinches.
Human beings are regrettably efficient little porcupines.
`voice_style` describes how that performed self comes out in language.
The required voice handles are:
- `dryness`
- `verbal_warmth`
- `formality`
- `verbosity`
- `pace`
- `plainspoken_directness`
- `lexical_precision`
- `technical_density`
- `technical_compression`
- `figurative_language`
- `lyricism`
- `narrative_detail`
- `emotional_explicitness`
- `pointedness`
- `self_disclosure`
- `hedging`
- `certainty_marking`
- `politeness`
- `coded_politeness`
- `ritualized_address`
- `register_switching`
- `dialect_marking`
- `theatricality`
- `humor`
- `conversational_dominance`
- `listening_responsiveness`
- `question_asking`
- `profanity`
Behavioral warmth and verbal warmth are intentionally separate:
- `behavioral_dimensions.interpersonal_warmth` is the tendency to offer care,
welcome, or affiliation.
- `voice_style.verbal_warmth` is the language surface that can sound soft,
reassuring, affectionate, or socially inviting.
So Cat's prickliness is not only a dialogue prompt instruction. It is backed by
canonical state:
- high `presentation_strategy.abrasive_boundary`
- high `presentation_strategy.ironic_distance`
- high `underlying_organization.shame_sensitivity`
- high `underlying_organization.mask_rigidity`
- high `behavioral_dimensions.distance_seeking`
- high `behavioral_dimensions.suspicion`
- high `situational_state.acute_shame` when exposed
The renderer derives defensive speech from those intersections plus voice
style. A dry, pointed voice under shame and exposure pressure may produce
sarcastic deflection; the schema does not store sarcasm-as-defense as its own
canonical organ.
Sarcastic deflection, sincerity evasion, emotional evasion,
banter-as-boundary, and verbal aggression remain target emergent behaviors for
projection tests.
## Perceived State
Perceived overlays are observer-specific. They do not replace canonical state.
An overlay records:
- observer
- target
- perceived dimensions, including observed activation and attributed disposition
- beliefs
- distortions
This is where misunderstanding lives. Suspicious agents can overread threat.
Attachment-hungry agents can overread interpersonal warmth. Avoidant agents can
underread care. Fundamental attribution bias also lives here: an observer can
mistake exceptional behavior for stable character. None of that requires
corrupting the canonical state.
Relationship stance is directional. If Cat has a relationship record toward Oz,
Oz needs a separate record toward Cat. Mutual presence does not imply symmetric
trust, fear, obligation, dependence, or expectation of betrayal.
## Event Interpretation
Events can include optional interpretation scaffolding:
- `observed_exchange` for externally visible action or dialogue
- `private_interpretations` for each participant's appraisal of what happened
- `event_effects` for proposed state deltas, belief creation, and memory updates
This is not a full social transition engine yet. It is enough structure for the
projection layer to know what an event changed without asking later prompts to
infer everything from a one-line summary and a bad attitude.
## Dialogue Context Packs
Scenes contain `dialogue_context_packs`.
A pack is a character-local prompt payload for one speaker. It includes:
- speaker-local truth
- speaker beliefs
- active memories
- active goals
- presentation constraints
The point is not to make the dialogue generator smarter by shouting plot at it.
The point is to keep each character inside their own partial reality.
Packs are positive-context payloads: if the speaker should not know something,
it is not included. Secrets the speaker does know but wants to withhold belong
in goals, memories, beliefs, and presentation constraints.
Ghostlight can build the trap. The character projection decides how the person
inside the trap breathes.
## Current Validation
The first validator is intentionally small and dependency-free:
- `tools/validate_agent_state.py`
It does not implement all of JSON Schema. It checks the invariants Ghostlight
currently cares about:
- example files parse as JSON
- schema versions match
- agent IDs are unique
- required canonical variable groups are present
- required relationship stance fields are present
- state variable components stay in `0..1`
- goals, memories, relationships, scenes, and dialogue context packs reference
existing IDs
- dialogue packs carry speaker-local context without requiring negative
author-only fences
This gives us a real seam before we build the prompt renderer. Not perfect.
Useful. We are allowed to be both.

View file

@ -0,0 +1,81 @@
# Corpus Coverage Ledger
The corpus coverage ledger is the project-level index for accepted and planned
Aetheria training fixtures.
Its job is not to store story content. Its job is to keep the corpus honest:
which factions, movements, flashpoints, timeline lanes, tonal modes, collision
axes, review states, and item/economy hooks are represented, and which are still
missing.
## Live Files
- Ledger: `state/corpus-coverage.json`
- Schema reference: `schemas/corpus-coverage.schema.json`
- Validator/status tool: `tools/validate_corpus_coverage.py`
- Command: `npm run coverage:status`
## Entry Contract
Each fixture entry records:
- `fixture_id`: stable fixture handle.
- `status`: `planned`, `draft`, `accepted_as_draft`, `accepted`,
`needs_revision`, `rejected`, or `superseded`.
- `timeline_lane`: `historical_grounded`, `transition_grounded`, or
`future_branch`.
- `canon_status`: single-history, branch-local, promoted branch, template, or
draft status.
- `story_type`: founding-era, day-in-the-life, flashpoint, movement,
future-branch, or trade-life story.
- `primary_subjects` and `secondary_subjects`: factions, movements,
institutions, species/body groups, or other represented subjects.
- `collision_axes`: the pressures the fixture exercises, such as law, labor,
care, class, logistics, species/body affordance, trade, memory, personhood,
technology, legitimacy, or infrastructure.
- `tonal_modes`: prose modes the fixture contributes to the corpus.
- `training_targets`: organs or reference surfaces this fixture is relevant to.
- `training_usability`: explicit per-stage declaration of whether the fixture
is `training_ready`, `reference_only`, or `not_training_data`.
- `artifacts`: paths to fixture files.
- `review`: status of schema, narrative, lore, spatial, visual, and IF review.
- `economy_hooks`: item, assembly, trade-good, supply-chain, or tech hooks.
- `open_lore_gaps`: blocking or useful gaps discovered during generation.
## Acceptance Rule
An accepted or accepted-as-draft fixture must have the core artifact refs:
- lore digest
- agent state
- coordinator artifact
- Ink file
- training sidecar
It must also carry review fields for schema, narrative, lore, spatial, visual,
and IF artifact review. A fixture may still be accepted-as-draft with review
caveats, but the caveats should be visible instead of hidden under the nice rug.
Coverage status is not training readiness. A fixture that looks good as a story
can still be unusable for a model stage if it lacks exact input/output receipts,
raw outputs, reviewer decisions, hidden-context audits, or mutation records in
the shape that stage requires. The ledger should be rude about this. If a
fixture is only a reference for story shape or grounding, mark it
`reference_only`; do not promote it by implication.
## Report Shape
`npm run coverage:status` validates the ledger and prints:
- total entries and accepted count
- progress toward the 100-150 broad target
- status, timeline lane, story type, collision-axis, tonal-mode, and subject
counts
- training-usability counts
- major-power founding/day-in-life candidates when present
- basic gap signals, such as missing future-branch coverage or no day-in-life
stories yet
This is deliberately a coarse instrument. It should tell us where to point the
next fixture without pretending to be a corpus scientist in a lab coat made of
spreadsheet tabs.

View file

@ -0,0 +1,102 @@
# CultNet Shared Persona-State Contract
Ghostlight no longer treats `ghostlight.agent_state.v0` as the cross-runtime
person-state contract. That schema still belongs here, but it owns scene,
world, relationship, event, and dialogue-context state for storytelling.
The portable person-shaped contract is now `gamecult.persona_state.v0`.
## Canonical Payload
The shared payload contract is:
- schema id:
`https://gamecult.dev/cultnet/gamecult.persona_state.v0.schema.json`
- schema version:
`gamecult.persona_state.v0`
- Ghostlight mirror:
`schemas/gamecult.persona_state.v0.schema.json`
The same schema is mirrored by Epiphany and VoidBot so Faces, repo
representatives, and Ghostlight characters can cross runtime boundaries without
each repo inventing its own local person-shaped blob.
## Ownership
Ghostlight keeps owning the story machine:
- world state
- scenes
- events
- relationships
- perceived overlays
- dialogue context packs
PersonaState owns the portable public-person projection:
- presentation
- values
- activation profile
- thought memory
- agency pressure
- candidate actions
- affect
- source provenance
That projection can be generated from Ghostlight scene agents, VoidBot repo Face
state, or Epiphany Face state. The projection does not erase native state. It is
the wire shape, not a throne.
## Wire Envelope
CultNet should carry PersonaState as a typed document replication message.
Current expected document envelope:
- `documentType`: `gamecult.persona-state`
- `documentKey`: stable runtime-defined persona key
- `payloadSchemaVersion`: `gamecult.persona_state.v0`
- `payload`: exact PersonaState document
Native Ghostlight scene payloads may still travel separately with:
- `documentType`: `ghostlight.agent-state`
- `payloadSchemaVersion`: `ghostlight.agent_state.v0`
Those are different contracts. One carries a story world. One carries a
portable Persona.
## Epiphany Boundary
Epiphany public Faces use PersonaState when they need full persistent
personhood. Epiphany work organs do not. A work organ such as Imagination can
have a light organ state without affect, social bonds, public presentation, or
candidate actions.
This prevents the old muddle where every useful subsystem was tempted to dress
up as a whole person. Useful machines do not all need faces.
## Contract Discipline
The schema lives in multiple repos for local validation, but the contract must
move as one:
- Epiphany keeps the primary CultNet schema copy.
- VoidBot mirrors it and emits PersonaState from repo Face reads.
- Ghostlight mirrors it and validates PersonaState examples.
- Native storage may stay richer than PersonaState.
- Importers must preserve unknown extension data when possible.
- Consumers must treat `provenance.authority` seriously.
Prompt projection may differ. Storage engines may differ. Story scenes may
carry more structure. The shared person-state payload does not drift just
because a runtime got clever at midnight.
## Immediate Consumers
The first intended consumers are:
- Ghostlight character projections for scene/story tooling
- VoidBot repo Face MCP reads and social memory interop
- Epiphany public Face state
- future CultNet replication and inspection tools

View file

@ -1,102 +0,0 @@
# DELVE/HOLD Consumer Profile for the Ghostlight World API
## Status
This document is a consumer binding and conformance profile. It records how
Delvehold maps its authored world and owned state onto Ghostlight's generic API;
it does not create a Delvehold organ, schema family, subject ID, or authority
branch inside Ghostlight core.
## Objective
Use Ghostlight's live external-world simulation as an ordinary API consumer
without making it the owner of DELVE/HOLD players, workshops, dungeons, civic
state, or quantitative economy. DELVE/HOLD provides an authored ontology and
fixed seed for one canonical outside world through consumer-neutral Ghostlight
operations. A consumer seed does not pass through the seed lane; it enters as
a consumer document, and this bypasses none of `WorldKernel`, typed
validation, the mutation algebra, or atomic CultCache commits.
## Core and consumer cut
Ghostlight admits generic world seeds, externally owned subject projections,
consumer-supplied domain effect schemas, proposals, and receipts. Delvehold's
adapter owns the names `delvehold.greathold_boundary_state.v0`,
`delvehold.greathold_effect_batch.v0`, `ghostlight.external_response_batch.v0`,
`delvehold.boundary_receipt.v0`, and the configured subject ID `greathold`. It
lowers and raises those documents at the API boundary. Ghostlight never
switches on those names or that ID.
## Authority map
- **Delvehold owner:** Greathold players, workshops, parties, civic seals, graph, dungeon ecology, and its own quantitative economy: recipes, facilities, capacity, inventories, orders, prices, exchange rates, contracts, expeditions, and local consequences. Custody of Greathold-owned resources changes only through Delvehold.
- **Ghostlight owner:** external regions, actors, institutions, Gestalts, their knowledge, relationships, goals, posture, pressures, strategic choices, external events, and news.
- **Configured boundary subject:** Delvehold configures stable ID `greathold`
through Ghostlight's generic external-subject authority contract. The ID has
no privileged meaning in Ghostlight core.
- **Ghostlight API:** consumer-neutral CultMesh operations admit authored seeds,
externally controlled subject observations and realized effects, and return
attributed intents, news, state projections, and receipts. They own no
consumer ontology or decision.
- **Delvehold adapter:** Delvehold owns translation between its detailed
Greathold state and the generic Ghostlight API. The adapter owns no truth and
cannot repair either canonical domain after rejection.
- **Forbidden writers:** Ghostlight Personas and strategic cells cannot mutate `greathold`; Delvehold cannot mutate foreign private state; the adapter cannot repair either owner after rejection.
The economy owner is Njörðr, the GameCult economy daemon (`gamecult-economy-daemon.md`), for both games and for the Greathold's interior as well as its exterior; Njörðr is itself a Ghostlight consumer and owns the market mirrors. The Delvehold-owner line below predates that decision (2026-09-11) where it names recipes, facilities, capacity, inventories, orders, prices, exchange rates, and contracts; those are Njörðr's, and Delvehold's civic organs author policy over them. Ghostlight owns a narrative-scale conserved quantity for the subjects it simulates: `Custody` holds a unitless `Quantity` per subject and resource, `Transfer`/`Consume`/`Transform` conserve it, and `Admit` creates it only with evidence (`docs/architecture/ghostlight-world-ontology.md`, Invariant 5). That is a ledger, not an economy. `Transform` is one-to-one with no unit, rate, yield, facility, or capacity field anywhere on a Ghostlight type, so prices, production, orders, and contracts are unrepresentable in Ghostlight rather than merely unwritten; they remain Delvehold-owned, and any resource an external mirror holds changes only through its admitted owner.
## Greathold boundary subject
`greathold` is externally controlled. It is not a person, sovereign government, averaged population will, or alternate player-state store.
- It receives no Persona turn or autonomous institution effect.
- Only generic API operations lowered by the Delvehold adapter from an accepted
`delvehold.greathold_boundary_state.v0` or
`delvehold.greathold_effect_batch.v0` document may update its projection.
- External subjects may observe it, relate to it, and direct attributed actions toward it.
- Any proposed change to Greathold-owned truth exits as `ghostlight.external_response_batch.v0` and remains pending until Delvehold returns `delvehold.boundary_receipt.v0`.
The projection excludes player identities, private workshop state, pending votes, unaccepted contracts, private communications, and inferred collective desire. It reports committed macro effects and authorized institutional acts.
## Consumer flow
```text
Delvehold commit
-> Delvehold-owned boundary projection or realized-effect batch
-> Delvehold adapter lowers to a generic Ghostlight API operation
-> WorldKernel validation and atomic commit
-> strategic resolution over external subjects
-> generic attributed intent/news/state response
-> Delvehold adapter raises to its consumer contract
-> Delvehold validation and atomic commit
-> admission receipt
```
Each document carries world ID, UTC epoch ID, source revision, effective time, causal refs, provenance, payload digest, and idempotency key. `delvehold.boundary_receipt.v0` is direction-neutral: the receiving domain returns it to the sender with sender and recipient IDs, per-item results, reason codes, resulting local revision, and committed event refs. Revisions remain local. The source may retry; the recipient must return the same receipt for the same key and digest.
Malformed envelopes, stale revisions, digest conflicts, and invalid causal structure reject the whole document without mutation. After envelope validation, semantically independent items may resolve to an explicit accepted subset, but that subset commits atomically or not at all. The receipt records every item result.
`greathold_boundary_state.v0` is an absolute replacement of its declared projection fields at a Delvehold source-revision watermark. `greathold_effect_batch.v0` carries deltas over explicit preceding and resulting revisions. A snapshot supersedes deltas at or below its watermark; delayed deltas below either accepted watermark are stale. Greathold ingress access and capacity are Delvehold-owned. External route topology and status remain Ghostlight-owned even when Delvehold mirrors their IDs in local admitted state.
Major committed events cross promptly. Ordinary material flow closes hourly. Recovery replays at most eight missed epochs and represents older time as one explicitly coarse horizon. A summarized horizon may reduce detail; it cannot invent player action or hide an unprocessed interval.
## Required generic Ghostlight API capabilities
Ghostlight needs:
1. one seed admission primitive, `AdmitPatch`, shared by the world owner, the
Draft seed lane acting as the owner, the Active elaborator, and the
external consumer;
2. generic external-subject ownership metadata enforced by selection and
mutation gates;
3. generic consumer effect-schema registration or supply;
4. generic proposal and idempotent receipt envelopes.
All four delegate to existing WorldKernel validation and atomic persistence.
The adapter lives in Delvehold and owns all Delvehold-specific projection,
economy translation, document names, and configured IDs. No Delvehold-specific
economy, civic, dungeon, or contract schema belongs in Ghostlight core. No
second kernel, economy store, Session Zero compatibility fiction, or direct
campaign-row writer is admitted.
Acceptance requires negative proof that ordinary strategic waves cannot select `greathold` as an acting subject, malformed or stale batches commit nothing, and foreign effects become local consequences only after a Delvehold receipt.

View file

@ -1,12 +0,0 @@
# Njörðr, the GameCult economy daemon
The specification moved to its owning repository on 2026-09-11:
`GameCult/Njordr`, file `docs/architecture/njordr.md`
(https://github.com/GameCult/Njordr). This file is a pointer so Ghostlight's
map and integration notes keep resolving; it carries no authority.
What Ghostlight owes Njörðr is unchanged and lives here: the outbound consumer
batch shaped as Njörðr's signal surface (custody, pressure and dependency,
route, and event deltas), market mirrors as externally controlled subjects,
several per world, and consumer patches carrying prices as witnessed facts,
shortages as pressures, and realized trades as custody with a receipt.

View file

@ -1,671 +0,0 @@
# Ghostlight authority architecture
> Status: the Dungeon daemon described here is parked at tag `parked/ghostlight-eve-surface` (2026-10-22); it is not on main.
## Status
This document is the adopted rebuild target for the Ghostlight runtime. It is
the authority map for implementation work. What it describes is built in
`crates/ghostlight` except where it says otherwise here: bounded co-op and the
`archived` phase with read/export-only archival are design intent, and nothing
in `crates/` implements them (`WorldPhase` has `Draft` and `Active` only).
Ghostlight is a persistent, source-grounded narrative world. Its job is to
preserve people, institutions, places, knowledge, material consequence, and
autonomous motion across time. It is not a pipeline for passing prose among a
committee of models until one model permits another model's text to exist.
## Objective
Build one sparse, open-world causal machine that supports solo play (bounded
co-op is design intent, unbuilt), autonomous subject decisions, source-grounded expansion, external
world owners, and actor-private experience.
The world grows when committed pressure reaches a typed boundary: a new
destination becomes relevant, an existing polity or population enters causal
range, a person must be individuated, or an effect needs a missing primitive.
A world also grows toward an authored `WorldScaleIntent`: how many goal-bearing
subjects it should hold at each level and realm. Elaborators work that deficit
down; structural validity never waits on it. Cover budget is the deliberate
choke: with subjects several times the cell budget, the scheduler must choose
where attention goes, and actors pursuing their own goals at every level is
what makes the world feel alive. Neither number gates activation or admits a
mutation.
## Prime invariants
1. One per-world `WorldKernel` owns the complete revisioned `WorldState`, from
draft through active play and archive.
2. Every accepted change crosses one `CommandEnvelope`, one deterministic
authority derivation, one ontology reducer, and one atomic CultCache CAS.
3. Structural identity, reference integrity, containment, topology, custody,
jurisdiction, knowledge scope, lineage, and external ownership are typed
code invariants.
4. Every autonomous authority scope names one decision controller. A
`NarrativePersona` uses the Projector-Persona-Interpreter prose membrane; an
`OperationalAgent` receives typed state and tools directly. Neither can
validate, reconcile, schedule, repair, or commit another model's proposal.
5. Projection, attention plans, transcripts, news, summaries, dashboards,
checkpoints, and model receipts do not own world truth.
6. Qualitative interest, political diversity, prose quality, name repetition,
and actor counts are evaluation evidence. They are never mutation gates.
7. A failed or interrupted inference (infrastructure interruption of an
inference; a world-scope interruption between intent and commit is
narrated, not discarded — the narrative lane re-lowers the same prose once
against the fresh scope) leaves no half-owned world state. Recovery starts
from the last committed revision and derives pending work again.
## Canonical owner
### Owner
One mailbox-backed `WorldKernel` owns a world. The mailbox serializes commands;
the CultCache compare-and-swap protects the same invariant across restart or
multiple process attempts.
`WorldKernel` owns:
- lifecycle phase and revision (`WorldState.phase`, `revision`);
- the owner and the draft approvals (`owner`, `draft_approvals`); membership,
a contract, and negotiated boundaries are design intent and no field of
`WorldState` holds them;
- the typed world ontology (the partitions listed under "Canonical world
state");
- committed events and fictional time (`events`, `now`);
- commitments and pressures;
- command idempotency and the commit digest chain.
There is no separate Session Zero owner, component-world owner, aggregate
campaign owner, elaboration committer, scheduler writer, or recovery writer.
### Inputs
The only mutation input is a `CommandEnvelope` containing:
- a stable command ID (`id`);
- the exact world ID and expected revision (`world_id`, `expected_revision`);
- an authenticated principal or internal system capability (`caller`);
- one closed command body (`body: CommandBody`).
`CommandEnvelope` (`crates/ghostlight/src/lib.rs`) has exactly these five
fields. Evidence references travel inside `AdmitPatch`'s `WorldPatch`, not on
the envelope.
The caller supplies identity evidence, not an authority verdict. For a patch
command the kernel derives the caller's authority itself:
`require_patch_author` reads the caller and committed state to decide who may
submit `AdmitPatch` and what ground it holds (the world owner unconfined, an
elaborator confined to a jurisdiction, or a consumer confined to the subjects
it controls), and `confine_to_ground` checks every declaration and operation
in the candidate patch against that ground before it is admitted. Callers
cannot grant themselves scope by serializing a persuasive envelope; the
kernel derives it from state it already committed.
Interpreters and operational agents submit the same typed commands through
narrower schemas. Narrative Personas never see those schemas or tools. No
controller receives a privileged mutation path.
### Outputs
An accepted command produces one `WorldCommit` (`crates/ghostlight/src/lib.rs`)
whose fields are:
- `schema` and `world_id`;
- `command` (the committed command);
- `previous_revision` and `resulting_revision`;
- `previous_state_digest` and `resulting_state_digest`;
- `previous_commit_digest` and its own `digest`;
- `effect` (a `WorldEffect`: the admitted patch, decision, or time step, with
its committed events);
- `committed_at`.
The next `WorldState` and `WorldCommit` are persisted atomically. A rejection
returns typed invariant failures and changes nothing.
### Derived state
The following are recalculated from committed state and may be discarded:
- subject-local projections;
- due-owner queues and attention plans;
- population covers, cells, cell ids, resolution, tick index, the agency
graph, and the cover budget (the only durable trace of a tick is the
controller-work row, custody-separate from world custody);
- action-owner counts and causal-capacity summaries;
- transcript, news, narration, and operator summaries;
- Eve/CultUI and CultMesh documents;
- model prompts, outputs, receipts, latency, and provider telemetry;
- qualitative evaluations and load-test reports.
Derived data may guide a later proposal. It may not admit a mutation, repair a
commit, or declare the world complete.
### Forbidden writers
The following cannot decide canonical state:
- HTTP, native, Eve, CultMesh, or chat handlers;
- Projectors, Personas, Interpreters, assessors, verifiers, reconcilers,
narrators, and copy desks; the elaborator decides nothing directly and
writes only through its confined `AdmitPatch` capability;
- schedulers, attention planners, initiative selectors, and resolution covers;
- acceptance drivers, smoke binaries, checkpoints, resume journals, caches,
and compaction summaries;
- Vault retrieval, evidence reranking, external consumers, and provider
telemetry;
- import, reload, fork, and repair helpers.
Each is either a read-only projection or a producer of one ordinary typed
command.
## Canonical world state
`WorldState` is one aggregate with these owned partitions:
```text
WorldState (crates/ghostlight/src/lib.rs, the fields of the struct)
identity: schema, world_id, revision, phase, state_digest, last_commit_digest
authorship: owner, title, brief, draft_approvals
ontology:
subjects, entities (place, resource, fact, channel), edges (routes)
positions, holdings, dependencies
facts, channels, knowledge
authority, selection, redress
commitments, pressures, last_opportunity_at
persona_material
controller_assignments, affordance_catalog, affordance_grants
time: now
intent: scale_intent, lens_weights
events: events (decision events)
```
There is no `members`, `contract`, or boundaries field and no
`applied_commands` ledger in `WorldState`. Command idempotency is decided from
the commit rows keyed by command id. `WorldCommit` rows, not `WorldState`,
carry the digest chain.
The lifecycle is data inside the aggregate:
`WorldPhase` has two variants, `Draft` and `Active`:
- `Draft`: `ApproveDraft`, `ActivateWorld`, `AdmitPatch` (seed and ontology
construction under draft authority, which answers nothing), and
`SetLensWeights`;
- `Active`: `ExerciseDecision`, `DeclineDecision`, `AdvanceTime`, `AdmitPatch`
that answers a derived boundary or a jurisdiction deficit, and
`SetLensWeights`.
An `archived` phase with read/export-only archival is design intent; no variant
exists.
Activation changes `phase` in place after the current revision has the required
member approvals. It does not copy a preview into another store or hand truth
from one kernel to another.
## Ontology and relational algebra
The component mutation algebra is the foundation. The aggregate `Campaign`
shape is not a second canonical representation.
### Runtime-issued identity
Stable IDs are issued by the reducer. Creation proposals use local draft
handles plus exact existing IDs. Lowering resolves the complete local reference
graph before allocating canonical IDs. Display names never function as keys.
Unknown IDs, cross-kind references, dangling endpoints, and ambiguous handles
are rejected without inference.
### Subjects
A subject is a stable identity with a declared kind:
- person;
- institution;
- autonomous population.
An externally controlled mirror is not a fourth kind. It is an ordinary
subject of one of these three whose `ControllerAssignment` is
`ExternallyControlled { consumer }`: no controller ID, no controller mode, no
decision opportunity, and no affordance, mutable only through its own
consumer and the world owner.
Demographic descriptors and statistical aggregates are not automatically
subjects. A canonical action owner is derived structurally from an active
autonomous subject, one non-overlapping decision controller, explicit decision
authority, and at least one executable typed affordance. Similar names, motives,
or cultures are legal; labels alone cannot create causal capacity.
Population partitions use disjoint typed slice keys. Individuation is an
explicit causal mutation. There is no fission quota and no active-leaf
completion metric.
### Components
Subject and world behavior is composed from narrow typed components:
- position and jurisdiction;
- decision controllers, authority scopes, and executable affordances;
- resource quantity, custody, and dependency;
- knowledge of exact fact IDs and communication access;
- commitments, pressures, and dependency exposure;
- Persona material: values, voice, goals, memories, and relationship reads;
- source provenance and external ownership.
Persona text can enrich lived meaning. It cannot substitute for an authority,
custody, topology, or knowledge component.
### Relations
`EdgeKind` (`crates/ghostlight/src/patch.rs`) has one variant, `Route`, so the
kernel has no general relation record yet. What the kernel carries, each in
its own `WorldState` partition with typed endpoints:
- containment (`EntityRecord.container`) and occupancy (`positions`);
- topology and access (`Route` edges with `AccessKind`);
- custody (`holdings`) and dependency (`dependencies`);
- authority and representation (`authority`, `selection`, `redress`);
- knowledge and communication (`knowledge`, `channels`);
- obligation (`commitments`) and causal pressure (`pressures`);
- control (`controller_assignments`).
Membership, lineage, supply and service, and alliance or opposition as
relations are design intent and have no record shape.
Civic order is a typed subgraph of authority, selection or succession,
resource access, representation, and redress relations. It is not a prose
manifest with fact-ID lanes and does not require a model's civic verdict.
### Structural admission
The reducer validates only structural promises:
- every referenced entity exists or is created in the same closed batch;
- containment is acyclic;
- routes have exact place endpoints and valid costs;
- relation endpoint kinds match the relation kind;
- custody quantities and transfers conserve declared resources;
- authority and affordance scope covers the proposed mutation;
- knowledge additions cite an existing accessible fact or a newly admitted
evidenced fact;
- population slices are disjoint beneath their declared parent;
- an externally controlled subject's components can change only through its
own consumer, confined by `PatchGround::Consumer`;
- a batch either reduces completely or not at all.
Interestingness, novelty, ideological distribution, prose style, and counts do
not appear in this validator.
## One command and commit path
All user and system operations lower through the same path:
```text
authenticated intent or model tool call
-> CommandEnvelope
-> mailbox ordering
-> load exact WorldState revision
-> derive MutationAuthorityEnvelope
-> lower command to WorldMutationBatch
-> validate and reduce the complete candidate
-> atomic WorldState + WorldCommit CAS
-> publish invalidation
-> derive projections and next attention plan
```
The closed command vocabulary is `CommandBody` (`crates/ghostlight/src/lib.rs`),
seven variants: `ApproveDraft`, `ActivateWorld`, `ExerciseDecision`,
`DeclineDecision`, `AdmitPatch`, `AdvanceTime`, `SetLensWeights`. Speech is an
`ExerciseDecision` effect, ontology construction and evidence admission are
`AdmitPatch`, and world creation is a separate genesis (`CreateWorld`).
Membership, contract and boundary changes, external snapshots, and archive are
not commands. Every command lowers to the same mutation vocabulary. There is no
`commit_elaboration`, separate component-batch ingress, or reload repair path.
## Inference boundary
`ControllerMode` (`crates/ghostlight/src/lib.rs`) has three variants, `Human`,
`NarrativePersona`, and `OperationalAgent`; an externally controlled subject
has no mode. Ghostlight supports two first-class model decision interfaces
(`DecisionControllerMode` in `crates/ghostlight-persona-projection/src/lib.rs`:
`NarrativePersona` and `OperationalAgent`). The ontology assigns
each exact authority scope to one `DecisionController`; the scheduler does not
choose a mode opportunistically. The scheduler does choose resolution: a
`NarrativePersona` controller receives its prose membrane in a singleton cell
and is represented operationally, at coarse resolution, when grouped. That is
a budget decision, not a mode change; the controller, its scope, and its
authority are unchanged. A controller changes representation and model
ergonomics, never permission or commit authority. A `NarrativePersona` in a
grouped cell receives its typed view and nothing from the membrane; it mints
no `PersonaTurn`, so the immutable-turn-receipt rule does not apply to it.
The membrane is not weakened; it is not entered. The agency graph is
scheduler-only and is reachable from no prompt builder; its mailbox request
is port-narrowed (absent from the controller and elaboration ports), not
principal-authenticated.
An opportunity is issued to exactly one controller. An untranslated intent or
infrastructure fault cannot fall through to the other mode, and the same
opportunity cannot be exercised twice.
### NarrativePersona controller
The narrative controller keeps one deliberate three-organ membrane around
roleplay. This is not a verifier chain: each organ owns a different
representation and none can commit.
### Projector
Deterministic code first constructs a permissioned `SubjectView` from exact
occupancy, knowledge, memories, relationships, pressures, contract boundaries,
and currently executable affordances. Private views omit unavailable facts and
other members' private state by construction.
The Projector receives that view and the visible stimulus. It emits one lived
narrative stream: perception, memory, uncertainty, desire, bodily circumstance,
and available possibility in prose. It cannot choose an action, emit a schema,
or claim a consequence. The Projector is a semantic renderer across the typed
state-to-lived-experience boundary; its prose is private derived context, not
world truth.
### Persona
The Persona receives only identity guidance and the lived narrative stream. It
does not see canonical field names, IDs, JSON, tool definitions, mutation
vocabulary, effect schemas, or kernel errors. It emits only natural roleplay
prose and may remain silent, speak, decide, hesitate, or attempt something in
character.
This isolation is an explicit quality invariant. Coding-agent training creates
a powerful schema and tool-use attractor. Ghostlight does not assume that a
model can preserve equivalent roleplay while simultaneously operating tools.
### Interpreter
The Interpreter receives the Persona prose, the lived stream, and the exact
permissioned typed context. Interpretation is a total operation. It always
finishes with an `InterpretationReport` containing:
- the immutable Persona turn receipt and exact prose preserved as noncanonical
source evidence;
- every typed proposal it could faithfully lower using existing IDs and
available affordances;
- zero or more `TranslationGap` records for meaningful material it could not
encode;
- the exact source spans supporting both proposals and gaps.
Before interpretation, the NarrativePersona runner persists one immutable
`PersonaTurn` receipt binding controller, decision opportunity, world
revision/state digest, Projector receipt, Persona inference receipt, exact
source prose, and its digest. The report carries that source receipt rather
than reconstructing provenance from prompt text. Report fields are produced by
the accumulator; arbitrary deserialization is not an admission path.
A translation gap identifies ambiguity, a missing reference, a missing
affordance, a missing mutation primitive, or source left unresolved by the
current attempt. It records what the Interpreter believes the Persona was
trying to express without pretending that the effect occurred. Gaps are
non-fictional inference evidence. They may inform evaluation or an explicit
later design decision; recording one does not request elaboration or mutate the
world.
Interpreter tools provide local structural feedback and a `record_gap` action.
An invalid proposal span is not admitted, but the harness records the complete
source as an unresolved gap. An invalid gap span is likewise rebound to the
complete exact source rather than discarded. Raw tool arguments that cannot be
decoded into either typed contract enter the same total fallback, with their
payload digest retained as attempt evidence. If the step budget ends, the
harness finalizes the valid proposals and accumulated gaps and adds an exact
unresolved-source gap instead of returning semantic failure.
The Interpreter cannot add motivation to the Persona turn, rewrite its source
prose, infer unavailable knowledge, or commit an effect. Spoken words become a
typed speech proposal; wondering, deciding, attempting, and narration do not
become audible speech merely because the Persona wrote them. The kernel remains
the final structural guard for typed proposals. A stale revision or persistence
fault is a command/infrastructure outcome, not an interpretation failure, and
does not summon a semantic verifier or reconciler.
Any model transport or dispatch fault before explicit semantic finalization
produces no report. The immutable Persona turn remains pending for a fresh
interpretation attempt; partial captures are discarded as attempt telemetry,
not committed as a half-report. `StepBudgetExhausted` means the harness reached
its configured semantic stopping point normally. Infrastructure interruption is
unavailable execution, not rejected meaning.
World authoring uses a separate typed proposal surface because it is not
roleplay. It does not pass through Persona or borrow Persona authority.
### OperationalAgent controller
An operational controller receives a permissioned typed view and exact tool
schemas directly. It is suitable when the simulated mind is itself an
operator: an institution, political or administrative Gestalt, logistics organ,
market participant, or other subject whose meaningful cognition is explicit
state reasoning rather than embodied dramatic experience.
The operational agent may inspect only the state and affordances granted to its
controller and may submit zero or one typed decision proposal. It may record an
unrepresented operational need, but it cannot emit a NarrativePersona turn as
fallback, claim facts outside its view, or commit.
Subject kind does not secretly choose the interface. A person normally carries
a narrative controller and an administrative institution often carries an
operational controller, but authored ontology makes the assignment explicit.
If one institution needs both an operational decision organ and a person-shaped
public representative, they are separate controllers with disjoint authority
scopes. Awkward overlap is rejected rather than resolved by precedence.
### Presentation inference
Optional narration renders committed events for a particular audience. It is
display-only. The exact typed events remain available beside the prose, and a
rendering failure cannot block, alter, or repair a commit.
Inference receipts are operational telemetry in a separate store. The kernel
does not require a provider, model tier, stage name, output hash, or verifier
receipt to authorize world state.
Every controller lane reaches one `InferencePort`, but that port now routes
to one of three transports chosen by the lane's configured model name: the
CodexConnector daemon peer, unchanged; a local OpenAI-compatible loopback
port (the `local/` prefix, Bonsai in production); or `SdkInferencePort`, a Node child
process running the Claude Agent SDK against the Claude subscription while
no Codex or Anthropic API budget exists. The SDK route is a named stopgap,
not a peer design: its receipt attests only that this process's own child
produced this session, not against a party Ghostlight does not control, and
a prior round's conversation reaches the model as rendered prose rather than
typed turns because the SDK owns the assistant side of its own transcript.
Its exit condition is deletion, not extension — once an API budget exists, a
Messages-API port is a closer structural match to `InferencePort` (inert
`tool_use` blocks, a caller-appended `tool_result`, a real request id, no
subprocess) and replaces it behind the same routed port.
## Action and consequence
An action proposal names one subject, one executable affordance, exact targets,
and typed desired effects. The kernel derives authority and feasibility from
the current ontology. If uncertainty matters, server-owned entropy selects a
bounded outcome band. Only the typed effects for that band enter the mutation
batch.
Speech is an event and may accompany an action. Generated speech cannot imply
that an uncommitted effect occurred. Social appraisal and private memory are
ordinary scoped mutations proposed by the affected subject; they do not gain a
separate appraisal or verifier authority.
Player, NPC, institution, population, import, and strategic actions share this
primitive.
## Autonomous scheduling
The scheduler is a pure planner over one revision. It orders eligible subjects
using unresolved pressure and time since the last opportunity, with subject id
as the final tiebreak. Causal exposure is derivable from `dependencies` and is
not an ordering input. It emits `DecisionOpportunity` values and cannot commit.
Dungeon runs no turn on its own: no wall-clock tick, cover cell, elaboration
sweep or owner-requested controller turn. The clock advances only through the
owner's `world.advance_time`. The controller pool
(`GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT`, default 4) is read at open; nothing
draws from it yet, and runtime readiness reads it. Changing it is a restart.
The five
controller models are configuration too (`GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL`,
`_PERSONA_MODEL`, `_INTERPRETER_MODEL`, `_OPERATIONAL_MODEL`,
`_ELABORATOR_MODEL`), each with a default when absent.
The kernel commits one decision at a time through the mailbox. After each
commit the planner derives a fresh queue. Parallel inference may speculate on
one snapshot; a proposal binds to the scope digest of the components its
verification reads, commits at any later revision where that digest is
unchanged, and is rejected with a typed `ScopeChanged` when it is not. Nothing
is rebased and nothing is discarded merely because the world moved elsewhere:
for the narrative lane, `ScopeChanged` on submit is one re-lowering, not a
lost turn. The runner re-lowers the same prose once through the Interpreter
against a fresh opportunity, with the delta the subject could perceive since
its bound revision (`Overheard` rows plus the typed component diff); the
Persona is never re-run, and the renewed binding carries the one it replaced
(`interrupted_from`) so a second interruption of the same turn ends it rather
than lowering it again.
Resolution covers and grouping are compute budgets for projection. They do not
create, merge, fission, or qualify identities. Every active subject is in the
cover every tick; the budget decides at what resolution. Singleton cells give
detail focus and the prose membrane; grouped cells represent their constituents
operationally at coarse resolution with per-constituent attribution. Debt
rotation guarantees every subject reaches detail focus within bounded ticks.
The 2,400-subject, 240-cell profile is a design target for a living world, not
only a load fixture: it tests the elaborators and the simulation for quality
under scarcity of attention.
## Source grounding and open-world expansion
Vault retrieval returns exact evidence receipts. One author inference may fill
semantic fields in a typed seed or boundary-expansion proposal. The reducer
issues IDs and validates the closed structural graph.
Seed construction, destination expansion, locality detail, causal
individuation, and external import all use the same ontology mutation
vocabulary. Expansion is requested only for a named causal boundary. A sparse
world with enough structure for its current horizon is valid.
Qualitative evaluators may report implausibility, monotony, missing social
texture, or poor narrative leverage after a run. Those reports guide a future
author proposal; they do not become a hidden admission tribunal.
## Persistence and recovery
One world `.cc` store (`crates/ghostlight/src/journal.rs`) contains:
- one current `world_state.elaboration.v1` row, schema
`ghostlight.world_state.consumer.v6`;
- immutable `world_commit.elaboration.v1` rows, schema
`ghostlight.world_commit.consumer.v6`, forming a digest chain. Evidence
receipts ride inside the commits' patches; there is no separate evidence row.
Service authentication and model telemetry use separate service-owned stores.
They cannot participate in world authority.
Recovery verifies `(world_id, revision, state_digest, last_commit_digest)`,
starts the mailbox, derives due work, and continues. In-flight inference is
disposable. A repeated command ID is idempotent only when its full digest
matches the recorded commit. Physical filenames, smoke checkpoints, prose
summaries, and status files are not recovery truth.
Pre-rebuild campaign stores remain immutable evidence. The new runtime does not
load them into live authority through a compatibility adapter. Any future
migration must be an explicit, audited import that emits ordinary commands.
## External boundaries and surfaces
- Heimdall owns public identity; Ghostlight stores only the app-local principal
needed to derive membership authority.
- VoidBot or another Vault provider owns retrieval; evidence receipts grant
provenance, not mutation authority.
- External world consumers retain sovereignty over their declared subjects.
Ghostlight imports only owner-signed components through the ordinary command
path and cannot invent internal state for them.
- Idunn owns deployment and daemon continuity; Odin owns discovery. Neither can
write a world.
- Eve/CultUI and CultMesh expose typed projections of the same `WorldState` and
command catalog. Renderers do not own parallel dashboard truth.
## Deletion line
The rebuild removes these authorities before replacing behavior:
- `SessionZeroKernel`, its registry/director state, and publication handoff;
- canonical aggregate `Campaign` and the component-to-Campaign projection
writer;
- `legacy_transition` and every special construction or repair commit path;
- duplicate or cell-specific Projector-Persona-Interpreter implementations;
implicit mode switching or fallback between narrative and operational
controllers; effect verifier, assessment verifier, outcome verifier, civic
verifier, and reconciliation roles;
- destination identity inference and name-based structural binding;
- model resolution demand, Nemesis selection, and identity invention;
- titled elaborator quotas, complexity qualification, semantic qualification,
fission completion counts, and model compaction memory;
- newspaper selection/editor/copy-desk authority and checkpoint recovery;
- acceptance-driver gates that decide world validity;
- checkpoints, resume files, caches, and model receipts used as fictional truth.
The retained foundations are the typed component mutation algebra, one mailbox,
CultCache CAS and immutable receipts, exact evidence, deterministic topology and
scope validation, actor-private projection, and the declared service ownership
boundaries.
## Verification contract
Focused tests prove the machine under fixture inference ports. No live smoke
exists: the play agent's Cut 1 (`d69e9d4`) deleted the tick driver, cover and
Active elaboration sweep it exercised, along with the ignored test itself, to
clear the ground for the play agent's own owner. `notes/local-live-smoke.md`
now documents only connector and Claude SDK sidecar bring-up, which the seed
lane still uses. The real-model gate that exists today is the Idunn recipe's
`accept-real-persona-membrane` step (`deployment/idunn/recipe.toml`), which
runs `controllers::tests::real_local_model_cognition_modes_commit_speech`
against a real model; exercising a whole play turn against one is not gated
by this contract.
`world.begin` is the one route that makes a world. Its payload is
`world_begin.v1`: title, brief and subject_label, nothing else; the route
decides everything else a world is born with (no targets, no roots, no persona
or agent label, uniform lens weights) and `begin_plan` decides how far Begin
goes. `world.seed` runs one
`SeedRunner` session per invocation against a `VaultEvidenceSource`.
Focused tests must prove:
1. Draft and active commands mutate the same aggregate through the same commit
primitive.
2. No alternate input can write canonical state.
3. Unknown IDs, dangling routes, invalid relation endpoints, custody creation,
authority escape, private-knowledge leakage, and external-owner violation
fail before persistence.
4. Interpreter semantics are total: representable material becomes typed
proposals, unrepresentable material becomes exact translation gaps, and no
semantic path terminalizes the interpretation or calls a verifier or
reconciler model.
5. Scheduler, transcript, news, and surfaces can be discarded and rebuilt from
the same committed state.
6. Restart resumes from the commit digest chain with no checkpoint or repair
pass.
7. A sparse structurally supported world activates successfully.
8. A synthetic 1,200-owner fixture exercises scheduling and projection without
changing production completeness rules.
9. Direct user, model, scheduler, import, and reload paths all reach the same
reducer and CAS.
10. Every autonomous opportunity resolves through one exact controller; its
authority scopes do not overlap another controller, and gaps or faults
cannot trigger cross-mode fallback or double action.
The Projector-Persona-Interpreter membrane has its own behavioral evaluation.
Operational-agent success in its admitted scopes is not evidence that tools are
safe for a person-shaped role. Any proposal to replace a `NarrativePersona`
controller with a tool-using agent must compare both designs on the same
sequential fixtures, model, visible facts, and token budget. It must show no
material regression in voice, embodiment, uncertainty, tonal range, schema
leakage, tool-shaped diction, or continuity while matching typed-effect
fidelity. Until that evidence exists, narrative Personas remain prose-only.
Qualitative world and narrative evaluation is a separate post-run artifact. It
may be severe. It may not become a writer.

View file

@ -1,886 +0,0 @@
# Ghostlight library extraction — cut map (plan step 15, L0)
Status: cut map. Ends are owned by `ghostlight-library-extraction.md`; this
document owns the means. Written 2026-09-15 against `d83534c` on
`codex/ghostlight-dungeon-mvp`; first version committed at `02bbf62`;
refreshed 2026-09-16 with the operator's rulings.
Cut 1 landed at Ghostlight `108b691..f859d2c`. `108b691` is 13 renames with
zero content change; `f859d2c` builds. Verified by Soul's own runs, not the
Hands report: library 419 passed + 1 ignored with test names identical to the
base `world::` set; 10 compile_fail doc-tests pass, also under
`--all-features`; Dungeon 50 + 1 ignored, all 49 base names present and the
+2 exactly the two new soul tests; no `[features]`, `cfg(feature`, or
`cfg(any(test` in the library; no schema string, `_NAMESPACE`, `derive_id`,
serde attribute, or `Preimage` changed; the rewritten tests fail under
mutation of what they pin. Windows only; the Linux release remains Idunn's.
Soul found six defects. Triage:
- **F1 seal is name-based (high, open):** every `pub` ID derives
`Deserialize` (`crates/ghostlight/src/lib.rs:186-200`), as do `ScopeDigest`
(`:532`) and `DecisionOpportunity` (`:559`), so an external crate mints IDs,
reproduces `ScopeDigest::fixture`, and forges a `DecisionOpportunity` into
`derive_cover` from JSON. The reducer still rejects forged opportunities
(`lib.rs:4192-4201`), so kernel integrity holds and the invariant's wording
does not. Dungeon's own Eve payloads deserialize these types, so removing
the derives is not available. Operator question Q1-9 below.
- **F2 single-minter test is bypassable (medium, fix):** the count at
`crates/ghostlight-dungeon/src/app_session.rs:530-555` greps a literal and
misses `<VerifiedPrincipalEvidence>::new(`, an alias, a renamed test module,
or a subdirectory.
- **F3 surface wider than bought (low, fix):** 71 `pub` identifiers are
unreferenced by Dungeon; `ScopeDigest`, `WorkLane`, and `ScopeComponents`
compile as `pub(crate)` and were opened only to quiet `private_interfaces`.
- **F4 "Eve" named in library error strings (low, fix):**
`crates/ghostlight/src/controllers.rs:1494,2576,2582,2584`. Pre-existing;
invariant 3 is still unmet.
- **F5 two Hands claims false as stated (cosmetic, recorded):** `Cargo.lock`
did gain a `ghostlight` package entry (no new external package), and
`fixture_[a-z]` has 8 benign hits in Dungeon.
- **F6 recipe schema drift (pre-existing, recorded):**
`deployment/idunn/recipe.toml` declares `world_state.foundation.v0` and
`controller_work.v3` against code at `consumer.v4` and
`controller_work.v15`. Outside L0; it changes no behavior here.
Cut 2 landed at gamecult-ops `6aba281` (text only; nothing live was run).
The library test step is in the runbook, the deploy script, and the wiring
test, ordered as `recipe.toml` orders it. Two spec defects Hands reported
rather than redesigned: the assertion this map specified was vacuous
(`require_text` is `grep -Fq`, and the string given is a substring of the
persona-projection line, so it passed with the library step deleted), so
Hands used the file's existing exact-line helper and proved it fails under
deletion; and the acceptance test path lives in `acceptance_test=` at
`scripts/deploy-ghostlight-yggdrasil.sh:34`, a fourth site this map did not
list, pinned by the wiring test and repeated in the runbook prose. Operator
consequence: changing `acceptance_test` changes the acceptance binding, so
sealed witnesses under `/srv/ghostlight/acceptance/<binding-sha>/` from
before this commit will miss and regenerate.
Soul passed on Cut 2 and found the assertions pin text, not invocations:
- **C2-F1 (high, fixing):** deleting the two lines above the pinned cargo
line in `scripts/deploy-ghostlight-yggdrasil.sh` leaves it byte-identical
as trailing argv on the *persona-projection* container, so the kernel
tests never run and the wiring test still exits 0. Prefixing the
`docker run` line with `: ` does the same.
- **C2-F2 (medium, fixing):** nothing pins the order of the four cargo
steps; the library block moved after the release build and the wiring
test passed, which would seal an artifact before the kernel tests ran.
- **C2-F3 (medium, fixing):** the wiring test never reads the runbook, so
only three of the four acceptance sites are enforced to agree.
- **C2-F4 (medium, pre-existing, recorded):** `deploy-…sh:937` takes a
reuse branch when the release directory for a commit already exists, so a
redeploy of a sealed commit runs no cargo steps at all. This bounds "the
deploy runs the kernel tests" to a commit's first build. Operator owns
whether that is right.
- **C2-F5 (low, recorded):** `docs/repo-census-2026-09/*` still shows
`src/world/...`. Dated census; no deploy effect.
Held: the step sits in the same branch, image and mounts as its
neighbours, and `set -euo pipefail` with `trap` means a library-test
failure does abort the deploy. The acceptance test exists at
`crates/ghostlight/src/controllers.rs:8980` under `-p ghostlight --lib`.
C2-F1, C2-F2 and C2-F3 are fixed at gamecult-ops `803f2c7` (wiring test
only). A new `require_invocation` helper pins each of the four cargo steps
as a whole contiguous docker invocation and returns its start line; three
numeric comparisons assert the recipe order; the runbook became a checked
file, tying all four acceptance sites together. All four of Soul's
mutations now exit 1 where they previously exited 0, and every
pre-existing assertion still passes. `require_order` was unusable here
because its `last_line` resolves a substring and would have bound the
library step to the acceptance invocation.
Soul passed on the fix batch and confirmed it does what it claimed:
whole-invocation pinning survives image swaps, line swaps, re-indentation,
continuation splits and appended flags; the order checks catch a move into
the reuse branch; the runbook is tied in both directions; `fail` inside a
command substitution does abort, because `set -e` fires on the
assignment's status; nothing was weakened. It also found the structural
limit, recorded and not fixed:
- **C2-F6 (high, recorded):** an exact-line pin proves the lines exist,
not that they run. Wrapping the block in `if false`, prefixing the
opener with `true || \`, or swallowing it in a heredoc keeps every
pinned line byte-identical and the checker exits 0.
- **C2-F7 (medium, recorded):** the four steps carry no explicit `||
exit`; abort depends entirely on `set -euo pipefail` at
`deploy-…sh:2`, which nothing pins. Removing the `e` leaves the checker
green, so a failing kernel suite would be followed by a sealed release.
- **C2-F8 (low, recorded):** a duplicated block passes, since the helper
takes the first match and never asserts a count.
These stay recorded rather than fixed: that script is a legacy actuator
under Ghostlight's do-not-invoke warning and is retired at the deployment
gate, and the authority that actually runs the tests is Ghostlight's own
`deployment/idunn/recipe.toml`. Closing them means control-flow analysis
in a bash checker for a script we intend to delete. Revisit only if the
deployment gate keeps the script.
Follow-ups outside this migration, from the fix batch:
- `scripts/deploy-ghostlight-yggdrasil.sh:974`, the web container, is
pinned by substring and survives a `: ` prefix that neuters it.
- The Codex Connector's four cargo steps are bare substring pins with no
invocation or order assertion: the connector-side C2-F1 and C2-F2.
- `require_command_options` searches a fixed 18-line window, so a block
that grows past it stops being checked silently.
Cut 1 fix batch landed at Ghostlight `7c1d1e9..2865ea7`: `a8d3377` external
rejection tests (Q1-9), `fac90e6` single-minter check by name (F2),
`7cbb9e3` Eve removed from library text (F4), `2865ea7` public surface
262 → 258 (F3). Hands' correction to F3 is confirmed by Soul: Dungeon calls
`bound_scope_digest` and `fresh_scope_digest`, and `ScopeDigest`, `WorkLane`
and `ScopeComponents` are held public by `KernelError::ScopeChanged`,
`ControllerWorkCustody::Uncertain::lane` and `NarrativeCheckpoint` variant
fields; closing them means reshaping public enums, which F3 does not
license. `fac90e6`'s commit message describes a replaced brace-counting
scanner; the landed code and its doc comment are correct.
Soul held: the rejection tests are a true external crate with no `#[path]`
or `include!`, driving `ControllerPort::submit_controller` through the
mailbox into `reduce` with no pre-validation; every commit moves `revision`
and `state_digest`, so the unchanged-state assertions are sound; the
positive test goes red when issued opportunities are refused; counts,
the 14 distinct warnings, and both manifests are unchanged.
Soul found:
- **S1 (medium, fixing):** both forged digests differ in length from a real
`sha256:` + 64 hex, so comparing only lengths at
`crates/ghostlight/src/lib.rs:4203` leaves all seven tests green. The
realistic forgery is a stale same-length digest from an earlier revision.
- **S4 (medium, open, Q1-10):** the minter scanner at
`crates/ghostlight-dungeon/src/app_session.rs:523-668` misses a `pub type`
alias, a multi-line alias, a `} // tests` closing brace, non-rustfmt
indentation, and `::new` taken as a function value.
- **S7 (low, fixing):** `controllers.rs:122 provider_model` closes to
`pub(crate)` with no error and no warning change.
- **S8 (cosmetic, fixing):** `mailbox.rs:580` names `AppSessionOwner` and
`controllers.rs:2606` names AppSession.
- **S2 (low, recorded):** neutering the world_id check at `lib.rs:4193`
leaves the suite green because `ScopePreimage` includes `world_id`, so the
scope lookup refuses first. Redundant by construction; not isolable from
outside the crate.
- **S3 (low, recorded):** the decline path (`lib.rs:1603`) is `pub(crate)`
and unreachable from an integration test.
- **S5 (low, recorded, pre-existing):** `runtime.rs:3584`'s credential-name
test splits on one literal `#[cfg(test)]` marker and is evadable the same
way the minter test was.
- **S6 (medium, recorded):** stable rustc does not enforce `compile_fail`
error codes; `E0603` changed to `E0999` still passes. All ten doc-tests
prove "does not compile", not privacy, and the three `#[cfg(test)]`
items (`SubjectId::issue`, `ScopeDigest::fixture`, the `fixture_*` fns)
prove non-existence. Enforcing codes needs a snapshot tool such as
trybuild; recorded, not added.
**Q1-10 how the single minter is enforced (defaulted, 2026-09-16).** Asked
how much it mattered, the operator said not at all. The scanner stays as a
tripwire with stated limits: it guards only against the project's own
Dungeon code, and what evades it is deliberate. S4 is a recorded follow-up,
with Clippy's `disallowed-methods` for
`ghostlight::VerifiedPrincipalEvidence::new` noted as the fix if a second
minter ever becomes plausible.
S1, S7 and S8 landed at Ghostlight `bde05de..af9c95a`. S1 submits a
genuinely issued digest made stale by another controller's speech, plus the
current digest with its last digit altered. Soul confirmed the premise
check fails when staleness does not happen and that no earlier check
intercepts the forgery, then found two surviving comparison mutants
(case-insensitive, hex-only after the label). Those, and "player"
vocabulary in library tests, landed at `b14507c` (uppercased-letter,
bare-hex and relabelled forgeries, all six comparison mutants killed) and
`ab95d78` (test-only rename to "human", one test name changed). Soul's
final pass found nothing to fix.
**L0 closed, 2026-09-16.** Postmortem:
`ghostlight-library-extraction-postmortem.md`. Follow-ups are listed there.
**Q1-9 what sealing means (ruled, operator, 2026-09-16): option A.** The
invariant is unforgeable admission, not unconstructible types. External
code may hold a syntactically valid ID, digest, or opportunity; the kernel
must reject any it did not issue, and that is proven by rejection tests
written from outside the crate. The compile_fail set stays for the
genuinely private items. The question as first posed: A: restate invariant 1 as unforgeable
*admission* — external code may hold a syntactically valid ID or opportunity,
and the kernel must reject any it did not issue — and prove it with rejection
tests from an external crate plus the existing compile_fail set. B: make the
types unconstructible from outside, which means Dungeon stops deserializing
`DecisionOpportunity` in its Eve payloads and receives an opaque token
instead, a design change L0 excludes. **Recommended: A**, because the kernel
already enforces it and B moves work into L0 that the target puts out of
scope. Whichever is chosen, F2 and F3 are fixed in the same Hands batch.
Rulings (operator, 2026-09-15):
- **Q1-1 crate name:** "crate name is `ghostlight`."
- **Q1-2 adapters:** "`vault.rs` and `sdk_inference.rs` both go in the
library."
- **Q1-3 principal seam:** "option A, library-owned
`VerifiedPrincipalEvidence` with a public `new`, plus the Dungeon count
test pinning the single minter."
- **Q1-4 fixtures:** "NOT the `test-support` feature. The operator takes the
alternative: the sealed ID `issue()` constructors and `ScopeDigest::fixture`
stay unreachable from outside the library under every configuration,
including feature-enabled builds, and the Dungeon tests that currently
need them move into the library instead. Rationale: a sealed constructor
exposed behind a feature is still reachable by any crate that turns the
feature on, which contradicts invariant 1." (Supersedes the `test-support`
design in the `02bbf62` map; that text is history and is not repeated
here. The classification below found that none of the affected tests is
a kernel test, which raises Q1-7 and Q1-8.)
- **Q1-5 persona projection:** "`ghostlight-persona-projection` stays a
separate crate."
- **Q1-6 gamecult-ops:** "edit the five gamecult-ops cargo lines in Cut 2;
do not retire the scripts (retirement belongs to the deployment gate)."
Correction to the `02bbf62` map: Ghostlight's handoff does call those
helpers unsafe — `notes/fresh-workspace-handoff.md:389-391`: "Do not
invoke the current bounded Connector or Ghostlight redeploy helpers; they
fail at the root/Idunn Git boundary and still embody duplicate target
deployment authority." The earlier claim that no such doc existed was
wrong; the ruling to edit rather than retire stands on the deployment
gate owning retirement, not on the scripts being live.
Rulings (2026-09-16), taken by Self under the operator's standing "Go"
after Q1-4's classification found no kernel test to move. Either may be
reversed by the operator; both are recorded here as the live design:
- **Q1-7 port value constructors:** option A. `PreparedInference::prepare`
(renamed from `prepare_invocation`), `InferenceOutput::new`, and
`InferenceFault::{retryable, recovery_required, integrity_violation}`
become the port's public contract; the five `fixture_*` items are
deleted and `TracingInferencePort` becomes an ungated decorator. A
public trait whose return types only the library can construct is not a
port, none of these touches a sealed item, and the change is a net
deletion.
- **Q1-8 cover source:** option A. The tick-ordering test derives its
cover from a real world through `derive_cover` and asserts 2 cells, with
its ordering and shared-tick assertions unchanged;
`fixture_controller_opportunities`, the only outside caller of a sealed
`issue()`/`ScopeDigest::fixture`, is deleted.
Together these satisfy Q1-4's intent: the sealed ID issuers and
`ScopeDigest::fixture` stay private `#[cfg(test)]` items with no feature
gate anywhere, unreachable from outside the library under every
configuration.
Open: nothing blocking Cut 1. Operator checks remain on the Linux release
(Idunn's recipe run), which no Windows probe can prove.
Follow-ups outside this migration: see "Findings not assigned to a cut".
Probe names versus real names: probes 1–4 built the crate as
`ghostlight-world` (`use ghostlight_world::…`); probe 5 rebuilt it as
`ghostlight` (`use ghostlight::…`). The difference is the package name, the
directory `crates/ghostlight`, and the path prefix; every mechanism finding
held in both. This map uses the real name throughout.
## What the probes established
All probes ran in scratch worktrees at `d83534c` (both removed, repo clean)
on the Windows workstation with `cargo check` and `cargo test --doc`; they
prove the crate graph and visibility on Windows only. The Linux proof is
Idunn's recipe run on Yggdrasil. Logs are in the session scratchpad
(`probe1*-check.log`, `probe3*-visibility.log`, `probe5.log`,
`base-test-list.log`); they are not repo artifacts.
- **Base test census** (`cargo test -p ghostlight-dungeon --bin
ghostlight-dungeon -- --list`, repo target dir): 469 unit tests in the bin,
of which 420 are under `world::` (action 34, clock_tests 45, consumer 30,
controllers 81, cover 18, custody_tests 17, elaboration 14, journal 24,
knowledge_tests 21, mailbox 15, patch 34, sdk_inference 23,
soul_knowledge_tests 9, tests 32, vault 6, witness_tests 17) and 49 are
Dungeon's own (app_session 7, eve 5, heimdall 5, idunn_health 4, mesh 4,
runtime 24). `tests/build_provenance.rs` has 1. `ghostlight-persona-
projection` has 13 unit, 0 doc. Two tests are `#[ignore]`:
`world::controllers::tests::real_codex_connector_cognition_modes_commit_speech`
and `runtime::tests::live_smoke_seeds_then_ticks_a_world_against_the_connector`.
- **Base warning**: `mod.rs:28-32` re-exports nine names nobody in the crate
uses (`ControllerOpenError`, `NarrativeCapture`, `NarrativeDecision`,
`NarrativePending`, `OperationalCapture`, `OperationalDecision`,
`OperationalPending`, `SourceRange`, `TranslationGapSummary`). Their
deletion is inside Cut 1.
- **The move compiles** (probe 1d). Moving `src/world/*` to the new crate
(`mod.rs` → `lib.rs`), rewriting `crate::world::` → `crate::` inside it and
→ `ghostlight::` in Dungeon, and moving `VerifiedPrincipalEvidence` into
the library root: `cargo check` on the library, its tests, the Dungeon
bin, and the Dungeon tests all pass. Two mechanical faults: the 94
`pub(super)` sites in the former `mod.rs` are illegal at a crate root
(become `pub(crate)`), and `consumer.rs:62` needs `serde_bytes` in the
library manifest.
- **What Dungeon needs public** (probe 3, four compiler rounds from every
item `pub(crate)`): 54 production items, 22 test-only items, 38 fields on
10 structs, 36 methods, the opaque IDs `AffordanceId`/`CommandId`/
`SubjectId`, and `FictionalMinutes(u64)` (one Dungeon test). Nothing
sealed appears: `WorldKernel`, `WorldState`, `reduce`, `apply_effect`,
`CommandEnvelope`, `AuthenticatedCaller`, the journal, `*::issue()` and
`ScopeDigest::fixture` are never named by Dungeon. Under the narrowed
library `cargo check -p ghostlight` emits 646 dead-code warnings — a
second enumeration of the same boundary (an item used only by Dungeon is
dead inside the library until it is `pub`).
- **The sealed set under the Q1-4 ruling** (probe 5, crate `ghostlight`, no
cargo features, fixtures left `#[cfg(test)]`): ten `compile_fail`
doc-tests on the library root pass under `cargo test -p ghostlight --doc`
and again under `cargo test -p ghostlight --all-features --doc` (the crate
declares no features, so the second run is the same build; it is the
command Soul re-runs if a feature is ever added). `cargo check -p
ghostlight-dungeon --bin ghostlight-dungeon` passes: production needs no
fixture. `cargo check -p ghostlight-dungeon --tests` fails on exactly four
errors — `runtime.rs:3081` (`ControllerWork…` family, `Inference…`
types, three `fixture_inference_*`), `:3570`
(`fixture_controller_opportunities`), `:2582` (`TracingInferencePort`),
`:2581` (`InferencePort`, because the base re-export at `mod.rs:66` is
`cfg(test)`). Those four sites are the whole cross-boundary test surface;
they are classified under Cut 1.
- **Compile-fail mechanism**: doc-tests compile as an external crate, which
is exactly the boundary; no `trybuild`, no scratch crate. The ten
(`use ghostlight::WorldKernel`, `reduce`, `WorldState`,
`CommandEnvelope`, `AuthenticatedCaller`, `journal::WorldJournal`,
`SubjectId::issue()`, `ScopeDigest::fixture("x")`,
`fixture_controller_opportunities(&[])`, `fixture_inference_output(..)`)
are pinned to `E0603`, `E0599`, `E0599`, `E0425`, `E0425`.
- **Negative-grep collisions** checked in `src/world/`: `axum`, `tower_http`,
`jsonwebtoken`, `heimdall`, `eve::`, `idunn_health`, `Session Zero` have
zero legitimate hits. `Dungeon` collides with the vault fixture path
`Spoilers/Dungeons/Provenance.md` (`vault.rs:489,581`): use `\bDungeon\b`.
`player` collides with `tests::player()` (`consumer.rs:966`): do not
publish a bare `player` pattern. `app_session` has 5 hits, all the
principal seam, and must reach 0.
- **Line endings**: index and working tree are LF (`git ls-files --eol`
reports `i/lf w/lf`); `core.autocrlf=true` rewrote every fresh scratch
worktree to CRLF. Hands edits in `F:\Projects\Ghostlight` itself, never in
a fresh worktree; if a worktree is unavoidable, run `git ls-files --eol
crates` after the move and refuse any `w/crlf`. `sdk_inference.rs:1831`
normalizes `\r\n` before scanning source.
## Cut 0. Captures
- **Repo/branch:** Ghostlight `codex/ghostlight-dungeon-mvp` at `02bbf62`
(source identical to `d83534c`). No commit; output lives in the session
scratchpad.
- **First:**
- Test census: `cargo test -p ghostlight-dungeon --bin ghostlight-dungeon
-- --list > base-tests.txt` (PowerShell `>` writes UTF-8 BOM + CRLF;
compare post-cut with the same redirection and `Compare-Object` on
trimmed lines after stripping the `world::` prefix). Expected 469.
- A `world.cc` written at base. No store exists on disk
(`F:\Projects\Ghostlight-smoke\ghostlight` holds no `world.cc`), so
produce one: in a scratch copy at `d83534c`, add an ignored test beside
`mailbox.rs:966 fixture()` that opens `WorldMailbox::open(<capture>/world.cc)`,
creates through `create_fixture`, approves, activates, and ticks three
times through `submit_clock`; record `snapshot().revision`, the
`state_digest`, and the last `commit_digest` from `operator_log` to
`capture.txt`. Copy `world.cc` and `capture.txt` to the scratchpad.
After Cut 1 the same test body, in the library's `mailbox` tests,
reopens that file and asserts the three values are equal. The
`controller-work.cc` layout is pinned by the untouched
`CONTROLLER_WORK_SCHEMA`/`CONTROLLER_WORK_ROW` constants
(`controllers.rs:75-76`) and the existing v7/v8 refusal tests
(`controllers.rs:6487,10654`); no separate capture.
- `Get-ChildItem target -Recurse | Measure-Object Length -Sum`: 7.5 GiB at
the start of this pass.
## Cut 1. Extract the library crate
- **Repo/branch:** Ghostlight `codex/ghostlight-dungeon-mvp` from
`02bbf62`. One commit; the crate graph does not build half-moved. Depends
on Cut 0 and rulings Q1-7, Q1-8.
- **First:** Cut 0 captures in hand; `git status` clean; working in the
main checkout (LF).
- **Deletes first:**
- `crates/ghostlight-dungeon/src/world/mod.rs:28-32` — the nine unused
re-exported names above (leave `CellRun`, `ConnectorBinding`,
`ControllerError`, `ControllerModels`, `ControllerPendingReason`,
`ControllerRunner`, `ControllerWorkCustody`, `NarrativeRun`,
`OperationalRun`, `SubmissionDisposition`, `open_controller_work`,
`open_inference`).
- `crates/ghostlight-dungeon/src/world/mod.rs:61-72` — the `#[cfg(test)]`
re-export block (12 lines). The port traits and their value types in it
return as ungated production `pub use` under Adds; the three
`fixture_inference_*` names do not return.
- `crates/ghostlight-dungeon/src/world/mod.rs:483-508` —
`fixture_controller_opportunities` (26 lines), per Q1-8 A; and
`controllers.rs:372-382,409-432` — `fixture_prepared_inference`,
`fixture_inference_output`, `fixture_inference_events` (about 40
lines) and `controllers.rs:221-237` — `InferenceFault::fixture_*`
(17 lines), per Q1-7 A. Under Q1-7 B / Q1-8 B these stay `#[cfg(test)]`
inside the library and the Dungeon tests that used them are deleted
instead (see the classification).
- `crates/ghostlight-dungeon/src/app_session.rs:54-91` — the
`VerifiedPrincipalEvidence` struct, accessors, and `fixture` (38 lines).
- `crates/ghostlight-dungeon/src/main.rs:7` — `mod world;`.
- `crates/ghostlight-dungeon/Cargo.toml:27` — the direct
`ghostlight-persona-projection` dependency (`controllers.rs:35` is the
only importer and it moves).
- **Keeps and moves:**
- `git mv crates/ghostlight-dungeon/src/world/{action,clock,consumer,
controllers,cover,elaboration,journal,mailbox,patch,sdk_inference,
tool_schema,vault}.rs crates/ghostlight/src/` and
`git mv .../world/mod.rs crates/ghostlight/src/lib.rs`. Verify with
`git diff --cached -M --stat` that all 13 show as renames.
- Inside the moved files: `crate::world::` → `crate::` (199 sites;
`super::super::` paths need no change); `pub(super)` → `pub(crate)` in
`lib.rs` only (94 sites; submodules keep theirs);
`crate::app_session::VerifiedPrincipalEvidence` → `crate::VerifiedPrincipalEvidence`
(`mailbox.rs:10`, `controllers.rs:10714,10790,10988,11473`).
- `vault.rs` and `sdk_inference.rs` move with the rest (Q1-2). Their
fixture writes (`sdk_inference.rs:1900,1983`) resolve from
`crates/ghostlight` at the same depth.
- `build.rs`, `tests/build_provenance.rs`, `runtime.rs:375` (web/dist)
stay in Dungeon; `CARGO_MANIFEST_DIR/../..` still resolves.
- No test moves between crates. Every test under `world::` was already a
library test and moves with its file (420); every Dungeon test stays in
Dungeon (49). See the classification.
- **Adds:**
- `Cargo.toml` (workspace): member `crates/ghostlight`.
- `crates/ghostlight/Cargo.toml`: package `ghostlight`; no `[features]`;
dependencies `async-trait`, `chrono`, `codex-connector`, `cultcache-rs`,
`ghostlight-persona-projection = { path = "../ghostlight-persona-projection" }`,
`rmp-serde`, `serde`, `serde_bytes = "0.11"`, `serde_json`, `sha2`,
`thiserror`, `tokio`, `tracing`, `uuid`, `zeroize` (all `.workspace =
true` except `serde_bytes`, which the workspace does not declare); dev
`tempfile = "3"`. Every one is already in `Cargo.lock`; no new package.
- `crates/ghostlight-dungeon/Cargo.toml`: `ghostlight = { path =
"../ghostlight" }` in `[dependencies]`; nothing in dev-dependencies.
- `Cargo.lock`: the new `[[package]] name = "ghostlight"` entry. Commit
it; Idunn builds `--locked`.
- `crates/ghostlight/src/lib.rs`, root: `pub struct VerifiedPrincipalEvidence
{ account_subject_hash: String, valid_until: DateTime<Utc> }` with `pub fn
new`, `pub fn account_subject_hash`, `pub fn valid_until`, and
`#[cfg(test)] fn fixture` delegating to `new` (Q1-3). Doc comment: the
consumer verifies; the library bounds by `valid_until` at
`mailbox.rs:231`.
- `crates/ghostlight/src/lib.rs`, the public boundary, one ungated list.
`pub use clock::{FictionalMinutes, TickMinutes}`;
`consumer::{CONSUMER_BODY_LIMIT, CONSUMER_CREDENTIALS_ENVIRONMENT,
CONSUMER_PATCH_SCHEMA, CONSUMER_RECEIPT_SCHEMA, ConsumerRegistry,
admit_document, encode_receipt}`;
`controllers::{CellRun, ConnectorBinding, ControllerError,
ControllerModels, ControllerPendingReason, ControllerRunner,
ControllerWork, ControllerWorkCustody, ControllerWorkLookup,
ControllerWorkStore, ControllerWorkStoreError, ControllerWorkWrite,
InferenceEvent, InferenceFault, InferenceOutput, InferencePort,
InferencePurpose, InferenceRequest, NarrativeRun, OperationalRun,
PreparedInference, SubmissionDisposition, ToolResultOracle,
open_controller_work, open_inference}` (plus `TracingInferencePort`
under Q1-7 A);
`cover::{AgencyGraph, Cell, Cover, CoverBudget, TickIndex, derive_cover}`;
`elaboration::{SeedOutcome, select_row}`;
`mailbox::{ConsumerPort, ControllerPort, MailboxError, SeedPort, WorldMailbox}`;
`patch::{JurisdictionKey, Statement}`;
`sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, SdkBinding}`;
`vault::VaultEvidenceSource`. Root items made `pub`: `STATE_SCHEMA`,
`state_schema_compatibility_tag`, `AffordanceId`, `CommandId`,
`SubjectId` (the `opaque_uuid!` macro at `mod.rs:98-106` emits
`pub(crate) struct`; give it a visibility parameter and emit `pub` for
these three only — the `issue()` impls stay private and `#[cfg(test)]`),
`PrincipalId`, `WorldPhase`, `SubjectKind`, `ControllerMode`,
`CreateWorldIntent`, `CreateJurisdictionIntent`, `DecisionOpportunity`,
`DecisionInvocation`, `PrincipalCommandIntent`, `CommandBody`,
`WorldSnapshot`, `OperatorEvent`, `CommitReceipt`, `SubmitReceipt`,
`KernelError`, `ScaleDeficitRow`, and the snapshot row types Dungeon
reads through `WorldSnapshot` fields (`SubjectSnapshot`,
`PlaceSnapshot`, `AffordanceSnapshot`, and whichever others the
compiler names; probe 3 stopped at the `WorldSnapshot` field layer).
`GroupedRun` (`controllers.rs`) is reached through `ControllerRunner`
return values and needs `pub` with its five fields.
- How the ports stay public without the fixture constructors becoming
reachable: `InferencePort` (`controllers.rs:259`) and
`ControllerWorkStore` (`:1541`) are traits whose method signatures name
`InferenceRequest`, `PreparedInference`, `InferenceOutput`,
`InferenceFault`, `ToolResultOracle`, `ControllerWork`,
`ControllerWorkLookup`, `ControllerWorkWrite`, `ControllerWorkCustody`,
`ControllerWorkStoreError`. Those types become `pub`; their fields stay
private except where listed below. Nothing about them reaches an ID
`issue()` or `ScopeDigest::fixture`, which are private free functions
and `#[cfg(test)]` impls (`mod.rs:200-226,448`) with no `pub` path of any
kind and no cargo feature — reachable only from inside the library's
own test build. The `fixture_*` functions are deleted (Q1-7 A / Q1-8 A)
or stay `#[cfg(test)]` (B), and the ten doc-tests pin both outcomes.
- Fields that become `pub` (38, from probe 3): `CommitReceipt.{command_id,
commit_digest, resulting_revision, resulting_state_digest}`,
`Constituent.subject`, `Cover.{cells, oversubscribed, tick}`,
`CoverBudget.{cells, constituent_cap, urgency_slots}`,
`DecisionOpportunity.{controller_mode, world_id}`, `GroupedRun.{cell,
needs, pending, resolution, submissions}`, `OperatorEvent.{revision,
speech}`, `PreparedInference.purpose`, `ScaleDeficitRow.{deficit,
jurisdiction, kind, target}`, `WorldSnapshot.{affordances,
draft_approvals, now, opportunities, owner, phase, places,
required_approvers, revision, scale_deficit, subjects, title, world_id}`.
`FictionalMinutes.0` stays `pub(crate)`: under Q1-8 A the one Dungeon
use (`runtime.rs:3579`) is replaced by `snapshot.now`. Fields of the row
structs reached through `WorldSnapshot` follow in the next compiler
round.
- Methods that become `pub` (36, from probe 3, by definition site):
`WorldMailbox::{open, create, submit_principal, submit_clock,
agency_graph, operator_log, snapshot}` (`mailbox.rs:93,105,226,355,448,
461,474`), `ConsumerPort::new` (`:552`), `SeedPort::new` (`:594`),
`ElaborationPort::new` (`:660`), `ControllerPort::{new, snapshot,
submit_controller}` (`:692,696,721`), `ControllerRunner::{open,
elaborator, seeder, custody_probe, run_narrative, run_operational,
run_cell}` (`controllers.rs:2691,2712,2728,2744,2748,2838,3057`),
the receipt/pending accessors at `controllers.rs:2397,2413,2421,2453,
2457,2461,2465,2469,2515,2519,2523,2543,2591,2595` (`persona_turn`,
`re_lowering`, `into_parts`, `subject`, `bound_scope_digest`,
`fresh_scope_digest`, `gap`, `mode`, `reason`, `persona_prose`),
`sweep` (`elaboration.rs:607,1746`), `name` (`elaboration.rs:1511`),
`Cover::{singletons, groups, validated}` (`cover.rs:163,170,198`),
`ConsumerRegistry::{empty, from_secret_file}` (`consumer.rs:168,176`),
`TickMinutes::{new, minutes}` (`clock.rs:45,51`), `CommandId::new`
(`mod.rs:122`), `PrincipalId::new` (`mod.rs:239`), `Statement::new`
(`patch.rs:281`). Under Q1-7 A add `PreparedInference::prepare`
(renamed from `prepare_invocation`, `controllers.rs:388`),
`InferenceOutput::new`, `InferenceFault::{retryable, recovery_required,
integrity_violation}`, `InferenceRequest::provider_model` (`:120`), and
`TracingInferencePort::new` (`:285`).
- `crates/ghostlight/src/lib.rs` crate docs: the ten `compile_fail`
doc-tests from probe 5, each pinned to its error code.
- `crates/ghostlight-dungeon/src/runtime.rs` (tests): a ~25-line copy of
`soul_no_credential_name_appears_in_the_ports_own_source` scanning
`runtime.rs` only, because the library test cannot read another
crate's source (see per-file `sdk_inference.rs:1824-1828`).
- `crates/ghostlight-dungeon/src/app_session.rs` (tests): one test
asserting `VerifiedPrincipalEvidence::new(` occurs exactly once in the
crate's production source, at `account_for_cookie` (same shape as the
`from_secret_file` count at `sdk_inference.rs:1860`). This is the
single-minter rule the deleted private fields used to enforce (Q1-3).
- **Cross-boundary test classification (Q1-4).** Every Dungeon test that
reaches an item which is `#[cfg(test)]` in the library today. Method:
probe 5's four compile errors plus a read of each test body.
| # | File:line | Test | Exercises | Reaches | Class |
|---|---|---|---|---|---|
| 1 | `runtime.rs:3270` | `the_tick_driver_never_exceeds_its_controller_permit_pool` | `run_cover_tick` and `state.controller_permits`: two singleton cells, pool of one, no overlapping `infer` | `fixture_prepared_inference`, `fixture_inference_output` (via `CountingInferencePort`, `:3241`); `AlwaysFreshWorkStore` (`:3194`) uses only `pub` enum variants | Dungeon runtime |
| 2 | `runtime.rs:3337` | `quarantine_raised_mid_tick_stops_the_sibling_cell_and_every_later_tick` | the driver's `controller_quarantined` flag across sibling cell and next tick | `fixture_prepared_inference`, `InferenceFault::fixture_integrity_violation` (`QuarantiningInferencePort`, `:3308`) | Dungeon runtime |
| 3 | `runtime.rs:3500` | `a_second_mid_turn_change_reaches_the_drivers_interrupted_arm` | the driver's `Interrupted` arm reached through `run_cover_tick`, commits through `ControllerPort::submit_controller` (production) | `fixture_prepared_inference`, `fixture_inference_output`, `fixture_inference_events`, `InferenceFault::fixture_recovery_required`, `InferenceEvent::ToolCall` (pub variant), `PreparedInference.purpose` (`InterruptingCoverPort`, `:3432`) | Dungeon runtime |
| 4 | `runtime.rs:3567` | `drive_one_tick_runs_every_cell_before_the_clock_and_all_share_one_tick` | `drive_one_tick` ordering: every cell before the clock, all cells carry the cover's tick | `fixture_controller_opportunities` (the only caller of the sealed `WorldId/SubjectId/ControllerId::issue()` and `ScopeDigest::fixture` from outside `world/`), `FictionalMinutes(u64)`, `AgencyGraph::default`, `Cell`, `TickIndex`, `CommitReceipt` literal (`controller_commit`, `:2492`) | Dungeon runtime |
| 5 | `runtime.rs:3697` (ignored) | `live_smoke_seeds_then_ticks_a_world_against_the_connector` | the road test: seed from a real Vault, activate, tick against a real connector; `GHOSTLIGHT_SMOKE_TRACE` writes the whole membrane (`notes/local-live-smoke.md:214-246`) | `TracingInferencePort` (`fixture_with`, `:2581-2582`) | Dungeon runtime |
Counts: 5 tests reach test-only library items; 0 are kernel tests; 5 are
Dungeon runtime tests. Two other Dungeon tests touch the boundary but
need nothing test-only: `runtime.rs:2502`
`no_proposal_projection_carries_the_canonical_world_commit` builds a
`CommitReceipt` literal (four `pub` fields, in the boundary list) and
`runtime.rs:4293` `soul_verified_evidence_outlives_the_session_that_minted_it`
uses `VerifiedPrincipalEvidence::fixture` → `::new` (Q1-3). Every other
Dungeon test (42) uses production ingress only.
Consequence: the ruling's "move the tests into the library" has no test
to move. Tests 1–4 exercise `run_cover_tick`, `drive_one_tick`, the permit
pool, and quarantine — Dungeon's tick driver — and test 5 is Dungeon's
road test; moving any of them would move the driver. What they need
divides into two kinds, and each is an operator question below rather
than a mechanism this map invents:
- tests 1, 2, 3, 5 need to construct **port values** (`PreparedInference`,
`InferenceOutput`, `InferenceFault`) and a port decorator; none of
these is a sealed item under invariant 1 (mutable state, ID allocator,
reducer, journal, authenticated-caller constructor) — Q1-7;
- test 4 needs a **`Cover`** to walk, and today gets it from fabricated
opportunities minted with sealed IDs — Q1-8.
Expected post-move counts, under Q1-7 A and Q1-8 A: library 420 unit
(the base `world::` list, prefix stripped) + 10 doc; Dungeon bin 49
(the same 49 names; tests 1–4 rewritten in place, test 5 unchanged);
`build_provenance` 1; persona-projection 13; ignored 1 + 1. Under Q1-7 B
tests 1–3 and the `trace` half of test 5 are deleted (Dungeon 46, or 45
if test 4 goes under Q1-8 B); the library count is unchanged either way.
- **Per-file changes** (against `d83534c` = `02bbf62` source):
- `Cargo.toml:3-5`: add member.
- `crates/ghostlight-dungeon/Cargo.toml:27`: replace with the library
path dep.
- `crates/ghostlight-dungeon/src/main.rs:7`: delete.
- `crates/ghostlight-dungeon/src/runtime.rs:3-22`: split the `use crate::{}`
block; `world::{…}` becomes `use ghostlight::{…}` (probe edit); `:4`:
import `VerifiedPrincipalEvidence` from `ghostlight`, not `app_session`.
`:518,519,535,1084,1088,1092,1201,1325,1621,2492,2493,2581,2582,3081,
3501,3568,3658,3666,3675,3677,3777,3782,4267`: `crate::world::` →
`ghostlight::`. `:4313`: `::fixture(` → `::new(`. `:3081-3086`: drop
the three `fixture_inference_*` names. `:3243,3310,3434`:
`PreparedInference::prepare("ghostlight-controller-test",
4_102_444_800_000, request)` (Q1-7 A; the two literals are the ones
`fixture_prepared_inference` hard-codes at `controllers.rs:381`).
`:3255,3442,3447`: `InferenceOutput::new(vec![InferenceEvent::Text(..)],
"sha256:<receipt>")`; `:3457`: `InferenceOutput::new(events, ..)`;
`:3318`: `InferenceFault::integrity_violation(..)`; `:3479`:
`InferenceFault::recovery_required(..)`. `:3567-3644` (Q1-8 A): replace
`fixture_controller_opportunities` + `FictionalMinutes(..)` with
`fixture().await`, `active_two_cell_world`, `snapshot()`, and
`agency_graph()`, then `derive_cover(snapshot.world_id, snapshot.now,
CLOCK_TICK_MINUTES, &snapshot.opportunities, &graph, budget)`; the
cell count assertion becomes 2 (a genesis world has two
controller-bearing subjects — `:3089-3095` already says this is the
most `world.create` can produce); the ordering and shared-tick
assertions are unchanged. `:504,2673` doc comments name
`world::consumer`; reword to the crate.
- `crates/ghostlight-dungeon/src/eve.rs:3-6` and `:182,335,338,354,386,
405,449,494`: same rewrite.
- `crates/ghostlight-dungeon/src/mesh.rs:6-9`: same.
- `crates/ghostlight-dungeon/src/idunn_health.rs:8`: same.
- `crates/ghostlight-dungeon/src/app_session.rs:54-91`: delete; `:6`: add
`use ghostlight::VerifiedPrincipalEvidence;`; `:232-235`: struct literal
→ `VerifiedPrincipalEvidence::new(session.account_subject_hash.clone(),
session.access_expires_at)`.
- `crates/ghostlight/src/controllers.rs:221-237,372-382,409-432` (Q1-7 A):
delete the fixtures; `:388` `prepare_invocation` → `pub fn
PreparedInference::prepare` (keep the body; the two in-library callers
at the connector and SDK ports follow); `:150` add `pub fn new(events,
receipt_digest)`; `:192,206` `new` → `pub fn retryable`,
`integrity_violation` → `pub`, add `pub fn recovery_required(detail)`
(the `RecoveryRequired` disposition has a private `new` today; make it
the named constructor); `:277-370` drop `#[cfg(test)]` from
`TracingInferencePort` and make it and `new` `pub`.
- `crates/ghostlight/src/sdk_inference.rs:1824-1828`: the scanned file
list becomes `["sdk_inference.rs", "controllers.rs"]` (paths are now
crate-root relative); `:1860` `sources[1]` still indexes
`controllers.rs`. The `runtime.rs` half moves to Dungeon (Adds).
- `deployment/idunn/recipe.toml:14-17`: `test-world-owner` becomes two
steps — `test-world-library`: `["cargo","test","--locked","-p","ghostlight"]`
(runs the 420 unit tests and the 10 doc-tests) and `test-dungeon`:
the existing `-p ghostlight-dungeon --bin ghostlight-dungeon` line.
`:51-53`: acceptance argv becomes `-p ghostlight --lib
controllers::tests::real_codex_connector_cognition_modes_commit_speech`
(the `world::` prefix is gone; `--exact` still matches).
- `package.json:9` (`dungeon:run`): unchanged; `:7-8` use `--workspace`
and pick the crate up.
- `notes/local-live-smoke.md:64`: unchanged; the ignored smoke stays in
`runtime.rs:3697`.
- Docs that name the old path (owner in brackets): `README.md:165-166`
[Hands] add the library line; `docs/public-architecture/index.md:46`
[Hands]; `docs/architecture/ghostlight-session-zero.md:21-23` [Hands]
rewrite "Source does not yet match" as the current rule;
`docs/architecture/ghostlight-world-ontology.md:939-941` [Hands] the
build-budget sentence now names `crates/ghostlight`;
`notes/ghostlight-current-system-map.md:18,28,289` [Mind steward];
`notes/fresh-workspace-handoff.md:284-286` [steward];
`state/map.yaml:57,389-390` [steward].
- **Authority map:**
- Owner: the library crate `ghostlight` owns the world kernel, its
ontology, reducer, journal, mailbox, controllers, elaboration, cover,
clock, consumer admission, inference ports (connector, SDK sidecar,
and the tracing decorator), and the markdown evidence source. Its
public surface is the list under Adds and nothing else.
- Inputs: `VerifiedPrincipalEvidence` values Dungeon constructs from
`AppSessionOwner::account_for_cookie`; `CreateWorldIntent`,
`PrincipalCommandIntent`, `DecisionInvocation`; consumer patch bytes via
`admit_document`; store paths via `WorldMailbox::open` and
`open_controller_work`; connector and SDK bindings via `open_inference`;
a consumer-implemented `InferencePort`/`ControllerWorkStore` when the
consumer supplies its own (Dungeon's tests do; production uses the
library's).
- Outputs: immutable `WorldSnapshot`, `OperatorEvent`, `AgencyGraph`,
typed receipts (`SubmitReceipt`, `CommitReceipt`, `CreationReceipt`
through `MailboxError`/`KernelError`), controller runs, cover
partitions, encoded consumer receipts.
- Derived state: Dungeon's Eve projection, mesh documents, Idunn health
(which reads `STATE_SCHEMA` and `state_schema_compatibility_tag` and
derives, never restates), HTTP responses.
- Forbidden writers: any path in Dungeon naming `WorldKernel`,
`WorldState`, `reduce`, `apply_effect`, `CommandEnvelope`,
`AuthenticatedCaller`, the journal, an `issue()`, or
`ScopeDigest::fixture` — enforced by visibility with no feature that
can lift it, proven by the doc-tests under `--all-features`. Any second
minter of `VerifiedPrincipalEvidence` — enforced by the Dungeon count
test. Any fixture-shaped `DecisionOpportunity` — there is no
constructor for one outside the reducer.
- Shared paths: Dungeon production and Dungeon tests reach the kernel
through the same `pub` items; a Dungeon test port constructs port
values through the same constructors the library's own ports use
(Q1-7 A). Library-internal tests keep `pub(crate)`/`super::` access as
today. Consumers other than Dungeon: none yet; Epiphany consumes only
`ghostlight-persona-projection`, which is unchanged (Q1-5).
- Deletion line: `mod world;`, the nine unused re-exports, the
`#[cfg(test)]` re-export block, the `fixture_*` functions (A) and
Dungeon's private principal struct are gone before the first `pub` is
written.
- **Verification** (Windows workstation; proves Windows only):
- builds: `cargo check -p ghostlight` (no new warnings; the 646
dead-code warnings of an under-opened boundary must be 0),
`cargo check -p ghostlight-dungeon --bin ghostlight-dungeon`,
`cargo check -p ghostlight-dungeon --tests`,
`cargo build --locked -p ghostlight-dungeon --bin ghostlight-dungeon`
(proves `Cargo.lock`). Expected target-dir delta: one extra lib crate
in debug; the scratch probe's check-only target was 2.3 GiB from empty,
so expect well under 1 GiB incremental on the repo's 7.5 GiB.
- tests: `cargo test -p ghostlight` = 420 unit + 10 doc (the 420 names
equal the base `world::` list with the prefix stripped);
`cargo test -p ghostlight-dungeon --bin ghostlight-dungeon` = 49
(same names as base);
`cargo test -p ghostlight-dungeon --test build_provenance` = 1;
`cargo test -p ghostlight-persona-projection` = 13. Ignored counts
unchanged (1 + 1). The reopen test from Cut 0 pins invariant 2
(`world.cc` written at base reopens with equal revision and digests).
The doc-tests pin invariant 1. The `VerifiedPrincipalEvidence::new`
count pins the single minter. The split credential-name test pins
"no credential name in the port's source" on both sides. Tests 1–4
keep their names and assertions (test 4's cell count is 2).
- negative:
`cargo test -p ghostlight --all-features --doc` = 10 passed (same as
without; the command is the standing check that no later feature
reopens the seal);
`rg -n '\[features\]' crates/ghostlight/Cargo.toml` = 0;
`rg -n 'cfg\(any\(test' crates/ghostlight/src` = 0 (no feature-gated
test path exists);
`rg -n 'fixture_' crates/ghostlight-dungeon/src` = 0 outside the
Heimdall `::fixture(` sites (`app_session.rs:560`, `runtime.rs:2552,
2611,4126` — use `rg -n 'fixture_[a-z]' …` which they do not match);
`rg -n 'crate::world::' crates` = 0;
`rg -n '^mod world;' crates` = 0;
`rg -n 'app_session|heimdall|eve::|idunn_health|axum|tower_http|jsonwebtoken|\bDungeon\b|Session Zero' crates/ghostlight/src` = 0
(collisions checked: `Dungeons` in `vault.rs` is excluded by `\b`;
do not add `player`);
`rg -n 'pub\(super\)' crates/ghostlight/src/lib.rs` = 0;
`rg -n 'VerifiedPrincipalEvidence::new\(' crates/ghostlight-dungeon/src`
= 1 outside `#[cfg(test)]`;
`cargo tree -p ghostlight` names no `axum`, `tower-http`,
`jsonwebtoken`, `cultnet-rs`, `cultmesh-rs`, `reqwest`, `aes-gcm`,
`hmac`, `rand`, `base64`, `libc`;
`git diff -M --stat 02bbf62..HEAD -- crates` shows 13 renames.
- operator: Idunn recipe run on Yggdrasil (Linux proof): the
`test-world-library`, `test-dungeon`, `build-daemon` steps and the
acceptance step resolve; `/srv/…/ghostlight-dungeon --state-root`
reopens the live `world.cc`; health reports `consumer-v4`. One
`GHOSTLIGHT_SMOKE_TRACE` road run after the cut shows the membrane
trace still writes (test 5).
- **Operator questions:**
- Q1-7 Port value constructors for consumer-implemented ports. Tests 1,
2, 3 and 5 implement `InferencePort` outside the library and must
return `PreparedInference`, `InferenceOutput`, `InferenceFault`; today
they do it through `#[cfg(test)]` `fixture_*` wrappers that exist only
because those types have private constructors. A: make the
constructors the port contract — `PreparedInference::prepare(caller_
runtime_id, expires_at_unix_ms, request)` (rename of the existing
`prepare_invocation`, "the one place a `PreparedInference` is built",
which every in-library port already calls), `InferenceOutput::new(events,
receipt_digest)`, `InferenceFault::{retryable, recovery_required,
integrity_violation}`, `InferenceRequest::provider_model`; delete the
five `fixture_*` items; make `TracingInferencePort` an ungated `pub`
decorator (it wraps any port and constructs nothing sealed; "production
never constructs it" becomes a Dungeon rule, which is where it was
enforced anyway — only the ignored smoke names it). B: keep every
fixture `#[cfg(test)]` in the library and delete tests 1–3 and the
`trace` field of `LiveController` (`runtime.rs:2538,3726`) from
Dungeon; the permit-pool, quarantine, and interrupted-arm invariants of
the tick driver lose their proofs and the road test loses its membrane
trace. **Recommended: A.** A public trait whose methods must return a
type nobody outside the crate can construct is not a port; it is a
trait only the library can implement. Invariant 1 seals the kernel,
not the inference transport, and none of these constructors mints an
ID, mutates state, reduces, or writes the journal. A is a net
deletion (about 85 fixture lines out, about 25 constructor lines in,
of which `prepare` is a rename).
- Q1-8 The cover for `drive_one_tick_runs_every_cell_before_the_clock_and_all_share_one_tick`.
A: derive it from a real world through production ingress — the
module's own `fixture()`/`active_two_cell_world`, then `snapshot()` and
`agency_graph()` into `derive_cover`; delete
`fixture_controller_opportunities` and the `FictionalMinutes(u64)`
construction; the test asserts two cells instead of three, and the
ordering and shared-tick assertions are unchanged. B: delete the test.
C: keep `fixture_controller_opportunities` `#[cfg(test)]` in the
library and move the test there — not available, `drive_one_tick` is
Dungeon. **Recommended: A.** It removes the last caller of the sealed
constructors from outside `world/`, uses only what tests 1–3 already
use, and the test's own doc (`:3558-3565`) is about ordering, not
about three.
## Cut 2. Build and deploy references in gamecult-ops
- **Repo/branch:** gamecult-ops, current default branch; one commit after
Cut 1 is pushed.
- **First:** `git -C F:\Projects\gamecult-ops status` clean;
`bash scripts/test-ghostlight-yggdrasil-wiring.sh` passes at base.
- **Deletes first:** none (Q1-6: retirement belongs to the deployment
gate).
- **Keeps and moves:** none.
- **Adds:** none.
- **Per-file changes:**
- `runbooks/ghostlight-dungeon-yggdrasil.md:249-251`: insert
`cargo test --locked -p ghostlight` before the Dungeon test line;
`:257` "one explicit Rust binary" stays true.
- `scripts/deploy-ghostlight-yggdrasil.sh:964-970`: add the library test
invocation in the same container run; `:1308`: acceptance becomes
`-p ghostlight --lib controllers::tests::real_codex_connector_cognition_modes_commit_speech`.
- `scripts/test-ghostlight-yggdrasil-wiring.sh:276-278`: add
`require_text "${deploy}" 'cargo test --locked -p ghostlight'`.
- `idunn/yggdrasil/bindings/ghostlight.toml.in`: unchanged; it names the
recipe path, and the recipe carries the commands.
- The scripts remain, per the Ghostlight handoff (`:389-391`), helpers
not to invoke: they fail at the root/Idunn Git boundary and hold
duplicate deployment authority. Editing them keeps their command list
from lying about the crate graph until the deployment gate retires
them; it is not an endorsement to run them.
- **Authority map:**
- Owner: `deployment/idunn/recipe.toml` in Ghostlight owns the build and
test commands (binding `:11 recipe_path`). The runbook describes; the
scripts are a second, dormant list pinned to the recipe's strings by
the wiring test until the deployment gate removes them.
- Inputs: the admitted ref and the recipe.
- Outputs: the same one binary plus `web/`.
- Derived state: runbook text, wiring-test assertions.
- Forbidden writers: no second list of cargo commands that drifts from
the recipe; the wiring test's `require_text` lines are that check.
- Shared paths: n/a.
- Deletion line: none in this cut.
- **Verification:**
- builds: none (shell and Markdown).
- tests: `bash scripts/test-ghostlight-yggdrasil-wiring.sh` passes with
the new `require_text`.
- negative: `rg -n 'ghostlight-dungeon --bin ghostlight-dungeon' F:\Projects\gamecult-ops --glob '!docs/**'`
lists only lines that also sit beside a `-p ghostlight` line.
- operator: the next Idunn deploy of a post-Cut-1 commit runs the
library step.
- **Operator questions:** none; Q2-1 was Q1-6 and is ruled.
## Subtraction ledger (estimate)
| Cut | Removed | Added | Deps / formats / targets |
|---|---|---|---|
| 0 | — | — | scratch captures only |
| 1 | `mod world;` (1), 9 unused re-exports (~3 lines), `cfg(test)` re-export block (12), Dungeon principal struct (38), Dungeon's direct persona-projection dep (1), `fixture_controller_opportunities` (26, Q1-8 A), inference fixtures (~60, Q1-7 A); ~140 lines | lib manifest (~28), workspace member (1), Dungeon dep (1), lock entry (~20), principal type in lib (~30), `pub use` boundary (~25), doc-tests (~30), runtime credential test (~25), minter count test (~15), port constructors (~25, Q1-7 A), recipe step (~6); ~205 lines. Visibility edits: 94 `pub(super)`→`pub(crate)`, ~150 `pub(crate)`→`pub` (items, fields, methods), 199 `crate::world::`→`crate::`, 32 `crate::world::`→`ghostlight::`; test 4 rewritten in place (~20 lines) | +1 lib crate, 0 features, 0 binaries, 0 new packages in `Cargo.lock`; 13 files renamed (~52k lines) |
| 2 | — | ~5 lines | 0 |
Net for L0: about +65 source lines, one crate, no feature. The growth is
boundary declaration (an implicit `pub(crate)` becomes an explicit `pub`
list plus its compile-fail proofs); the liability it retires is the
convention "Dungeon does not touch kernel internals", which becomes a
compile error with no feature that can lift it, and five fixture wrappers
that existed only to work around private port constructors.
Actual, reconciled 2026-09-16 against `6ddabca` (Ghostlight) and `647e57e`
(gamecult-ops):
| Area | Estimate | Actual |
|---|---|---|
| Crate sources incl. in-module tests | about +65 net | +1202 / −992 (+210 net) |
| Integration tests | not planned | +479 |
| Manifests and lock | about +50 | +50 / −2 |
| Ghostlight recipe | about +6 | +10 / −5 |
| gamecult-ops | about +5 | +61 / −9 |
The miss is explained, not hidden. The single-minter scanner grew about 110
lines chasing Soul's evasions and remains evadable (S4). The boundary needed
roughly 90 more public items than this map enumerated, each forced by a
compile error or a `private_interfaces` warning. The integration tests buy
ruling Q1-9, which postdates the estimate. Features and binaries added:
none, as estimated.
## Findings not assigned to a cut
- `deployment/idunn/recipe.toml:142-146,169-171` declare the world slot and
provided capability as `ghostlight.world_state.foundation.v0` /
`foundation-v0`, and `:150-154` the controller-work slot as
`ghostlight.controller_work.v3`; source is `consumer.v4`
(`mod.rs:84-85`, tag `consumer-v4`) and `controller_work.v15`
(`controllers.rs:75-76`). Pre-existing drift; L0 changes no schema
string, so it stays.
- `tests/build_provenance.rs` is never run by the recipe or the scripts:
`--bin ghostlight-dungeon` selects the bin's unit tests only. A
`cargo test --locked -p ghostlight-dungeon --test build_provenance` step
would be a recipe change with its own reason.
- `notes/ghostlight-current-system-map.md:18-19` still names the state
owner as `ghostlight.world_state.foundation.v0`; `:28` says "the private
`world::WorldKernel`". Both are stale before this cut; the steward owns
the rewrite.
- `runtime.rs:2492` is a `CommitReceipt` literal in Dungeon tests; it is
why `CommitReceipt`'s four fields are in the boundary at all. Under
Q1-8 A the same literal serves `drive_one_tick`'s fake clock submitter.
- `PreparedInference.invocation` (`controllers.rs:131`,
`CodexTransportInvocation` from `codex-connector`) stays `pub(crate)`. A
consumer port that talks to a real transport would need it; no such
consumer exists in L0, and opening it is a port-contract decision for
the pass that brings one.
- `web/` references nothing in `crates/`; `sidecar/claude-sdk/test/*` is
written by library tests under `GHOSTLIGHT_WRITE_SIDECAR_FIXTURES` and
read otherwise — path depth unchanged, nothing to do.

View file

@ -1,172 +0,0 @@
# Ghostlight library extraction (L0) postmortem
Written 2026-09-16. Evidence: the cut map
(`ghostlight-library-extraction-cut.md`), the target
(`ghostlight-library-extraction.md`), commits in Ghostlight and gamecult-ops,
and the Soul reports recorded in the map.
## Summary
The world kernel moved out of the `ghostlight-dungeon` binary into the
`ghostlight` library crate, and Dungeon became a consumer across a public
boundary. Thirteen files (about 52k lines) moved by rename with no content
change. The boundary is sealed by admission: external code may build a
syntactically valid ID, digest or opportunity, and the kernel rejects every
one it did not issue, proven by rejection tests written as an external crate.
gamecult-ops' build commands run the library tests they would otherwise have
skipped.
State at writing: landed and pushed in both repos, Windows-verified. The Linux
release is Idunn's recipe run on Yggdrasil and has not been exercised; no
Windows result proves it. The operator owes nothing for L0.
## Scope and invariants
The target set seven invariants: sealed kernel at the crate boundary, no
behavior or schema change, no Dungeon concept in the library, dependencies
pointing one way, a working release path, unaffected external pins, and one
new crate with no feature matrix. Excluded: every library capability of plan
step 15 L1–L4, schema renames, the network path for outside consumers, and
deployment cutover.
Invariant 1 changed meaning during the migration (ruling Q1-9). It began as
"sealed items are unreachable from outside" and ended as "the kernel rejects
anything it did not issue", because the first reading was not true of the
code and could not be made true without a design change L0 excluded.
## Timeline
| Cut | Repo, commits | Soul passes | Notable finding |
|---|---|---|---|
| Map | Ghostlight `02bbf62`, `6ddabca` | — | Classifying the fixture tests found no kernel test to move; Q1-7 and Q1-8 followed |
| 1 | Ghostlight `108b691..f859d2c` | 1 | F1: public types deriving `Deserialize` are constructible from outside; the compile_fail tests pin names only |
| 2 | gamecult-ops `6aba281` | 1 | The specified assertion was vacuous (substring match); the acceptance path had an unlisted fourth site |
| 2 fix | gamecult-ops `803f2c7` | 1 | Exact-line pins prove presence, not execution (`if false`, `true \|\|`, heredoc) |
| Q1-9 | Ghostlight `7c1d1e9` | — | Operator ruled unforgeable admission |
| 1 fix | Ghostlight `a8d3377..2865ea7` | 1 | F3's premise was wrong; forgeries differed from real digests in length |
| S batch | Ghostlight `bde05de..af9c95a` | 1 | Case-insensitive and hex-only comparisons survived |
| T batch | Ghostlight `b14507c`, `ab95d78` | 1 | None |
## Structural delta
| Area | Estimate | Actual |
|---|---|---|
| Crate sources, including in-module tests | about +65 net | +1202 / −992, +210 net |
| Integration tests | not planned | +479 (`crates/ghostlight/tests/external_admission.rs`) |
| Manifests and lock | about +50 | +50 / −2 |
| Ghostlight recipe | about +6 | +10 / −5 |
| gamecult-ops | about +5 | +61 / −9 |
The source overrun has two causes. The single-minter scanner in
`crates/ghostlight-dungeon/src/app_session.rs` grew about 110 lines chasing
Soul's evasions, and it is still evadable (S4). The public boundary needed
roughly 90 more items than the map enumerated, each forced by a compile error
or a `private_interfaces` warning. The integration tests were not in the
estimate because Q1-9, which requires them, was ruled after it.
Deleted: `mod world;`, nine unused re-exports, the `cfg(test)` re-export
block, five inference fixtures, `fixture_controller_opportunities`, and
Dungeon's own principal evidence struct. Added: one library crate, a public
`pub use` boundary, port constructors, ten compile_fail doc-tests, the
external admission tests, and two Dungeon soul tests. Parked: nothing.
Features added: none. Binaries added: none.
## What Soul caught
- **Untested rulings.** Ruling Q1-4 said sealed constructors must be
unreachable under every configuration. The code satisfied the letter
(no feature gate) and missed the intent: `Deserialize` is a public
constructor. Ten green compile_fail tests could not see it, and adding an
ID-minting `Default` impl left all ten green. It would have failed as a
false guarantee in any later review that trusted the target doc.
- **Tests pinning spelling, not behavior.** Every text scanner lost to a short
evasion: the minter count to an alias, a subdirectory, a type alias and a
function value; the gamecult-ops wiring test to a two-line deletion that
reattached the pinned line to the wrong container; its fix to control flow
around exact lines. Each would have let a real regression through with a
green check.
- **Forgery shape.** Rejection tests that used short fake digests passed
against a kernel comparing only length, only a prefix, all but the last
character, case-insensitively, or only the hex after the label. Each would
have admitted a digest the kernel never issued.
- **Spec errors.** The map's vacuous `require_text`, its unlisted acceptance
site, its miscount of Dungeon tests, and Soul's own F3 premise (the two
accessors it called uncalled are called) were all wrong, and all were
caught before landing a fix built on them.
- **Unmeasured claims.** "No new package in `Cargo.lock`", "zero `fixture_`
hits", "a guard that never fired", and a 13-warning ceiling nobody could
reproduce.
## Operator corrections
- **Session Zero is Dungeon authority.** The first design placed a player
flow on the kernel. Missing context: no document named which features
belonged to the library and which to a consumer.
- **Focus was too narrow.** Focus as a set of subjects became a typed detail
rule, a function from place to detail level. Missing context: Delvehold's
constraints as a consumer; the design generalized from Dungeon alone.
- **Extract first.** The library capabilities were designed before the crate
they belong to existed.
- **The titled elaborators** had been cut without an operator decision; the
cut conflated a verifier with the lenses it verified.
- **Proportion.** Asked how much Q1-10 mattered, the operator said not at
all. It was a tripwire against the project's own code, and Self should have
defaulted it instead of posing it.
## Incidents
- **A Hands agent returned its private to-do list as its report** while its
own background cargo job held the locks. Cost: one resume round. Rule:
briefs now say to wait for long jobs and never end a turn with a to-do list.
- **A mutation run was invalidated by `git checkout`** reverting uncommitted
fix code. Cost: two mutations rerun. Rule: run mutations against committed
code, or restore with a diff rather than a checkout.
- **Cached no-op builds reported zero warnings.** Cargo replays warnings only
when it rebuilds. Rule: measure warnings from a forced rebuild, and compare
distinct messages by `cmp`.
- **A commit message described code replaced before commit** (`fac90e6`).
Left in history; recorded in the map.
- **A pre-existing `cargo fmt --check` failure** across the library, found
in passing.
## What worked
- Classifying tests before moving them. Q1-4's "move the tests" had nothing
to move, and the classification turned a vague ruling into two concrete
ones.
- Soul building an external scratch crate to break the seal. The serde route
was invisible from inside the crate and to every doc-test.
- Holding map edits until Soul finished, so every Soul pass read a clean tree.
- Having Hands report spec discrepancies instead of redesigning: the vacuous
assertion, the fourth acceptance site, the recovery_required collision.
- Parallel Hands in separate repos only when the second did not depend on the
first landing.
## What to change in the pipeline
- **Brief Soul to attack constructibility, not names, on any sealed boundary.**
Evidence: F1 on Cut 1, found only because the root agent added the serde
route to the brief by hand.
- **Treat a text scanner as a tripwire with stated limits, never as proof of a
semantic property.** Prefer a semantic tool (Clippy lints, the type system)
or record the property as unenforced. Evidence: every scanner in L0 lost.
- **Rejection tests must use forgeries shaped like real values.** Evidence:
S1 and the two survivors after it.
- **Default proportionate questions instead of asking.** A fork that guards
only against the project's own code is a default with a recorded follow-up.
Evidence: Q1-10.
## Open follow-ups
| Item | Owner | Where | Why it can wait |
|---|---|---|---|
| S4 minter scanner evadable; Clippy `disallowed-methods` recorded as the fix | Dungeon | `crates/ghostlight-dungeon/src/app_session.rs:523-668` | Guards only against the project's own code |
| S5 credential-name test splits on one literal marker | Dungeon | `crates/ghostlight-dungeon/src/runtime.rs:3584` | Same class as S4, pre-existing |
| S6 stable rustc does not enforce compile_fail error codes | Library | `crates/ghostlight/src/lib.rs:15-57` | Admission is proven by the external tests; codes need a snapshot tool |
| S2 world_id check redundant, S3 decline path unreachable from outside | Library | `lib.rs:4193`, `lib.rs:1603` | Redundant by construction and crate-private respectively |
| `ScopeDigest`, `WorkLane`, `ScopeComponents` public through public enums | Library | `KernelError`, `ControllerWorkCustody`, `NarrativeCheckpoint` | Closing them reshapes public enums, a design change |
| `cargo fmt --check` fails across the library | Library | `crates/ghostlight` | Pre-existing; formatting only |
| Recipe schema drift (`foundation.v0`, `controller_work.v3` against `consumer.v4`, `controller_work.v15`) | Deployment gate | `deployment/idunn/recipe.toml` | Changes no behavior in L0 |
| `build_provenance` not run by the recipe | Deployment gate | `deployment/idunn/recipe.toml` | A recipe change with its own reason |
| Redeploy of a sealed commit runs no tests; exact-line pins cannot see control flow; `set -e` unpinned; duplicate blocks pass; web container and Connector steps pinned by substring; 18-line option window | Deployment gate | `gamecult-ops/scripts/deploy-ghostlight-yggdrasil.sh`, `test-ghostlight-yggdrasil-wiring.sh` | Legacy actuator under a do-not-invoke warning, retired at the gate |
| Linux release unverified | Operator, via Idunn | Yggdrasil | Needs the deployment gate |

View file

@ -1,84 +0,0 @@
# Ghostlight library extraction (plan step 15, L0)
Status: closed 2026-09-16. Landed in Ghostlight `108b691..ab95d78` and
gamecult-ops `6aba281..803f2c7`; the means and every Soul verdict are in
`ghostlight-library-extraction-cut.md`, the scars in
`ghostlight-library-extraction-postmortem.md`.
Reconciled with the Body. Invariant 1 holds as restated by Q1-9 and is
proven by `crates/ghostlight/tests/external_admission.rs`; the compile_fail
doc-tests prove "does not compile", not privacy, because stable rustc does
not enforce their error codes. Invariants 2, 4, 6 and 7 hold as written.
Invariant 3 holds for library source and tests: no Eve, Heimdall, AppSession
or player vocabulary remains. Invariant 5 holds on Windows; the Linux release
is unexercised until Idunn builds it. The open questions below were all
ruled (Q1-1 through Q1-10 in the cut map) and are kept as history.
## Target
The Ghostlight library is a crate of its own. It owns the world kernel and
everything consumer-neutral around it: the ontology and reducer, the journal,
the mailbox, controllers and the Projector-Persona-Interpreter membrane,
elaboration and seeding, the cover, the clock, inference ports, evidence
sources, and consumer patch admission. Ghostlight Dungeon is a crate that
consumes it: the daemon binary, HTTP routes, Eve projection, Heimdall and app
sessions, CultMesh publication, and Idunn health.
After the cut, "Dungeon cannot reach kernel internals" is a compile error, not
a `pub(crate)` convention.
## Invariants that must survive
1. **Sealed kernel at the crate boundary.** The library's public API exposes
create/open, immutable snapshots, command submission, typed receipts, and
the runner and port entry points Dungeon needs. It exposes no mutable
`WorldState`, canonical ID allocator, reducer entry, journal writer, or
authenticated-caller constructor. Negative proofs are compile-fail tests
from outside the library.
Sealing means **unforgeable admission**, not unconstructible values
(operator ruling Q1-9, 2026-09-16). Public ID types, `ScopeDigest` and
`DecisionOpportunity` derive `Deserialize` because Dungeon's own Eve
payloads carry them, so any caller can build a syntactically valid one.
The kernel must reject every one it did not issue, and rejection tests
written from outside the crate are the proof. A compile-fail test pins a
path name and cannot see constructibility: adding a `Default` impl that
mints an ID left all ten green.
2. **No behavior change.** Every existing test passes unchanged in meaning.
No schema string, command id namespace, digest preimage, or store layout
changes: a `world.cc` and controller work store written before the cut open
and replay after it.
3. **No Dungeon concept in the library.** No Dungeon type, route, Eve or
Heimdall type, HTTP framework, or principal format enters the library. The
principal evidence the kernel needs crosses as a library-owned type that
Dungeon constructs from its own sessions.
4. **Dependencies follow ownership.** The library does not depend on axum,
tower-http, jsonwebtoken, or the Heimdall and Eve surfaces. Dungeon depends
on the library, never the reverse.
5. **The release path keeps working.** The `ghostlight-dungeon` binary name,
its `--state-root` contract, and the Idunn recipe's build and test
invocations still resolve, or are updated in the same cut with their owners.
6. **Existing pins are unaffected.** Epiphany's pin of
`ghostlight-persona-projection` by revision still resolves.
7. **Build fan-out stays bounded.** One new library crate, no new binary, no
new feature matrix beyond what test support strictly needs.
## Out of scope
- Every library capability of plan step 15 L1–L4: lenses, detail rules,
evidence binding, Draft sessions. L0 moves code; it adds no behavior.
- Renaming schemas, stores, or wire documents.
- Changing how external consumers reach the library over the network. The
consumer patch HTTP route stays in Dungeon for now.
- Deployment cutover (the deployment gate).
## Open questions for Imagination to bring back
- The library crate's name.
- Whether `vault.rs` (markdown evidence source) and `sdk_inference.rs` (Claude
SDK port) belong in the library, as consumer-neutral adapters, or in Dungeon.
- The seam for principal evidence (`app_session::VerifiedPrincipalEvidence`).
- How test fixtures that span the boundary are shared without making sealed
constructors public.
- Whether `ghostlight-persona-projection` stays a separate crate or folds into
the library.

File diff suppressed because it is too large Load diff

View file

@ -1,236 +0,0 @@
# Play agent postmortem
Written 2026-09-23 from the cut map, the commits, the Soul reports and an Eyes
pass over all three. The cut map
(`docs/architecture/ghostlight-play-agent-cut.md`) remains the detailed record:
every cut's status, findings PA.f1 to PA.f195, and every ruling.
## Summary
Ghostlight Dungeon now runs on one operational agent. It reads the world through
an omniscient table view, calls kernel tools directly as the Play authority,
dispatches characters for their own narrative turns, asks the player questions,
and closes each turn with narration. `world.speak` and the story card are gone;
`world.play` and a single player card replace them.
Seventeen cuts and about ten fix batches landed over two days. 195 findings were
recorded. The kernel gained a Play authority, ruled facts, minting, retirement,
affordance grants and a callable Persona turn. A loopback-only local inference
port landed so the whole thing can run against a small model on the operator's
own machine.
State at writing: the loop is built and verified as far as tests and a falsifier
reach. **Nobody has played it, and no model has ever run behind the local port.**
The seed path has never executed past its configuration check. All evidence is
Windows; the release evidence is Idunn's Linux gate on Yggdrasil.
Two capabilities the design promises do not exist: fiction-first risk resolution
and gestalt agency. They are named in *Open follow-ups* and carried into the
target doc as gaps rather than promises.
## Scope and invariants
The pivot: the previous machine was built for offline narrative generation and
world simulation, which is the wrong set of compromises for play. The Persona
sandwich stays, because actors should think narratively; everything else — turn
dispatch, interpretation, prompting the player, negotiating the result — becomes
one operational agent's job.
Eight invariants scoped the work. The kernel is the only writer and no
transcript crosses turns; Personas never see structured state, and the agent
never rewrites an existing character; an actor acts only through its own
affordance; speech is verbatim, checked against that actor's own prose; there is
one play authority; removal is retirement; one loop serves every backend; and
the player sees a projection, the question, and the refusal of their own act,
and nothing else.
Explicitly out of scope: the offline simulation lanes, which keep total
interpretation; Njordr's evidence invariants, which the operator ruled do not
bind the play agent ("if the agent can invent people, it can invent loot"); and
the world compiler.
## Timeline
| Cut | What | Commits | Notable finding |
|---|---|---|---|
| 1 | Delete the autonomous drivers and owner controls | `d69e9d4` | −2,184 lines. A re-added tick loop passed 46 of 46 tests |
| 2 | The local inference port | `182f803` + fixes | `HTTP_PROXY` sent the whole request, and a credential, to a proxy (PA.f16) |
| 3 | Play authority, ruled facts, minting | `4c4973b` | The genesis lane never ran `require_ruler` (PA.f26) |
| 4 | Retirement | `3725ba8` | A retired subject was still an audience and a raw speaker (PA.f33) |
| 5 | Grant and revoke affordances | `732b1d3` | Two loosenings survived every test (PA.f30, PA.f35) |
| 6 | The Persona lane and the recency marker | `c4334cc` | The spec's own stated rationale was impossible; Hands corrected the spec |
| 7 | The table vocabulary and inference seams | `7d40393` | `actor_tools` emitted names `decode_actor_call` refused (PA.f55) |
| 8a | The play table and the turn loop | `6b69270` | `communicate` let the agent make any actor "tell" an invented fact (PA.f61) |
| 8a-fix2 | | `74b628d` | Every mutation reported killed; eight rules unguarded |
| 8a-fix3 | | `754c7fe` | The id spelling had four copies; changing the printer passed 735 tests and broke every dispatch (PA.f113) |
| 8a-fix4 | | seven commits | Not ready for 8b: a crash window stranded a dispatched Persona (PA.f125) |
| 8b | Wiring, routing, the Eve schema | `1b20a0f`, `a99fdfe` | `ask_player` wedged the world: no client could build an answer (PA.f134) |
| 9 | The play surface; `world.speak` deleted | `322bdf6`, `f1732c0` | The real client could not submit anything at all |
| 10 | The client round trip | `d9f0159`, `43b6af6` | `world.create` had no field for `brief`: no client could ever create a world |
| 11 | The answer path and the gate | `4155823` | Two of three bridge tests failed instead of skipping without node |
| 12–13 | The store schema; the answer token | `7052644`, `2f2a8b6` | An answer composed for one question resolved another (PA.f170) |
| 14 | Preflight fixes | `58324f8`, `0808c6a` | The seed refusal handed the player the inference endpoint's URL (PA.f187) |
| 15 | The closing fixes | `f295a3a` … `1dea8f5` | An unwritten invariant, stated and broken in one commit (PA.f193) |
| 16–17 | Closing the bar | `63964b0` … `07aae19` | The runbook's weekly check printed `ok` without running (PA.f194-B) |
## Structural delta
New: `local_inference.rs`, `table.rs` (the consumer-neutral vocabulary),
`play.rs` (the turn loop), `tools/eve_client_bridge.mjs` and its committed
fixture. Two dependencies: `reqwest` for the local port, `unicode-segmentation`
for UAX #29 word boundaries.
Deleted: Cut 1's tick driver, Active elaborator and owner "let X act" path
(−2,184 lines, and ten tests whose only subject was deleted code); Cut 9's
`SpeakPayload`, `world.speak` arm, story card, speak control and
`current_operator_view`.
Tests: the library went 466 → 622 and has been flat since the play loop's third
fix batch — all later churn is Dungeon-side. The Dungeon binary went 56 → 46
(Cut 1's deletion) → 182, plus four client-bridge tests that are `#[ignore]`d
behind an opt-in. `ghostlight-persona-projection` went 13 → 35.
The subtraction budget was met once, at Cut 1, and not thereafter. Every fix
batch was net additive, mostly in tests. Soul audited the largest claim (Cut 13's
"~150 lines") and found 29 lines of production code; the rest was comments. That
is defensible, but the ledger stopped being a pressure after Cut 1 and nobody
noticed until this postmortem.
## What Soul caught
Of roughly 195 findings, about 150 were introduced by this pass's own earlier
steps rather than inherited. That is the honest shape of a foundation change:
each fix is a fresh chance to be wrong, which is why the falsifier never grades
its own work.
**Split authority (~14).** Four copies of one id spelling, because the library's
printer was private to its module (PA.f113). Two computations of the retired set
and of the exercise revision (PA.f82). Two owners for round entry (PA.f127). The
resume path's collision check duplicated verbatim (PA.f118).
**Tests that pinned spelling or passed trivially (~13).** A dependency check
asserting `contains("0")`, always true. A test that failed one run in four and
checked the wrong subject when it passed. Two refusal tests whose expected kind
was a substring of their own fixture's handle.
**Mutations aimed at the wrong layer (~4).** Deleting an in-memory record
instead of the on-disk write it stood for; testing a helper instead of its call
site; every test using a fresh key, so deriving the turn id from the key
survived.
**Inputs built from a copy of production logic (2).** The dispatch tests spelled
their subject id with a fourth copy of the printer, so changing what the world
view actually printed left 735 tests green while every dispatch an agent could
make was refused.
**Forged input accepted (~6).** A forged opportunity, a forged revision, a
deserialized colliding subject id, and a ruled fact riding in through world
creation.
**Player-visible leaks (~10).** The question id rendered as a visible, editable
box. A connection-refused error handing the player the inference endpoint's host
and port. A subject census on a card any authenticated account could see.
**Lifecycle and crash windows (~11).** A fresh request key discarding an open
turn; an empty answer wedging it forever; a spent round budget leaving it
running with nothing said; a crash between persisting a Persona's prose and
recording the call that produced it, which stranded that character for the rest
of the turn.
**Things the real client could never do (~5).** The binding shape did not match
what the client sends, so every command submitted an empty payload — including
`world.create`, which also had no field for a value its own contract required.
Nobody had ever driven the real client end to end.
## Operator corrections
Eight questions were ruled by the operator directly, and one correction changed
a design mid-pass. Self had suggested updating an existing character's attitude
through `set_persona_material`; that collapses the no-puppets rule, and the
ruling was reversed so the agent authors new characters and never rewrites an
existing one. The operator's review — *"I saw those calls in your traces, I've
been watching. No objections"* — arrived after the reversal rather than before
it.
The operator also cut a scope error at the root. Self proposed binding the play
agent to the offline lanes' evidence invariants; the ruling was *"if the agent
can invent people, it can invent loot"*, which is what made ruled facts and
minting coherent rather than a hole in the model.
What made the wrong answers look right in both cases: the agent was reasoning
from the library's offline discipline, where those rules are correct, without
noticing that the play path has a different author and a different purpose.
## Incidents
- **The workstation rebooted mid-pipeline** under concurrent cargo builds, mine
among several sessions'. Rule: one cargo process at a time on the workstation,
in every brief, and verification moves to Yggdrasil under Idunn.
- **A Hands agent amended and force-pushed** over its own first push of Cut 3.
Nothing was lost, because it had rebased first. Rule: never amend, never
force-push; it is now in every brief and in the skill.
- **A Soul pass died on an API 529.** Its worktree was cleaned and the pass
rerun.
- **A `git pull --rebase` was refused** while Hands had unstaged work in the
shared tree. Rule: never pull in a tree where Hands is working. (Observed in
session; not recorded in the cut map.)
- **PowerShell map edits failed** on an overload error and on mismatched
anchors. Rule: Python scripts that assert each anchor occurs exactly once and
preserve CRLF. (Observed in session.)
- **A stray `node_modules`** left by an agent's own debugging made a test count
report success for tests that could not run on a clean checkout (PA.f162).
## What worked
- **Quoting the cut inline in the brief** instead of pointing at a 3,900-line
map. The one run that read the whole map reached ~400k tokens and produced the
pass's sloppiest claims.
- **Hands stopping on a real fork.** Cut 9's counter had no honest derivation;
Hands traced why, stopped, and reported. The ruling took one message and the
cut resumed correctly.
- **Soul driving the real client.** Every blocker in the last third of the pass
came from running the vendored browser lowering over the served surface rather
than from reading it.
- **Recording a finding as closed-not-fixed when the mutation proved the code
unreachable.** Hands built a guard, mutated it, found an existing guard already
refused, reverted its own work and kept the test. The mutation decided, not the
diff.
## What to change in the pipeline
Three lessons are already in the Eureka brief and changelog:
1. **Mutate the production call site, at the layer the rule protects** — a later
write can hide a deleted one (`fd01545`).
2. **A test's inputs come from the production path**, never from a helper that
re-spells what production prints (`2e0ea97`).
3. **Name the inference, not the line** (`181e819`). One defect shape ran through
five instances: a committed file exists, therefore the client works;
`git` exited zero, therefore this is a checkout; the format check failed,
therefore the row is unreadable; the schema is unknown, therefore the row
cannot be read; cargo printed `ok`, therefore the fixture is live. Each local
fact true, each inference false, each fix scoped to the reported instance. And
after changing how a test reports, run the owning runbook's commands verbatim
and read what they print: that surface is the one a test suite structurally
cannot check.
Two more this pass earns:
4. **A subtraction ledger that stops being updated stops being pressure.** It
held at Cut 1 and then went unexamined for sixteen cuts.
5. **Soul's closing pass should be briefed for a walk-through, not only a
verdict.** Asking what happens when a person actually sits down and plays
produced the most useful output of the pipeline, including two defects no
invariant covered.
## Open follow-ups
| Item | Where | Why it can wait |
|---|---|---|
| Fiction-first risk resolution | kernel + `play.rs` | The kernel resolves a risky act through an affordance's weighted outcome bands, drawn deterministically. There is no assessment step, no modifiers, and the agent cannot author affordances — so an act no granted verb expresses is authored directly as a ruled consequence with no draw at all. Those two paths are indistinguishable to the player. This is the next pipeline. |
| Gestalt and institution agency | kernel | Institutions exist as structure — offices, grants, jurisdiction — and constrain who may act. Nothing makes them act. Advancing time rolls routines and accumulates pressure; nobody deliberates off-screen. |
| The seed leg | `runtime.rs`, vault | Never executed past its configuration check. `GHOSTLIGHT_SEED_VAULT_ROOT` appears in no runbook. Attempt it alone, first. |
| PA.f194-A's fourth exit | `play.rs` | Closed in Cut 17, listed because its rule now lives on `retire_unreadable_row` as a precondition and every future caller must satisfy it. |
| PA.f195-B, PA.f195-C | `play.rs`, `runtime.rs` | A dead tuple element, and a skip notice cargo swallows without `--nocapture`. Trivial. |
| `state/map.yaml` is not parseable YAML | `state/` | Latent: nothing reads it programmatically. Fixing it is a deliberate sweep, not a drive-by. |
| A read path for a retired row | `play.rs` | The sidecar is JSON with the payload in base64, so an operator can read it. Nothing imports one back. |

View file

@ -1,332 +0,0 @@
# Ghostlight Dungeon play agent (plan step 16)
> Status: the Dungeon daemon described here is parked at tag `parked/ghostlight-eve-surface` (2026-10-22); it is not on main.
## Status
Target, adopted 2026-09-22. Not implemented. The means will be in
`ghostlight-play-agent-cut.md`. This target is the playtest gate. It replaces
library passes L2–L4 and Dungeon passes D1–D3 on the gate's path; those are
deferred by ruling, not dropped (see "Deferred").
## Why
Ghostlight's controller machinery was built for offline narrative generation
and world simulation. It includes the cover partition, grouped cells,
grant-filtered action catalogs per subject, a separate Interpreter pass, and
the elaborator swarm. Those are the wrong compromises for interactive
role-play: today a reply takes minutes, and a player's whole vocabulary is
`world.speak`.
The operator, 2026-09-22:
> the way Ghostlight previously ran is great for offline narrative generation
> and world simulation, but it's the wrong set of compromises for an efficient
> role-playing experience. The Persona stuff is good, we want actors to think
> narratively. All the rest of it can be operated by a single operational
> agent, from dispatching and interpreting Persona turns to prompting the
> player and negotiating the result.
What makes this worth building is where consistency lives. In AI Dungeon it
lives in the context window, so it decays as the story grows. In Ghostlight it
lives in the kernel: typed state, one reducer, affordance preconditions,
outcome bands, and a digest-chained journal. None of that spends a token. A
small local model therefore does only what it is good at, which is judgment
and prose over a bounded context, while the kernel keeps the books.
## Target
A player on one local machine plays a world seeded from a Vault, turn by turn.
The reference machine is Raven's, running Bonsai 2, a Qwen 3.8 quant tuned for
agentic use, with several concurrent slots. One operational agent (the **play
agent**) runs the table: it reads the world, interprets what the player and
the Personas do, commits the consequences through the kernel, dispatches
Personas, and asks the player questions when an outcome needs negotiating.
Personas keep thinking narratively. For each Persona, the existing Projector
renders that subject's own slice of the world into lived prose. The Persona
reads only that prose and writes prose back. Neither the Projector nor the
Persona changes.
### Ownership
- **Dungeon** owns the play agent: its loop, its prompt, its tool catalog, the
turn lifecycle, and the Eve surface. None of it enters the library
vocabulary.
- **The library** gains only consumer-neutral pieces:
- one author capability for a play authority;
- retirement, and granting and revoking affordances;
- a callable Persona turn (Projector then Persona) that does not require
the controller runner;
- the table vocabulary (`table.rs`: the world view, named tool subsets and
their decoders, and refusal text), plus the public inference seams a
consumer needs to build and read a request.
A consumer other than Dungeon could run its own table on them. (Cut map
PA-Q10 and PA-Q12, ruled 2026-09-22.)
- The library keeps everything the play path stops using: cover, grouped
cells, action catalogs, the controller runner, the Interpreter, the elaborator
sweep, and lenses. Offline consumers and simulation still own them.
### One turn
1. The player types. Their text is prose from an actor, exactly as a Persona's
is.
2. The play agent reads a projection of world state rebuilt for this turn. It
interprets the player's prose. Speech commits verbatim through the player
subject's speaking affordance, and acts commit by exercising the player
subject's affordances. The agent may instead **ask the player** something
("what are you offering him?"). A question commits nothing and holds the
turn open.
3. The agent dispatches the Personas who react. They run concurrently, each
through Projector then Persona, reading what they perceived from world
state.
4. The agent interprets each Persona's prose under the same rules as the
player's, and commits its own rulings for anything no actor's affordance
covers.
5. The player sees their projection. The Projector renders the player
subject's own slice, including what they perceived this turn, into prose,
exactly as it does for a Persona. Beside that prose the surface shows any
question the agent is asking.
## Invariants
1. **The kernel is the only writer, and the agent carries no world.** Every
consequence is a library command. The agent's context each turn is built
from world state and the current turn; no transcript is carried across
turns. Test: restart the daemon between two turns, and the second turn's
agent input is byte-identical to the input it would have received without
the restart.
2. **Personas never see structured state or the agent's context.** A Persona's
input is Projector prose. The Projector's input is that subject's own typed
slice (`controllers.rs` `projector_context`). The agent never writes a
Persona's input, so a secret in the agent's context cannot reach a Persona
except through world state that subject holds. The one input every
subject shares is the owner's world brief. It is world-public framing,
and the owner keeps secrets out of it (cut map PA.f45). The agent never
rewrites an existing character's persona material; it authors material
only for characters it declares. A character's feelings follow from what
it perceives (cut map PA.f61).
3. **An actor's act goes through that actor's affordance.** An act attributed
to a subject, whether a Persona or the player, commits only as that
subject's `ExerciseDecision`, with preconditions checked and the outcome
band drawn by the kernel. The agent's raw ops are its own rulings: they are
journaled with the play authority as author and never attributed to an
actor. (Operator ruling, decision 1.)
4. **Speech is verbatim.** Speech committed for an actor is a literal span of
that actor's prose, checked in code, not by prompt. This holds for the
player's typed text and for a Persona's output. It keeps the agent from
paraphrasing every actor into its own voice.
5. **One play authority, and only one thing holds it.** The library defines one
consumer-neutral author capability. Its holder may:
- declare in Active without answering elaboration demand;
- reach the whole world, unconfined to a ground;
- advance time;
- state facts that stand as `Ruled` by it;
- mint quantity without an evidence receipt.
Only the play authority gains the last two. Elaborators, consumers and the
seed keep the evidence gate, so a consumer feeding Njordr keeps quantity
provenance. The operator: "if the agent can invent people, it can invent
loot." (Cut map PA-Q15.)
The elaborator gate is unchanged: elaborator sessions still answer a
boundary or deficit. The agent is Dungeon's detail demand: when the player
walks into the tavern, the agent fills it. (Operator ruling, decision 1.)
6. **Removal is retirement.** A retired subject stays in history, holds no
opportunity, cannot be the actor of a decision, and is never dispatched.
Replay reproduces retirement. A body that matters afterwards is declared as
a resource.
7. **One loop, many backends.** Rust drives every tool round, as it already
does. A local OpenAI-compatible backend returns tool calls inert, as the
connector lane does, and adds no second loop. Routing stays per model
name, so each lane (agent, Projector, Persona, seed) is pointed at a backend
independently.
8. **The player's view is a projection.** The Projector renders the player's
narration from committed state, as it does for every Persona (operator
ruling, open question 11). Nothing the player is shown is world truth
unless it was committed. The surface also shows the kernel's refusal of
the player's own act, rendered from the refusal and the affordance's
preconditions. That is the world's verdict, derived from state, not a
claim of world truth (cut map PA-Q13). The agent's questions are the one
thing shown that is not derived from state.
## Playtest gate
Passes when a human, on a local daemon with every play lane on a local model,
does all of the following:
1. creates a world and seeds it from a Vault;
2. activates it;
3. plays at least these:
- speaks to a Persona and gets a reply in the Persona's own words;
- does something physical that a precondition refuses, and sees why;
- moves to another place;
- is asked a question by the agent and answers it;
- kills or removes a subject, who then never acts again;
4. restarts the daemon mid-session and continues with the world intact.
It proves one player. Hosted play, multiple players, Session Zero's Vault
choice and sliders, and detail rules are not in this gate. Seconds per turn
are **measured and recorded** on Raven's machine. The gate does not set that
number in advance, because nobody has measured Bonsai 2 on this workload yet.
The current baseline is minutes.
## Cut line
Dungeon's play path stops using:
- the owner-only "Let X act" controls and `world.controller.act`;
- automatic tick dispatch through cover cells on the play path;
- the Interpreter pass;
- the per-subject action catalogs;
- elaboration while Active.
Whether these are deleted from Dungeon or merely go unused is for the cut map
to establish, one surface at a time. Deletion is the default where nothing
else consumes the surface.
The library keeps them.
The Claude SDK sidecar stays as the cloud fallback until the local lane has
carried the playtest. It is the only live cloud provider (there is no Codex
subscription and no API budget), so "cloud fallback" means the sidecar. The
decision to delete it comes after the gate. This corrects the 2026-09-22 chat
default, which named the connector lane as the fallback.
## Deferred, by ruling (2026-09-22, decision 3)
Deferred until a consumer that still runs the offline machinery needs them:
- L1.f16, configurable lens sets (operator: yes);
- L1.f1, quarantine-class errors never quarantine;
- L1.f13, seed lane orphans rows;
- L1.f14, controller-work rows never retired;
- L2, per-world evidence binding;
- L3, detail rules;
- L4;
- Session Zero D1–D3.
After the gate, decide whether anything still consumes the controller runner,
cover and lenses. If nothing does, park them at a tag.
Exception: if the cut map finds that L1.f13 bites seeding on the playtest
path, it is in scope, because seeding is on the path.
## Open questions for the cut map
Imagination establishes each of these by probing the Body, and returns forks
with a recommendation.
1. **Where the local backend lives.** The shared seam today is the
in-process `InferencePort` trait, not a CultNet connector API. The SDK
sidecar is a private MessagePack child-process pipe that only borrows
`codex_connector` input types (checked 2026-09-22). No local or
OpenAI-compatible transport exists, so the gate has none to use yet.
The options are a third `InferencePort` in `ghostlight` that follows the
connector posture (~150 lines), or a connector behind a CultNet contract
that the operator wants and that does not yet exist. The map records "a
generic OpenAI-compatible connector is required before third parties use
the deployment", so this pass may be that connector. The handoff says
nothing goes into CodexConnector itself.
2. **What a Persona perceived.** Does the Projector's context already carry
what the subject perceived since its last turn (speech heard, acts seen,
`Seen { by }` knowledge)? If not, what is the smallest addition?
3. **A callable Persona turn.** Projector then Persona currently runs inside
the narrative lane of `ControllerRunner`, with checkpointing. What is the
smallest library surface the play agent can call per subject, and does it
keep resumability?
4. **Exercising on an actor's behalf.** `ExerciseDecision` is admitted for the
subject's controller principal. How does the play authority exercise an
affordance for an actor it dispatched without weakening sealed admission,
given that opportunities and digests are kernel-issued?
5. **The play authority's shape.** Name the capability, where it is granted,
and how the clock capability's precedent maps onto it.
6. **Retirement's shape.** Is it a component op, a declaration, or a subject
state? What do preconditions, opportunity derivation and the Projector read?
7. **The agent's catalog.** The kernel's component ops plus light declarations
(not `declare_affordance`), plus exercise-for-actor, dispatch-Persona,
ask-player and end-turn. Measure the strict-schema size, and say whether a
small model plausibly handles it.
8. **The turn lifecycle.** Where does an open turn (a question outstanding, or
Personas in flight) live, and what survives a restart (invariant 1)?
9. **The Eve play surface.** Place, co-presence, perceived speech with speaker,
displays, the agent's question, and the player's input.
10. **The player's subject.** Does the genesis human subject at the commons
serve, with the agent placing it after seeding?
11. **The player's prose.** Ruled 2026-09-22, operator: the player's
perception is rendered by the same Projector a Persona gets. "Render it
with the Projector; we're paying for it on every Persona already." The
Projector renders only committed state, which satisfies invariant 8, and
it is the player's narration; the play agent writes none. The cut map
measures the extra serial call rather than deciding on it.
## Verification sketch
The cut map owns exact tests. Each invariant gets a check that fails under its
own mutation.
- **Invariant 1:** restart equivalence of the agent's turn input.
- **Invariant 2:** the Persona's request contains no field of structured state
and none of the agent's context.
- **Invariant 3:** an act for a subject not present is refused, and a raw op
never carries an actor attribution.
- **Invariant 4:** a paraphrased quote is refused.
- **Invariant 5:** an elaborator's declaration in Active without an answer is
still refused, and the play authority's is admitted.
- **Invariant 6:** a retired subject gets no opportunity and no dispatch
across a replay.
- **Invariant 7:** a scripted local backend drives a full tool round through
the existing evaluator.
- **Road:** the playtest gate itself, on Raven's machine.
## Reconciliation, 2026-09-23
The cut map records the means and the postmortem records the cost. This section
says how the Body stands against the target above.
**Landed.** All eight invariants hold, each with a test that fails under its own
mutation, and Soul verified each at the layer where it would fail rather than in
a unit test. One operational agent drives a turn through `world.play`; the
kernel is the only writer; the player's card carries a projection, the question,
and the refusal of their own act. `world.speak` and the story card are deleted.
**Changed from the target as written.**
- An answer names its question through an opaque per-question token carried in
the play button, not through a version comparison. The version machinery that
preceded it is deleted. Two questions in one turn commit nothing between them,
so no counter can tell them apart.
- The player's turn is one row keyed per world, with a request-key ledger across
turns. A replayed key is a no-op; a stale answer and a busy turn are refused
synchronously, before anything is spawned.
- A row the daemon cannot read is retired to a readable JSON sidecar and play
starts fresh, reported in readiness. A row that *can* be read is never
destroyed — that rule is stated on the function that destroys.
- The verbatim-quote check uses Unicode word boundaries (UAX #29), because the
hand-written rule accepted "I can" out of "I can't" and refused most CJK
quotes.
**Not built, and named as gaps rather than promises.**
- **Risk resolution.** The kernel resolves an act through an affordance's
weighted outcome bands, drawn from a digest of the world, revision, command
and affordance — deterministic, so a replay reproduces it. There is no
assessment step, no modifiers, no skill and no roll receipt, and the play
agent cannot author affordances: it may only grant and revoke the catalog's
existing verbs. An act no granted affordance expresses never draws at all; the
agent authors the consequence directly as the Play authority. Those two paths
are indistinguishable from the player's chair, which is the real gap.
- **Gestalt and institution agency.** Institutions exist as structure and
constrain who may act. Nothing makes them act, and there is no strategic tick.
Advancing the clock rolls routines to their next due and accumulates pressure
on overdue obligations and goals; that is the whole of what happens
off-screen.
**Unproven.** The seed path has never run past its configuration check. No model
has run behind the local inference port. All test evidence is Windows; the
release evidence is Idunn's Linux gate on Yggdrasil, where the browser-client
tests cannot run at all, because that gate materialises source without git
metadata.

View file

@ -1,122 +0,0 @@
# Ghostlight Dungeon Session Zero
> Status: the Dungeon daemon described here is parked at tag `parked/ghostlight-eve-surface` (2026-10-22); it is not on main.
Status: adopted direction, 2026-09-15. Not implemented. Its role as the
playtest gate is superseded (operator, 2026-09-22) by the play agent,
`ghostlight-play-agent.md` (plan step 16). D1–D3 and the library passes
L2–L4 they consume are deferred by ruling, not dropped. Plan step 15 in
`notes/ghostlight-implementation-plan.md` carries the deferred pass order.
## Ownership
Session Zero is Ghostlight Dungeon's concept and Dungeon's authority. Dungeon
is a consumer of the Ghostlight library. Session Zero consumes library
capabilities through their generic surfaces and adds nothing Dungeon-shaped
to the library: no Vault registry, player, slider, starting location, or
Session Zero phase exists in the library vocabulary.
The library capabilities it needs are specified, consumer-neutral, in
`ghostlight-world-ontology.md` under "Elaboration lenses and detail rules
(target)": the stock lens set and weights, detail rules, per-world evidence
binding, and elaborator sessions in Draft. Other consumers use the same
capabilities with their own policy; Delvehold, for one, starts from a
`Uniform` detail rule.
The world kernel lives in the `ghostlight` library crate
(`crates/ghostlight/`); `ghostlight-dungeon` consumes it across a public
boundary and cannot reach its internals.
## Objective
A player chooses a Vault, says what kind of experience they want, and gets a
world seeded from that Vault. The world is dense where they stand and sketched
where they don't, and it grows detail ahead of them as they travel. The flavor
of the world comes from how often each of the eight stock lenses works on it.
## The flow
1. **Choose a Vault.** The player picks from Vaults the Dungeon operator has
admitted. A Dungeon Vault entry names its root and the scope a player may
read, for example Kalsa's `Public`. The payload carries a Vault id, never a
path. Dungeon binds the chosen Vault as the world's evidence source.
2. **Describe the experience.** The player writes what they want. A model
reads that description and proposes weights for the eight stock lenses. The
proposal fills the sliders; the player adjusts them. Dungeon submits only
the numbers and the description, which becomes the world brief.
3. **Create.** Dungeon creates a library world with title, brief, the stock
lens set and weights, and Dungeon's detail rule with no anchor yet. No
player subject is declared yet, so every place sits at the rule's floor.
4. **Sketch.** Dungeon's seed session authors a coarse world from the Vault:
regions, routes with travel costs, institutions, populations.
5. **Choose a start.** The player picks a sketch place. Dungeon submits one
owner patch declaring the player's human-controlled subject there, and pins
that subject as the first anchor of its detail rule.
6. **Elaborate.** The library's elaborator sessions run, pulled toward the
anchors by distance.
7. **Activate** when the player chooses. Dungeon never makes activation wait
on a count.
8. **Play.** As the player travels, the library's derived demand follows the
anchor and detail follows the player.
## Dungeon policy
- **Lenses:** the library's stock set of eight, weighted by the player's
sliders. The owner may change weights in Draft and Active; later sessions use
the new weights.
- **Detail rule:** `ByDistance`, anchored on important subjects, the player
first. Recommended levels: within 60 minutes, persons, institutions, and
populations; within 1 day, institutions and populations; beyond, institutions
only; lookahead 120 minutes. Tuned on the road. Which other subjects Dungeon
pins, and when, is Dungeon policy not yet decided.
- **Travel:** Dungeon's seed authors a travel affordance for persons, and the
Eve surface projects one control per affordance a player's subject holds.
## Authority map (Dungeon)
- **Owner:** Dungeon's runtime owns Session Zero's flow, the Vault registry,
the weight proposal, the player principal, anchor pinning, and the Eve
surface. Every world change it makes is an ordinary library command.
- **Inputs:** the authenticated player, the admitted Vault list, the player's
description and slider values, the chosen start place.
- **Outputs:** library world creation, seed and owner patches, rule and
weight changes, activation, and Eve projections.
- **Derived state:** the slider proposal, the Session Zero step a player is on
(derived from the library snapshot's phase, rule anchors, and structure), and
every projection.
- **Forbidden writers:** Dungeon writing world state other than through
library commands; the proposal model submitting weights without the
player's command; a Vault path in any payload; any Dungeon identifier,
schema, or policy entering the library vocabulary.
## Cut line (Dungeon)
- `GHOSTLIGHT_SEED_VAULT_ROOT` as the only Vault: Dungeon's Vault registry
replaces it.
- The `world.create` payload fields for jurisdiction roots and permille, when
the library's detail rule replaces them.
- The genesis human subject: Dungeon declares its player at the chosen start.
## Verification (Dungeon)
1. A player-chosen Vault id resolves only to an admitted Vault and scope; an
unknown id or a path is refused before anything is spent.
2. The slider proposal changes nothing until the player submits weights.
3. The start choice declares exactly one player subject, at a sketch place,
once, in Draft, and pins it as the rule's first anchor.
4. Activation succeeds with nonzero deficits.
5. Road: a seeded world on the SDK route shows persons near the start,
institutions far from it, and new persons at a place after the player's
subject travels toward it.
## Pass order
Library passes L0 through L4 are in plan step 15; L0 is the kernel
extraction. Dungeon passes follow them:
1. Vault registry, world creation with Vault id, brief, lens weights, and
detail rule.
2. The Session Zero Eve surface: Vault choice, description, slider proposal,
sliders, sketch, start choice, activation.
3. Travel affordance and per-affordance player controls. This pass closes the
playtest gate.

File diff suppressed because it is too large Load diff

View file

@ -1,152 +0,0 @@
# Ghostlight stock lenses (L1) postmortem
Written 2026-09-16. Evidence: the cut map (`ghostlight-stock-lenses-cut.md`),
the target (`ghostlight-stock-lenses.md`), and the commits on
`codex/ghostlight-dungeon-mvp` from `817c9f4` to `872ba35`, plus the Cut 5 doc
commits.
## Summary
Elaboration in the `ghostlight` library now has a flavor the world's creator
controls:
- eight stock lenses;
- per-world weights in world state, replaceable by the owner;
- a replayable per-session draw that records the lens and its instruction
text on the session;
- concurrent sessions under their own permit ceiling.
In-flight elaborator work is rediscovered by reading the store.
Scale: 12 crate files, +4,907 / −266; four schema strings replaced
(`consumer.v5`, `controller_work.v16`, `world_create.v4`, and the commit
schema); one environment variable; one required trait method; no dependency,
crate or binary.
State at writing: landed and pushed, Windows-verified. The Linux release is
unexercised until Idunn builds it. The operator owes rulings on L1.f1
(quarantine handling), L1.f13 (seed-lane orphans), L1.f14 (row retirement)
and L1.f16 (consumer lens sets). None blocks L2.
## Scope and invariants
The target set eight invariants: lenses never decide admission, every lens
sees the whole catalog, the draw is replayable, weights are admitted honestly,
concurrent sessions stay distinct, the lens is recorded and survives resume,
stores refuse rather than migrate, and no Dungeon concept enters the library.
All eight hold. Excluded: detail rules, evidence binding, Draft sessions
(L2–L4), and Dungeon's Session Zero surface (D1–D3).
## Timeline
| Cut | Commits | Soul passes | Notable finding |
|---|---|---|---|
| Map | `ff766e8` (with rulings Q1–Q9) | — | Two sessions on one answer collided; a boundary repair was Superseded forever after any commit |
| 1 lens module | `835ea4d` | 1 | No external crash path; duplicate keys last-wins; guard and divisor diverged |
| 2 weights, command | `d06fd7e`, `10be98c`; fixes `afca403`, `acb9b33` | 2 | Identical weights committed a no-op; forged row caught by the digest, not the rule; a padded twin still committed |
| 3 session, store, adoption | `dfb3c52..2bf8164`; fixes `f63dfd1..2c3b513` | 1 | Flaky pin (3/40); the Q7 resume rule untested; the call-site draw unpinned |
| 4 concurrency, pools, rediscovery | `8538fab..3e35b3d`; fixes `6f35229..0764842`, `635123f..872ba35` | 3 | The adoption rule on one test; speak-lane pool untested; a panic killed the driver; the retryable-no-stop leg unpinned |
| 5 docs | `39b2af4`, `04fd004`, `b15ade4` | 1 | The ontology claimed seed requests and Vault evidence for the Active sweep |
## Structural delta
The estimate grew from about +900 to about +1,300 as rulings added the owner
command and rediscovery. The actual was +4,907 / −266 in crates, overwhelmingly
test code (`controllers.rs` +2,807). Production grew by the lens module (379
lines including its tests), weights and the command in the kernel,
session fields and adoption in elaboration, the concurrent sweep and
`SessionPermit`, and the runtime's second pool. Deleted: the sequential
sweep, `step`, `Clean`, `Inactive`, the instruction constant as integrity
reference, whole-session supersession equality, and a proven-dead digest
comparison. Nothing parked.
## What Soul caught
- **Untested operator rulings.** L1-Q7's whole purpose, that a resumed session
keeps its stored text when a lens's text changes, had no test: rebuilding the
text from the current lens passed everything. The operator ruled it; nothing
pinned it.
- **Flaky tests passing by luck.** A test rewrote a session's lens to a fixed
value while its fixture drew one at random. It failed about one run in eight,
and Hands' green run was luck.
- **Rules that no longer bear weight.** After Cut 4 routed resume through the
listing, Cut 3's adoption rule was guarded by a single test. Cut 3's own
former killers no longer reached it.
- **Semantic equality by spelling.** The no-op check compared raw maps, so
`{charter:3}` and `{patina:0, charter:3}`, which draw identically, still
committed revisions both ways.
- **Tests catching the wrong thing.** A forged all-zero journal row was
refused by a digest mismatch, so weakening the draw rule changed nothing.
- **Failure paths.** One panicking session task unwound out of the sweep,
aborted its sibling, and silently ended the runtime's elaboration driver
until restart.
- **Spec errors, caught before they shipped.** Identical weights "still a
commit"; a Dungeon payload mutation that could never fail; the `NoEffect`
variant the plan names but the kernel never had.
## Operator corrections
- **"Are you relying on some deterministic code outputting the same id rather
than just checking the state?"** This was the campaign's best question. It
came from Self having told the operator the lens "has to be recorded" in the
command identity. Answering it from the Body exposed the pre-existing
defect that the elaborator repair loop had never worked across sweeps (L1.f10),
and led to L1-Q9 (resume reads state). Missing context: Self framed the
recording question and the identity question as one.
- **Weights and Draft approvals.** Self recommended binding approvals to a
digest that included lens weights. The operator asked how weights could ever
alter an approval. They cannot: weights shape future elaboration, and the
owner may change them in any phase. Missing context: the probe that found the
approval gap happened to use weights.
- **Proportion.** "Dear Lord, we don't need even more machinery" (L1-Q5), and
the pools as "a ceiling, not a budget" (L1-Q4). Both shrank designs that Self
had presented with more options than they needed.
## Incidents
- **Agents ending their turn to wait.** Three times, an agent launched cargo
detached and ended its turn "to wait", and the work stopped until resumed by
hand. The brief already said to wait for long jobs. What fixed it was naming
how: block inside a tool call, with cargo in the foreground or `Wait-Process`
on the pid. Recorded in the Eureka changelog.
- **Line endings.** The working tree mixed LF and CRLF files over an LF index.
A naive newline anchor silently matched nothing, and `git apply -R`
rewrote an LF file to CRLF. Rule: detect each file's ending, require every
anchor to match exactly once, restore by reverse edit only.
- **A Soul probe left an empty untracked `lib.rs`.** Its permission to delete
was refused. Found in the report, verified, removed at close-out.
- **A map refresh raced an operator message.** Imagination finished before a
second ruling arrived, so the map contradicted two rulings until it was
resumed. Self held the commit until the map was refreshed.
## What worked
- Probing the operator's challenge instead of defending the design: the
stranding probe turned a question into a fixed pre-existing defect.
- Measuring flakes before and after (3/40, then 120/120) instead of rerunning
until green.
- Folding small, related findings into the next cut's pass instead of a
separate Hands and Soul cycle, with each still in its own commit.
- Skipping Soul on a test-only batch with an empty production diff, and
having the next Soul pass rerun its mutations.
- Derived status: no "Open:" line was ever hand-edited; questions were open
exactly while they lacked a ruling.
## What to change in the pipeline
- Tell agents how to wait, not only to wait (Eureka changelog, 2026-09-16).
- Treat any test built on a random draw or identity as requiring a loop.
- When the operator asks why a mechanism works, answer from the Body with a
probe before defending the design.
## Open follow-ups
| Item | Owner | Where | Why it can wait |
|---|---|---|---|
| L1.f1: quarantine-class elaboration errors never set quarantine, and are logged only at debug (c4.s2.f4: a panic in `persist` would wedge the lane silently) | operator | `runtime.rs` elaboration driver | Pre-existing; the lane keeps running |
| L1.f11: the browser create form never lifts bindings into the payload | operator ruled: D2 | `eve-browser-lowering`, `runtime.rs` | Fixed with the Session Zero surface |
| L1.f12: Draft approvals bound to nothing | operator ruled: deferred to multi-player | `lib.rs` `draft_approvals` | Approvals are the owner's own today |
| L1.f13: the seed lane orphans rows like deficits did | operator | `elaboration.rs` seed runner | Outside L1 |
| L1.f14: stored rows are never retired, including the L1-Q10 crash window | operator | controller work store | Growth bounded by world lifetime |
| L1.f15: `Uncovered` pinned only with at most one named root | Library | `elaboration.rs` | Behaviour is correct; the case is untested |
| L1.f16: consumer-supplied lens sets | operator | `lens.rs` | No consumer needs one yet |
| c3.s1.f3 cost: stored instruction text is not tied to the recorded lens | accepted with L1-Q7 | `elaboration.rs` | Only the local store file can write it |
| Linux release | operator via Idunn | Yggdrasil | Needs the deployment gate |

View file

@ -1,84 +0,0 @@
# Ghostlight stock lenses (plan step 15, L1)
## Status
Closed 2026-09-16. Landed in Ghostlight `835ea4d..872ba35`, plus the Cut 5
doc commits `39b2af4`, `04fd004` and `b15ade4`. The means, every ruling
(L1-Q1 to L1-Q10), and every Soul verdict are in
`ghostlight-stock-lenses-cut.md`; the scars are in
`ghostlight-stock-lenses-postmortem.md`. Windows only: the Linux release is
Idunn's build and is unexercised.
## Target
Elaboration in the `ghostlight` library gets a flavor the world's creator
controls. The library ships eight stock lenses. A world carries lens weights
as world data. Every elaborator session draws one lens by those weights,
replayably, and the drawn lens shapes what kind of structure the session
reaches for. Several sessions elaborate at once.
The lenses are the library's, not Dungeon's. Dungeon supplies weights at
world creation.
| Lens | Reaches for | Leads with |
|---|---|---|
| Patina | ordinary objects, customs, nicknames, local jokes | persona material, ordinary affordances |
| Charter | government, law, offices, selection, succession, redress | authority, selection, redress |
| Ledger | resources, labor, trade, infrastructure, scarcity, class pressure | custody, dependency, route cost |
| Hearth | kinship, daily life, care, obligation, belonging | commitments, reads |
| Tangle | factions, alliances, rivalries, leverage | relations, pressure, authority |
| Veil | secrets, rumors, misinformation, taboos, unevenly held knowledge | knowledge scope, channels |
| Ember | disputes, hazards, instability, escalation, urgent pressure | pressure, near-due commitments |
| Numen | religion, magic, ritual, awe, cosmology, the genuinely strange | facts, affordances, material |
The design text is `ghostlight-world-ontology.md`, "Elaboration lenses and
detail rules", which separates what L1 implemented from what L2 to L4 owe.
## Invariants, reconciled with the Body
1. **A lens never decides admission.** The same patch admits identically under
all eight lenses, with the mismatch set equal to the pre-L1 capture. A lens
is not part of the command id, the caller, the confinement ground, or any
mismatch. Holds.
2. **Every lens sees the whole catalog.** The catalog signatures and digest
are unchanged from before L1; emphasis is prompt text only (L1-Q5).
Holds.
3. **The draw is replayable.** The lens is drawn from world id and command
id with the kernel's `select_band` recipe, and the library has no RNG
dependency. The operator cares about replayability, not about what seeds
the draw (L1-Q1). Holds.
4. **Weights are world data with honest admission.** `WorldState` carries
them (`consumer.v5`); creation requires explicit weights with no library
default (L1-Q6); the owner replaces them with `SetLensWeights` in any phase
(L1-Q3). An all-zero set is refused at creation, at the command, at the
Dungeon payload and in a stored state row. A set that draws the same as the
current one, however it is spelled, is refused as no canonical change.
Holds.
5. **Concurrent sessions are distinct work.** The sweep hands concurrently
running sessions distinct demand entries through an in-memory claim set.
The lens stays out of the command id, which remains the idempotency key
(L1-Q4). Elaboration draws from its own pool, a ceiling
(`GHOSTLIGHT_ELABORATION_MAX_CONCURRENT`, default 2), separate from the
simulation budget, and saturating either pool never delays the other.
Dungeon runs no Active elaboration since the play agent's Cut 1
(`d69e9d4`) deleted its sweep and pool; the claim stands as a library
capability. Holds.
6. **The lens is recorded and resume reads state.** The drawn lens and its
instruction text are persisted on the session (`controller_work.v16`,
L1-Q7). A resumed session keeps both even if the weights or the lens's
text change. In-flight sessions are rediscovered from the store by what
they answer (L1-Q9); rows ready to submit are excluded from that listing
(L1-Q10). Holds.
7. **Stores refuse, not migrate.** `consumer.v4` states and
`controller_work.v15` rows are refused at open. Holds.
8. **No Dungeon concept enters the library**, and the boundary stays sealed
by admission. Holds.
## Out of scope, still owed elsewhere
- Detail rules, distance-weighted demand, and the permille cut (L3).
- Per-world evidence binding; the Active elaborator still uses
`NullEvidenceSource` (L2).
- Elaborator sessions in Draft (L3).
- Dungeon's Session Zero surface, slider proposal, and weight UI (D1-D3).
Dungeon passes explicit uniform weights through `world_create.v4` today.

View file

@ -1,204 +0,0 @@
# Ghostlight World Consumer API
Status: this describes the landed pass-10 consumer ingress — a world's third
patch author, reaching `AdmitPatch` through one loopback-bound typed document.
## Objective
Let an external consumer author and observe the exact subjects a Ghostlight
world has admitted as its mirrors, without becoming part of Ghostlight's
runtime and without the world learning the consumer's vocabulary. A
consumer-authored seed and a compiled seed are the same `AdmitPatch`; there is
no separate seed type, registry, or publication handoff. Delvehold is the
first consumer; no Delvehold identifier, schema, or policy is core authority
(`docs/architecture/delvehold-forced-ontology-integration.md` names the
profile-side binding).
## Authority map
- **Admission owner:** `require_patch_author` (`crates/ghostlight/src/lib.rs`) decides which
caller may submit `AdmitPatch` and returns that caller's `PatchGround`;
`confine_to_ground` decides what a confined ground may write. Both run in
`reduce`'s `AdmitPatch` arm and again in `apply_effect`'s `PatchAdmitted`
arm — there is no second confinement function and no way for a patch to
commit without being re-decided.
- **Consumer ground:** `PatchGround::Consumer(ConsumerId)` is derived, never
carried. The set of subjects a consumer may write is
`{ s | controller_assignments[s] == ExternallyControlled { consumer } }`,
read from committed state at decision time. A consumer cannot name its own
scope on the wire, and revoking a binding in a later commit shrinks its
authority with no ingress change.
- **Caller minting:** `WorldMailbox::submit_consumer` (`crates/ghostlight/src/mailbox.rs`) is
the only constructor of `AuthenticatedCaller::verified_system(SystemCapability::Consumer { consumer })`.
- **Ingress owner:** `crates/ghostlight/src/consumer.rs` owns decoding a document, bounding
it, authenticating the consumer, one port call, and one receipt
projection. It owns no world truth, holds no opinion about a patch's
content, and does not pre-validate — a second reducer here could disagree
with the kernel's, so structure is decided once, by `resolve_patch`.
- **Port:** `ConsumerPort` (`crates/ghostlight/src/mailbox.rs`) has one method,
`submit_consumer`. It cannot read the world: it does not select an answer,
does not pre-validate, and returns a receipt rather than state.
## Typed flow
```text
ConsumerPatchDocument (canonical MessagePack)
-> ConsumerRegistry: name -> ConsumerId, secret verified against a
stored SHA-256 digest in constant time
-> patch::decode_patch, bounded by MAX_PATCH_BYTES / _DECLARATIONS /
_OPERATIONS / _EVIDENCE
-> WorldMailbox::submit_consumer(world_id, expected_revision, command_id,
consumer, answers, patch)
-> reduce / apply_effect: require_patch_author, the answer rule,
confine_to_ground
-> ConsumerReceiptDocument: one atomic verdict — a commit reference or
the complete mismatch set
```
`command_id` and `world_id` on the receipt are `Option`: a frame that fails to
decode or names an unregistered consumer never derives a command key or reads
a world, so the receipt has none to report. The outbound half of this
contract — a consumer reading its own projection, or receiving an
attributed proposal — is not part of this pass; see "Not in this pass" below.
## Transport
Status: the HTTP door below lived in the Dungeon daemon's `api_router` and is
parked with it at tag `parked/ghostlight-eve-surface`; no process on main serves
it. `ghostlight::admit_document` and `encode_receipt` are the contract a host
serves.
`POST /cultnet/world-patch`, declared beside `/cultnet/snapshot` in
`api_router` (`runtime.rs`). The handler gates loopback and content type
(`application/msgpack`) exactly as the snapshot route does, then hands the
body to `ghostlight::admit_document`; everything past those two gates is
`consumer.rs`'s to decide. The body limit is
`CONSUMER_BODY_LIMIT = patch::MAX_PATCH_BYTES + CONSUMER_ENVELOPE_SLACK` (an
8 KiB envelope allowance over the 256 KiB patch cap), so the transport guard
cannot become a second opinion about how big a patch may be.
The document and receipt are Ghostlight-owned typed records in canonical
MessagePack, not CultNet control messages, pinned to two schema constants:
```text
CONSUMER_PATCH_SCHEMA = "ghostlight.consumer_patch.v0"
CONSUMER_RECEIPT_SCHEMA = "ghostlight.consumer_receipt.v0"
```
`ConsumerPatchDocument` carries `schema`, `world_id`, `consumer` (a
configured name, lowered to a `ConsumerId` by the registry and never carried
further), `secret`, `idempotency_key`, `expected_revision`, `answers:
Option<PatchAnswer>`, and `patch: Vec<u8>` — the encoded `WorldPatch` as a
nested canonical-MessagePack byte frame rather than an inline value, so
`MAX_PATCH_BYTES` is checked against the patch itself before any of its items
deserializes. The outer document is decoded first, is tiny, and is bounded by
the route's derived limit.
`mesh.rs`'s advertisement gains the two schema constants and nothing else:
this door is loopback-bound, so it is not a remotely reachable surface and
advertising it as one would claim availability the binary does not have.
## Idempotency and staleness
`expected_revision` is required; the port submits through
`submit_authenticated`, not the stamped path, because a caller that cannot
name the revision it built against cannot be told its batch is stale. The
idempotency ledger is checked before the revision, so an exact resubmission
still returns the original receipt (`AlreadyApplied`) even after the world has
moved; a stale document is `RevisionMismatch { expected, actual }`, and the
receipt carries the live revision so the consumer knows what to build against
next. `CommandId::derived` computes the command key from `(world, consumer,
idempotency_key)`; the same key with a different body is
`CommandIdConflict`, and nothing commits.
There is no receipt-probe request and no separate mailbox `Request` variant
for it. A consumer's document is byte-identical on retry and its `CommandId`
is derived, so resubmission is the probe and the ledger answers it directly.
## The externally controlled subject
A subject declared `NewController::External { consumer }` receives
`ControllerAssignment::ExternallyControlled { consumer }`. It mints no
controller ID and no controller mode — both accessors return `Option` for it,
and every reader fails closed rather than assuming a default. Concretely:
- it derives no decision opportunity and mints no turn;
- it is excluded from `agency_graph` and so from the cover;
- it is visible in the snapshot as an ordinary subject, related to, targeted,
and counted like any other, with `controller_id: None` and
`controller_mode: None`;
- it may hold no affordance — declaring it with a non-empty affordance grant
set is `Mismatch::ControllerGrantMismatch`, and the pairing is checked both
ways (an ordinary subject with an empty grant set is the same mismatch);
- its components change through exactly two callers: its own consumer, and
the world owner, who is unconfined and always could write it — that is the
owner's standing authority, not a leak in the consumer boundary.
## Confinement
A consumer writes only the subjects bound to it and operations grounded on
those subjects (`confine_to_ground`, the `PatchGround::Consumer` arm):
- a declared subject is admitted only if its controller names the same
consumer; position is unconfined;
- a declared place, a declared route, `Relocate`, `OpenRoute`, `CloseRoute`,
and `AlterCost` are always refused — they carry a place or a route, and a
consumer's ground names no place;
- `Witness` is always refused, for the same reason: its ground is the named
place, never the acting subject, and a consumer's ground names no place.
A consumer tells what its mirror knows through `AcquireKnowledge` on its own
bound subject; it cannot cause a place-wide witnessed event;
- `Retire`, `GrantAffordance`, `RevokeAffordance`, and `Mint` are always
refused (`ResolvedOp`s that are authority over standing, not structure over
ground);
- a `Claimed { by }` fact must name a bound subject; a `Ruled` fact is refused
outright, and so is a `Canonical` fact
declaration — a consumer's evidence buys an `Admit`
into its own custody and a `Claimed` fact, never a canonization;
- a channel's reach and controller must all be bound subjects;
- every operation's ground subjects must be bound, and its place and route
lists must be empty — `Transfer` therefore requires both endpoints bound,
so a consumer cannot push custody into a Ghostlight subject; `Admit` and
`Consume` work inside its own custody.
In Active phase a consumer patch that declares answers nothing except a
`CausalBoundary::MissingStructure { subject }` derived on one of its own
mirrors — the world noticing that a subject it can see has structure it
cannot account for. Every other Active declaration is refused by the answer
rule plus this confinement, not by a separate phase gate: a consumer cannot
answer a boundary on a foreign subject (not covered), cannot answer a
`Deficit` row (deficits are jurisdictional; a consumer holds no
jurisdiction), and cannot declare without an answer. A component-only batch —
the overwhelming majority of consumer traffic — answers nothing and commits
through the same `require_answer` path as any other author.
## Operator configuration
`ConsumerRegistry` is loaded once at startup from the file named by
`GHOSTLIGHT_CONSUMER_CREDENTIALS`: one `name = <64 hex digits>` line per
consumer (the SHA-256 of that consumer's shared secret), blank lines and `#`
comments ignored. A missing file means no consumers, and every document is
`Unauthenticated`, the fail-closed default that lets this route exist before
an operator configures anything. A file that exists but does not parse is
fatal at startup, so a mistyped credential can never read as "no consumers". The registry holds only digests; the
plaintext secret never enters the process image beyond the hash and never
enters a log, a receipt, or the journal.
## Deployment
The consumer capability's tag is part of the commit digest and the
externally controlled assignment is part of the state shape, so both bump the
schema. World lens weights later entered the state and `SetLensWeights`
the commit, so the live schemas are state `ghostlight.world_state.consumer.v6`
(state-schema generation `world-v3`) and commit
`ghostlight.world_commit.consumer.v6`. A store written under an earlier schema
is refused, not migrated.
## Not in this pass
- The outbound consumer response — a consumer reading its own projection, or
receiving an attributed proposal about a Ghostlight subject acting toward
its mirror. This is the next seam; building it prematurely would grow a
second projection owner ahead of its use.
- A CultMesh authority lease for a non-loopback consumer. Until that exists,
this route is loopback-only and offers a consumer no remote door.

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more