Compare commits
599 changed files with 102065 additions and 45746 deletions
10
.gitignore
vendored
10
.gitignore
vendored
|
|
@ -1,4 +1,11 @@
|
|||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
node_modules/
|
||||
web/dist/
|
||||
sidecar/claude-sdk/dist/
|
||||
state/scratch-compaction-*.md
|
||||
experiments/images/
|
||||
target/
|
||||
|
||||
# Disposable local scaffolding. These accumulated to ~87MB of untracked debris
|
||||
|
|
@ -11,6 +18,3 @@ target/
|
|||
|
||||
# Claude Code agent worktrees (Hands/Soul isolation); never source
|
||||
.claude/worktrees/
|
||||
|
||||
# Captured probe screenshots (scripts and fixtures under probes/page/ stay tracked)
|
||||
probes/page/*.png
|
||||
|
|
|
|||
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
[submodule "vendor/eve"]
|
||||
path = vendor/eve
|
||||
url = https://github.com/GameCult/Eve.git
|
||||
309
AGENTS.md
309
AGENTS.md
|
|
@ -2,110 +2,233 @@
|
|||
|
||||
## Project Purpose
|
||||
|
||||
Ghostlight is a Rust world kernel and the play daemon built on it. Models
|
||||
propose; the kernel admits or refuses. The same kernel is meant to run the
|
||||
simulation behind Aetheria's public story, a persistent cast and storylets, as
|
||||
well as Ghostlight Dungeon (`crates/ghostlight-dungeon` and
|
||||
`deployment/idunn/recipe.toml`, live on `main` for the Dungeon playtest; the
|
||||
earlier Eve surface is at tag `parked/ghostlight-eve-surface`). `README.md`
|
||||
says what exists today and what does not.
|
||||
Ghostlight is a research and implementation home for socially persistent
|
||||
generative agents. The core problem is not "make an LLM sound like a person."
|
||||
The core problem is building an architecture where personality, culture,
|
||||
memory, masks, perception, and incentives can actually survive contact with
|
||||
time, relationships, routine, tonal variation, and pressure.
|
||||
|
||||
## 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,
|
||||
follow-ups) lives in the Eureka mind, not in this repo. The current campaign
|
||||
is `ghostlight-verse`; query it through the `huginn` CLI
|
||||
(`EUREKA_INSTANCE=weksa`, `HUGINN_ENDPOINT=rudp://10.77.0.1:17877`).
|
||||
- `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.
|
||||
## Canonical State
|
||||
|
||||
## 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. A direct write to either is silently reverted: every `add-evidence`
|
||||
regenerates `evidence.jsonl` from the CultCache evidence document, so edits
|
||||
and deletions that do not go through `tools/ghostlight_state_store.py` look
|
||||
applied until the next append restores what you removed. Compaction means
|
||||
replacing the store's evidence document through
|
||||
`ghostlight_state.py compact-evidence --replacement <distilled.jsonl>`,
|
||||
which archives every current record verbatim to
|
||||
`state/evidence.archive.jsonl` first; the export follows.
|
||||
- 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
|
||||
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.
|
||||
## Important Paths
|
||||
|
||||
## Where Things Are
|
||||
- Project root: `F:\Projects\Ghostlight`
|
||||
- Canonical map: `F:\Projects\Ghostlight\state\map.yaml`
|
||||
- Scratch surface: `F:\Projects\Ghostlight\state\scratch.md`
|
||||
- Distilled evidence ledger: `F:\Projects\Ghostlight\state\evidence.jsonl`
|
||||
- Branch ledger: `F:\Projects\Ghostlight\state\branches.json`
|
||||
- Handoff summary: `F:\Projects\Ghostlight\notes\fresh-workspace-handoff.md`
|
||||
- System map: `F:\Projects\Ghostlight\notes\ghostlight-current-system-map.md`
|
||||
- Implementation plan: `F:\Projects\Ghostlight\notes\ghostlight-implementation-plan.md`
|
||||
- Architecture rationale: `F:\Projects\Ghostlight\notes\architecture-rationale.md`
|
||||
- State CLI: `F:\Projects\Ghostlight\tools\ghostlight_state.py`
|
||||
- CultCache state seam: `F:\Projects\Ghostlight\tools\ghostlight_state_store.py`
|
||||
- CultCache-Py dependency: pinned `cultcache-py==0.2.0` from PyPI, declared in
|
||||
`F:\Projects\Ghostlight\tools\requirements.txt`
|
||||
- CultCache state store: `F:\Projects\Ghostlight\state\ghostlight-state.cultcache.jsonl`
|
||||
- Pre-compaction helper: `F:\Projects\Ghostlight\tools\ghostlight_prepare_compaction.py`
|
||||
|
||||
- Kernel: `crates/ghostlight/src/`. Its vocabulary and current mechanism:
|
||||
`docs/architecture/ghostlight-world-ontology.md`. The consumer contract:
|
||||
`docs/architecture/ghostlight-world-consumer-api.md`.
|
||||
- Dungeon daemon and Idunn recipe: `crates/ghostlight-dungeon/` and
|
||||
`deployment/idunn/recipe.toml` (the earlier Eve surface is at tag
|
||||
`parked/ghostlight-eve-surface`).
|
||||
- Persona membrane: `crates/ghostlight-persona-projection/src/lib.rs`.
|
||||
- Architecture rationale (earlier Dungeon / parked Eve surface design record):
|
||||
`docs/architecture/ghostlight-dungeon-mvp.md`.
|
||||
`notes/ghostlight-implementation-plan.md` is the historical plan of the 2026-09
|
||||
rebuild, not the current plan.
|
||||
## Useful Commands
|
||||
|
||||
## Build, Verify, Deploy
|
||||
Use the bundled Python runtime if `python` is not on PATH. `npm run state:status`
|
||||
and `npm run state:prepare-compaction` install the pinned `cultcache-py`
|
||||
dependency automatically (a `pre*` npm hook runs `state:bootstrap` first, an
|
||||
idempotent `pip install -r tools/requirements.txt`). A direct
|
||||
`ghostlight_state.py` invocation does not go through npm, so run
|
||||
`state:bootstrap` once per session before the first direct call:
|
||||
|
||||
`crates/ghostlight-dungeon` deploys to Yggdrasil from `deployment/idunn/recipe.toml`
|
||||
for the Dungeon playtest (brake release admitted in
|
||||
`ghostlight-verse:ruling:ghostlight-brake-release-granted`). Kernel, verse, and
|
||||
Dungeon tests run on Linux on Yggdrasil (the `ygg-verify` stopgap), not on the
|
||||
workstation; a Windows compile is not evidence about Linux, so say which host you
|
||||
used.
|
||||
```powershell
|
||||
npm run state:bootstrap
|
||||
npm run state:status
|
||||
npm run state:prepare-compaction
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' add-evidence --type research --status ok --note '...'
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' add-branch --id branch-id --hypothesis '...'
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' compact-evidence --replacement '.\distilled.jsonl'
|
||||
```
|
||||
|
||||
For infrastructure, SSH, Idunn, Odin, or Heimdall work, consult
|
||||
`F:\Projects\gamecult-ops` before acting.
|
||||
## Build And Deploy Target
|
||||
|
||||
Ghostlight Dungeon ships to Linux on Yggdrasil. Yggdrasil is its build, test,
|
||||
and production body: Idunn freezes an exact commit, runs the locked native
|
||||
Linux tests, builds the daemon and web projection in pinned Linux containers,
|
||||
and seals the release. Owning runbook:
|
||||
`gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`.
|
||||
|
||||
You are almost certainly reading this on a Windows workstation. That is where
|
||||
the shell is, not where the artifact runs. A Windows compile of a commit is not
|
||||
evidence about the Linux release — toolchain, linker, filesystem semantics and
|
||||
path handling all differ — and it is not the build the deploy path will use.
|
||||
Build for the target, or let the deploy path's own builder do it, and say which
|
||||
one you used.
|
||||
|
||||
## Session Bootstrap And Re-entry Protocol
|
||||
|
||||
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:bootstrap` (installs the pinned `cultcache-py` dependency;
|
||||
idempotent, safe to rerun)
|
||||
- `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
|
||||
|
||||
- Restate the current mechanism and intended change before substantial edits.
|
||||
Prefer one clear hypothesis per iteration.
|
||||
- Verify with checks that reflect the real goal, not proxy success. Revert
|
||||
changes that do not clearly improve the target.
|
||||
- If the diff grows while understanding shrinks, stop and diagnose.
|
||||
- Delete obsolete authority before adding a new path. Do not keep an old writer
|
||||
alive behind a shim.
|
||||
- Commit completed work and push it. Merge, confirm the tip by SHA, then delete
|
||||
the branch; push only after reading the test result line.
|
||||
- In documentation, describe the live system and the current rule directly. No
|
||||
claim of capability without a file that implements it. Keep rejected history
|
||||
short and decision-relevant, or leave it in git.
|
||||
- Steward persistent state as part of the work. If a lesson changes future
|
||||
behavior, update the smallest correct memory surface before moving on; if a
|
||||
memory surface is stale, duplicated, or making re-entry slower, cut or
|
||||
consolidate it.
|
||||
- Before substantial edits, restate the current mechanism and intended change.
|
||||
- Prefer one clear hypothesis per iteration.
|
||||
- Verify with checks that reflect the real goal, not just proxy success.
|
||||
- Revert or discard changes that do not clearly improve the target.
|
||||
- If the diff grows while understanding shrinks, stop implementation and switch
|
||||
to diagnosis.
|
||||
- Keep maps and prose together; do not replace useful maps with prose-only
|
||||
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
|
||||
factions, institutions, species or body types, location, and time period
|
||||
involved. Ground detail in the source's material facts: habitat, law, money,
|
||||
route access, surveillance, communication channels, and local failure costs.
|
||||
- If the source is too vague for a concrete detail, do not bluff. Mark the gap
|
||||
and propose a narrow elaboration for AetheriaLore, subject to operator review.
|
||||
- Choose a tonal mode on purpose. Aetheria supports wit with stakes, warmth,
|
||||
absurdity, domestic texture, ritual quiet, wonder, horror, noir, and dry
|
||||
systems prose; do not default to constant crisis. Comic precision in the
|
||||
Adams/Pratchett manner is a good default, where jokes reveal stakes instead of
|
||||
dissolving them.
|
||||
- Establish ordinary life before interruption: routines, work, relationships,
|
||||
small desires, and local accommodations are worldbuilding, not filler.
|
||||
- Before writing or generating Aetheria scenes, check AetheriaLore for the
|
||||
factions, movements, institutions, species or body types, location, and time
|
||||
period involved.
|
||||
- Before drafting story prose, choose an intentional tonal mode or blend for the
|
||||
scene. Aetheria should support wit-with-stakes, warmth, absurdity, domestic
|
||||
texture, ritual quiet, wonder, horror, noir, dour poetry, and dry systems
|
||||
prose as needed. Do not default to constant crisis or procedural severity.
|
||||
- Use Adams/Pratchett-style comic precision and humane levity as a useful
|
||||
default touchstone when no stronger scene-specific style is called for:
|
||||
jokes and absurdity should reveal stakes, not dissolve them.
|
||||
- Establish ordinary life before interruption when the fixture calls for it:
|
||||
routines, work texture, relationships, private jokes, rituals, small desires,
|
||||
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.
|
||||
|
|
|
|||
337
Cargo.lock
generated
337
Cargo.lock
generated
|
|
@ -61,15 +61,6 @@ version = "1.0.104"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "ar_archive_writer"
|
||||
version = "0.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec"
|
||||
dependencies = [
|
||||
"object",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-stream"
|
||||
version = "0.3.6"
|
||||
|
|
@ -185,6 +176,12 @@ version = "0.22.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
|
|
@ -275,6 +272,22 @@ dependencies = [
|
|||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-connector"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/GameCult/CodexConnector.git?rev=68fe94b9475823de92ed766a97ea962d48723708#68fe94b9475823de92ed766a97ea962d48723708"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"base64 0.23.1",
|
||||
"rand_core 0.6.4",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.9.6"
|
||||
|
|
@ -332,7 +345,7 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a01
|
|||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"cultcache-rs-derive 0.1.0",
|
||||
"cultcache-rs-derive",
|
||||
"fs2",
|
||||
"redb",
|
||||
"rmp-serde",
|
||||
|
|
@ -343,26 +356,6 @@ dependencies = [
|
|||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cultcache-rs"
|
||||
version = "0.3.1"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"cultcache-rs-derive 0.2.0",
|
||||
"fs2",
|
||||
"redb",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"serde_stacker",
|
||||
"stacker",
|
||||
"uuid",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cultcache-rs-derive"
|
||||
version = "0.1.0"
|
||||
|
|
@ -373,24 +366,14 @@ dependencies = [
|
|||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cultcache-rs-derive"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cultmesh-rs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cultcache-rs 0.1.0",
|
||||
"cultnet-rs 0.1.0",
|
||||
"cultcache-rs",
|
||||
"cultnet-rs",
|
||||
"serde",
|
||||
]
|
||||
|
||||
|
|
@ -401,34 +384,9 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a01
|
|||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"cultcache-rs 0.1.0",
|
||||
"ed25519-dalek",
|
||||
"hmac",
|
||||
"rand 0.9.5",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"socket2 0.5.10",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cultnet-rs"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
"base64",
|
||||
"chrono",
|
||||
"cultcache-rs 0.3.1",
|
||||
"cultcache-rs",
|
||||
"ed25519-dalek",
|
||||
"hmac",
|
||||
"rand 0.9.5",
|
||||
|
|
@ -483,9 +441,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.9"
|
||||
version = "0.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
|
|
@ -509,12 +467,6 @@ dependencies = [
|
|||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dyn-clone"
|
||||
version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "2.2.3"
|
||||
|
|
@ -711,12 +663,11 @@ version = "0.1.0"
|
|||
dependencies = [
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"cultcache-rs 0.1.0",
|
||||
"codex-connector",
|
||||
"cultcache-rs",
|
||||
"ghostlight-persona-projection",
|
||||
"model-connector",
|
||||
"reqwest",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
|
|
@ -725,8 +676,6 @@ dependencies = [
|
|||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"unicode-normalization",
|
||||
"unicode-properties",
|
||||
"uuid",
|
||||
"zeroize",
|
||||
]
|
||||
|
|
@ -740,27 +689,29 @@ dependencies = [
|
|||
"async-stream",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"cultcache-rs 0.1.0",
|
||||
"codex-connector",
|
||||
"cultcache-rs",
|
||||
"cultmesh-rs",
|
||||
"cultnet-rs 0.1.0",
|
||||
"cultnet-rs",
|
||||
"ghostlight",
|
||||
"ghostlight-persona-projection",
|
||||
"hmac",
|
||||
"jsonwebtoken",
|
||||
"libc",
|
||||
"model-connector",
|
||||
"rand 0.9.5",
|
||||
"reqwest",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
|
|
@ -776,18 +727,6 @@ dependencies = [
|
|||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ghostlight-verse"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"ghostlight",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
|
|
@ -830,6 +769,12 @@ dependencies = [
|
|||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-range-header"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c"
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
|
|
@ -885,7 +830,7 @@ version = "0.1.20"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
"futures-util",
|
||||
|
|
@ -1068,7 +1013,7 @@ version = "9.3.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"js-sys",
|
||||
"pem",
|
||||
"ring",
|
||||
|
|
@ -1079,9 +1024,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.1"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
|
|
@ -1145,9 +1090,19 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
|||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.18"
|
||||
version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "mime_guess"
|
||||
version = "2.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
|
||||
dependencies = [
|
||||
"mime",
|
||||
"unicase",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
|
|
@ -1160,26 +1115,6 @@ dependencies = [
|
|||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "model-connector"
|
||||
version = "0.1.0"
|
||||
source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=edf2f8e03cbb61df385b9b145b46f676ce3b70d5#edf2f8e03cbb61df385b9b145b46f676ce3b70d5"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"base64",
|
||||
"cultnet-rs 0.2.0",
|
||||
"rand_core 0.6.4",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
|
|
@ -1223,15 +1158,6 @@ dependencies = [
|
|||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "object"
|
||||
version = "0.39.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
|
|
@ -1273,7 +1199,7 @@ version = "3.0.6"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
|
|
@ -1322,9 +1248,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.1"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
|
||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
|
|
@ -1344,16 +1270,6 @@ dependencies = [
|
|||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "psm"
|
||||
version = "0.1.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
|
||||
dependencies = [
|
||||
"ar_archive_writer",
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.11"
|
||||
|
|
@ -1513,31 +1429,11 @@ dependencies = [
|
|||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ref-cast"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"
|
||||
dependencies = [
|
||||
"ref-cast-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ref-cast-impl"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.19"
|
||||
version = "0.4.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
|
|
@ -1546,9 +1442,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.12"
|
||||
version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
|
|
@ -1556,7 +1452,7 @@ version = "0.12.28"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
|
|
@ -1710,31 +1606,6 @@ version = "1.0.23"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "schemars"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e"
|
||||
dependencies = [
|
||||
"dyn-clone",
|
||||
"ref-cast",
|
||||
"schemars_derive",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schemars_derive"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde_derive_internals",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
|
|
@ -1787,17 +1658,6 @@ dependencies = [
|
|||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive_internals"
|
||||
version = "0.30.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.151"
|
||||
|
|
@ -1822,17 +1682,6 @@ dependencies = [
|
|||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_stacker"
|
||||
version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_core",
|
||||
"stacker",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_urlencoded"
|
||||
version = "0.7.1"
|
||||
|
|
@ -1950,19 +1799,6 @@ version = "1.2.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "stacker"
|
||||
version = "0.1.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"psm",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
|
|
@ -2183,13 +2019,23 @@ checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
|||
dependencies = [
|
||||
"bitflags",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"http-range-header",
|
||||
"httpdate",
|
||||
"mime",
|
||||
"mime_guess",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"url",
|
||||
]
|
||||
|
||||
|
|
@ -2279,27 +2125,18 @@ version = "1.20.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicase"
|
||||
version = "2.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-normalization"
|
||||
version = "0.1.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
|
||||
dependencies = [
|
||||
"tinyvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-properties"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-segmentation"
|
||||
version = "1.13.3"
|
||||
|
|
@ -2694,18 +2531,18 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.66"
|
||||
version = "0.8.56"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a"
|
||||
checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.66"
|
||||
version = "0.8.56"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"
|
||||
checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ members = [
|
|||
"crates/ghostlight",
|
||||
"crates/ghostlight-dungeon",
|
||||
"crates/ghostlight-persona-projection",
|
||||
"crates/ghostlight-verse",
|
||||
]
|
||||
resolver = "2"
|
||||
|
||||
|
|
@ -20,7 +19,7 @@ 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" }
|
||||
codex-connector = { git = "https://github.com/GameCult/CodexConnector.git", rev = "68fe94b9475823de92ed766a97ea962d48723708" }
|
||||
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" }
|
||||
|
|
@ -34,6 +33,7 @@ serde_json = "1"
|
|||
sha2 = "0.10"
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tower-http = { version = "0.6", features = ["fs", "trace"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
unicode-segmentation = "1"
|
||||
|
|
|
|||
278
README.md
278
README.md
|
|
@ -1,123 +1,197 @@
|
|||
# Ghostlight
|
||||
|
||||
**Ghostlight is a world kernel: typed world state that a language model can
|
||||
propose changes to and can never write.** The valuable part is
|
||||
`crates/ghostlight`. The live Dungeon playtest daemon (`crates/ghostlight-dungeon`,
|
||||
below) is one client of it; the earlier Eve surface is parked.
|
||||
Ghostlight builds persistent generative people and worlds. Its active product is
|
||||
[Ghostlight Dungeon](https://ghostlight.gamecult.org): a Vault-grounded narrative
|
||||
simulation in which places, knowledge, relationships, institutions, clocks, and
|
||||
consequences survive beyond the model's current context.
|
||||
|
||||
**The thesis.** World state is typed documents. Every change to it, and every
|
||||
narrative dependency on it, is an operation in a closed, predefined algebra.
|
||||
Models propose operations; the kernel checks each against the state (references,
|
||||
preconditions, authority, conservation, who knows what) and admits it or refuses
|
||||
it with the complete list of mismatches. Narration describes only what was
|
||||
committed. A model-as-game-master holds the world in a context window and
|
||||
drifts; here the world is a digest-chained journal that survives restarts and
|
||||
cannot be talked into contradicting itself.
|
||||
The project began as a research and fixture pipeline for socially persistent
|
||||
Aetheria agents. That material remains useful regression evidence. The live
|
||||
machine is now a Rust runtime with typed campaign state, one canonical world
|
||||
authority, bounded Persona projection, fiction-first action resolution, and a
|
||||
multiresolution agency graph for keeping large settings active at finite cost.
|
||||
|
||||
**Use it as a structured state backend.** Do not judge it by the Dungeon playtest's
|
||||
or the earlier parked Eve surface's prose. The kernel is a library; prose comes
|
||||
from whichever model you plug into its ports.
|
||||
## What Ghostlight Owns
|
||||
|
||||
- `crates/ghostlight`: the sealed library. A consumer gets create/open
|
||||
(`WorldMailbox::open`, `create`), immutable snapshots (`snapshot`), command
|
||||
submission through role-scoped ports (`PlayPort`, `ConsumerPort`,
|
||||
`ControllerPort`, `SeedPort`), typed receipts, and the runner and inference-port
|
||||
entry points (`ControllerRunner`, `ElaborationRunner`, `SeedRunner`,
|
||||
`InferencePort`). Mutable state, ID issuers, the reducer and the journal
|
||||
writer are not public. `compile_fail` doc-tests in `crates/ghostlight/src/lib.rs`
|
||||
and `crates/ghostlight/tests/external_admission.rs` prove the seal.
|
||||
- `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`).
|
||||
- `WorldKernel` is the sole owner of committed campaign state and revisions.
|
||||
- Every player command, NPC action, strategic tick, wait, import, and reload
|
||||
enters the same validated campaign mailbox and atomic CultCache commit path.
|
||||
- Foreground actions, NPC reactions, strategic Gestalt activity, waits, travel,
|
||||
and population fission lower into one closed semantic world-mutation algebra.
|
||||
Means and intended effects remain proposals; only an admitted mutation batch
|
||||
can change canonical components. There is no model-authored JSON Patch path.
|
||||
- Vault evidence constrains world compilation without pretending every playable
|
||||
route, procedure, or local institution is already written down. The compiler
|
||||
synthesizes the smallest compatible branch elaboration, exposes it for
|
||||
approval, and keeps it distinct from canon. Details that must not vary belong
|
||||
in the Vault.
|
||||
- Hosted lore Vaults are planned as Git-synchronized, Obsidian-compatible
|
||||
Markdown hierarchies. The Vault service owns their indexes; campaigns retain
|
||||
only manifest bindings and exact evidence receipts.
|
||||
- Projector → Persona → Interpreter turns produce proposals. Models never
|
||||
commit world state.
|
||||
- Knowledge, perception, capability, location, custody, and authority are
|
||||
validated against the exact actor proposing an action.
|
||||
- Fiction-first d20 resolution treats player text as an attempt rather than an
|
||||
accomplished fact.
|
||||
- Multiresolution Gestalts keep people, institutions, and factions active under
|
||||
a bounded Persona-cell budget without merging rivals into one mind or erasing
|
||||
named individuals.
|
||||
- Away-time simulation advances clocks and remote agency without puppeting or
|
||||
directly harming an absent player character.
|
||||
- CultMesh publishes typed service and Eve/CultUI state; the browser lowers that
|
||||
surface and does not become a second state authority.
|
||||
- Odin receives Ghostlight's advertised boundary schemas and typed projections
|
||||
over ACK-bounded RUDP publication. Internal runtime schemas are not treated as
|
||||
discovery contracts merely because Ghostlight owns them.
|
||||
|
||||
Start with those two documents, then `cargo doc -p ghostlight --open`.
|
||||
## Eve-native interface
|
||||
|
||||
**Populate the algebra first.** The kernel owns the component operations; a world owns its
|
||||
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.
|
||||
Ghostlight publishes one stable logical surface, `ghostlight.play`, for
|
||||
anonymous entry, Session Zero, Contract Review, and campaign play. The browser
|
||||
contains Eve's canonical provider host and lowering package plus Heimdall's
|
||||
access-plugin adapter. It does not contain Ghostlight-specific screen renderers
|
||||
or domain API routing.
|
||||
|
||||
## Elaborators
|
||||
Editable Eve bindings are the input model. Text, number, and choice controls
|
||||
bind either provider-owned typed state or renderer-local draft state; an
|
||||
operation captures named bindings and submits one canonical Eve command.
|
||||
Rejected or stale commands preserve local drafts, while an accepted receipt may
|
||||
clear named bindings before the host refetches the authoritative surface. A
|
||||
browser may lower this interaction to an HTML form for accessibility, but forms
|
||||
are not part of Eve's state or command ontology.
|
||||
|
||||
An elaborator is a model session, confined to one jurisdiction of the world, that
|
||||
adds structure where the world is thin: it answers a derived causal boundary
|
||||
(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.
|
||||
Heimdall authentication is composed as the required
|
||||
`gamecult.heimdall.access` Eve plugin. Heimdall owns OAuth attempts, provider
|
||||
callbacks, claims, entitlements, and single-use completion redemption.
|
||||
Ghostlight owns only its hashed HttpOnly app session and derives campaign
|
||||
authority from canonical membership. The browser sees an opaque attempt handle,
|
||||
never a claim, refresh credential, account hash, member ID, or actor authority.
|
||||
See
|
||||
[`docs/architecture/ghostlight-eve-native-interface.md`](docs/architecture/ghostlight-eve-native-interface.md).
|
||||
|
||||
## Direction (planned, not built)
|
||||
## Current Status
|
||||
|
||||
Use the kernel to simulate a whole world with many kinds of actor: Aetheria's
|
||||
factions and a persistent cast whose members keep identity, memory and
|
||||
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 is implemented and deployed as a native Yggdrasil,
|
||||
Heimdall-gated playtest harness. Idunn owns daemon continuity, Odin owns Verse
|
||||
discovery, and the application remains the sole owner of campaign truth.
|
||||
Authentication commands resolve Heimdall's redacted private boundary through
|
||||
Odin; no direct route is browser- or unit-owned, and valid local sessions do
|
||||
not phone home on routine commands. The
|
||||
current acceptance surface covers:
|
||||
|
||||
## Ghostlight Dungeon
|
||||
- persistent DM-led Session Zero with shared/private channels, typed contracts,
|
||||
private boundaries, character bargains, digest-bound unanimous approval, and
|
||||
atomic publication;
|
||||
- source-constrained world compilation from an approved brief: canon evidence
|
||||
pins what must remain true, compatible game-scale connective tissue becomes
|
||||
disclosed branch-local state, and genuine premise conflicts return to
|
||||
negotiation instead of borrowing a nearby story;
|
||||
- selectable Aetheria and Kalsa Vaults, with Kalsa's player-safe `Public` and
|
||||
GM-only `Spoilers` evidence lanes preserved through exact receipts;
|
||||
- persistent campaigns, forks, resets, exports, and Heimdall-account-isolated sessions;
|
||||
- parallel affected-character Projector/Persona/Interpreter waves;
|
||||
- impossible-action refusal, assessed stakes, server-side rolls, and receipted
|
||||
commits;
|
||||
- strategic clocks, away-time catch-up, institution activity, migration, and
|
||||
information-channel-aware news;
|
||||
- bounded shared-scene co-op for up to eight Heimdall members, with exact
|
||||
member→actor authority, actor-filtered surfaces, unanimous time/budget
|
||||
governance, and no player puppeting or PvP mutation;
|
||||
- connected cohesive and arena simulation covers at budgets from 1 to 128;
|
||||
- Gestalt materialisation, folding, member deltas, migration, and later
|
||||
rematerialisation of the same person;
|
||||
- atomic rejection of malformed, stale, or semantically invalid model waves;
|
||||
- one kernel-owned mutation reducer for foreground, reaction, strategic, time,
|
||||
travel, population-fission, and bounded region-expansion consequences, with
|
||||
exact component versions and mutation proof receipts;
|
||||
- provider, token, cache, latency, validation, state-version, and build receipts;
|
||||
- provider-neutral inference through either direct DeepSeek/OpenRouter
|
||||
boundaries or the independent CodexConnector daemon's encrypted loopback
|
||||
CultNet boundary, while every prompt, schema, retry, interpretation, and world
|
||||
commit remains Ghostlight's;
|
||||
- exact-build deployment, state migration, public cutover, and restart
|
||||
verification on Yggdrasil.
|
||||
|
||||
`crates/ghostlight-dungeon` and `deployment/idunn/recipe.toml` are live on `main`
|
||||
for the Dungeon playtest: one Rust binary serving the compiled browser page,
|
||||
the Deru HTTPS API, and the Idunn/Odin CultNet runtime-presence endpoints. The
|
||||
earlier Eve surface remains at tag `parked/ghostlight-eve-surface` as history.
|
||||
Initial compiler seed publication is a bounded empty-store creation
|
||||
transaction. Named-person materialisation and folding are resolution
|
||||
transactions that preserve individual deltas without rewriting their Gestalt.
|
||||
The remaining forge gates are expansion and review of the agency corpus beyond
|
||||
its current candidate seed, removal of legacy model effect schemas,
|
||||
multi-account human pressure testing of Session Zero privacy/publication and
|
||||
bounded co-op, and continued multiresolution Gestalt agency pressure. The
|
||||
public site is provisional; checkout is not live.
|
||||
|
||||
## Repo map
|
||||
## Bounded Co-op
|
||||
|
||||
| Path | What it is |
|
||||
|---|---|
|
||||
| `crates/ghostlight/` | The sealed kernel library. |
|
||||
| `crates/ghostlight-dungeon/` | The live Dungeon playtest daemon (HTTP/browser surface, Heimdall sign-in, Idunn/Odin presence). |
|
||||
| `crates/ghostlight-persona-projection/` | Membrane between structured state and a prose-only Persona. |
|
||||
| `crates/ghostlight-verse/` | The `ghostlight-verse` operator command line (`genesis`, `run`). |
|
||||
| `deployment/idunn/` | Idunn deployment recipe (`recipe.toml`) for the Dungeon playtest on Yggdrasil. |
|
||||
| `AGENTS.md` | Invariants and where things are. |
|
||||
| `docs/architecture/ghostlight-dungeon-mvp.md` | Earlier Dungeon / parked Eve surface authority architecture (design record). |
|
||||
| `notes/` | The verse campaign's target and map, the handoff pointer, local smoke notes. |
|
||||
Campaign creation now supports one to eight authenticated players. One
|
||||
`SessionZeroKernel` owns negotiation; after unanimous approval, one
|
||||
`WorldKernel` owns the shared campaign. Membership binds each account to one
|
||||
exact actor, and every player receives an actor-filtered Eve projection.
|
||||
|
||||
`docs/public-architecture/`, `docs/articles/` and `docs/product/` are design
|
||||
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.
|
||||
This milestone is intentionally one shared scene with sequential public
|
||||
actions. PvP, split parties, private in-play actions, delegation, late joining,
|
||||
and simultaneous declarations remain closed until their consent and governance
|
||||
contracts exist. See
|
||||
[`docs/architecture/ghostlight-dungeon-session-zero.md`](docs/architecture/ghostlight-dungeon-session-zero.md)
|
||||
and the longer-term
|
||||
[`multiplayer intention`](docs/architecture/ghostlight-dungeon-multiplayer-intention.md).
|
||||
|
||||
## Build and test
|
||||
## Lore Vault Product Intention
|
||||
|
||||
Dungeon deploys to Yggdrasil through Idunn from `deployment/idunn/recipe.toml`.
|
||||
Linux verification runs on Yggdrasil, not on a workstation:
|
||||
The hosted product will accept ordinary Obsidian-compatible lore Vaults synced
|
||||
through Git. Contributor and Private plans provision one active custom Vault;
|
||||
their Plus variants provision three, subject to combined indexed-source and
|
||||
import allowances. The entitlement, accounting rules, authority boundary, and
|
||||
security gates are recorded in
|
||||
[`docs/product/lore-vault-entitlements.md`](docs/product/lore-vault-entitlements.md).
|
||||
Custom tenant import is not yet part of the deployed tester harness.
|
||||
|
||||
```sh
|
||||
cargo build --locked --workspace
|
||||
cargo test --locked -p ghostlight-persona-projection
|
||||
cargo test --locked -p ghostlight
|
||||
cargo test --locked -p ghostlight-dungeon
|
||||
cargo test --locked -p ghostlight-verse
|
||||
## Architecture
|
||||
|
||||
The shortest reliable re-entry path is:
|
||||
|
||||
- [`docs/architecture/ghostlight-dungeon-mvp.md`](docs/architecture/ghostlight-dungeon-mvp.md): runtime authority, compiler, action loop, persistence, hosting, and security;
|
||||
- [`docs/architecture/ghostlight-dungeon-session-zero.md`](docs/architecture/ghostlight-dungeon-session-zero.md): campaign negotiation, privacy, publication, membership, and bounded co-op;
|
||||
- [`docs/architecture/ghostlight-multiresolution-agency.md`](docs/architecture/ghostlight-multiresolution-agency.md): dynamic Gestalt partitioning, cohesive and arena cells, fairness, and atomic strategic waves;
|
||||
- [`docs/architecture/ghostlight-eve-native-interface.md`](docs/architecture/ghostlight-eve-native-interface.md): Eve bindings, the stable provider surface, private Heimdall command plane, app-session custody, and browser cut line;
|
||||
- [`docs/architecture/ghostlight-transition-algebra.md`](docs/architecture/ghostlight-transition-algebra.md): canonical subjects and components, semantic mutations, admission envelopes, atomic reduction, and the remaining writer migration;
|
||||
- [`notes/ghostlight-current-system-map.md`](notes/ghostlight-current-system-map.md): current implemented pipeline;
|
||||
- [`notes/ghostlight-implementation-plan.md`](notes/ghostlight-implementation-plan.md): live sequence and next pressure tests;
|
||||
- [`state/map.yaml`](state/map.yaml): canonical human-readable project state.
|
||||
|
||||
## Repository Shape
|
||||
|
||||
- `crates/ghostlight/`: the library crate — world kernel, ontology and reducer,
|
||||
journal, mailbox, controllers, elaboration, cover, clock, consumer admission,
|
||||
inference ports, and evidence sources;
|
||||
- `crates/ghostlight-dungeon/`: Rust daemon consuming that library — HTTP
|
||||
routes, Eve projection/command ingress, Heimdall and app sessions, CultMesh
|
||||
publication, Idunn health, and acceptance harnesses;
|
||||
- `crates/ghostlight-persona-projection/`: generalized projection membrane owned
|
||||
by Ghostlight and consumed by Epiphany;
|
||||
- `docs/architecture/`: durable contracts and authority maps;
|
||||
- `docs/articles/`: accessible public explanations;
|
||||
- `notes/`: implementation planning, handoff, and current-system maps;
|
||||
- `schemas/`: published JSON Schemas for typed boundary documents;
|
||||
- `examples/`: earlier fixtures and regression material;
|
||||
- `state/`: human-readable project memory plus older research-pipeline state;
|
||||
- `tools/`: state, validation, and fixture helpers.
|
||||
- `web/`: thin Eve browser host, Ghostlight transport, and Heimdall plugin
|
||||
adapter; product state and product-specific rendering remain server-owned.
|
||||
|
||||
Runtime documents and campaign exports use MessagePack-backed CultCache `.cc`.
|
||||
JSON exists at schema publication, browser, MCP, model-provider, and diagnostic
|
||||
boundaries; it is not the canonical hosted state store.
|
||||
|
||||
## Useful Commands
|
||||
|
||||
```powershell
|
||||
cargo test --workspace
|
||||
npm run state:status
|
||||
npm run state:prepare-compaction
|
||||
npm run schema:validate
|
||||
```
|
||||
|
||||
The kernel alone needs only `cargo test -p ghostlight`. 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
|
||||
loopback endpoint, the verse runner's `hosted/` goes to an https endpoint,
|
||||
and any other model goes to the connector. 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
|
||||
publication, model-provider and diagnostic boundaries.
|
||||
For Codex-driven work, read `AGENTS.md` before changing the repository. It owns
|
||||
the persistence, grounding, verification, and handoff discipline.
|
||||
|
|
|
|||
8
acceptance/full-world-delvehold-regions-v2.txt
Normal file
8
acceptance/full-world-delvehold-regions-v2.txt
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
Beyond the Confluence, approach and admit a politically inhabited elven forest realm whose watershed law, living-landscape institutions, rival offices, settlements, and public routes respond independently to the deep crisis.
|
||||
Beyond the Confluence, approach and admit a politically inhabited human rail-capital realm with a government, opposition, university, mage interests, labor constituencies, dependent infrastructure, surrounding settlements, and public routes.
|
||||
Beyond the Confluence, approach and admit a politically inhabited orcish oathland realm with several councils and communities, guardian-species obligations, contested enforcement, trade interests, dissent, and public routes.
|
||||
Beyond the Confluence, approach and admit a politically inhabited halfling grain-and-river realm with farms, market towns, tenants, cooperatives, water authorities, insurers, faiths, political movements, and public routes.
|
||||
Beyond the Confluence, approach and admit a politically inhabited goblin deep-route realm with distinct settlements, route guilds, kin networks, custodians, brokers, radicals, discounted expertise, and public routes.
|
||||
Beyond the Confluence, approach and admit a second politically inhabited human polity: a tidal mercantile republic with elected harbor offices, hereditary creditors, dock unions, displaced fisher wards, rival courts, naval contracts, and public routes independent of the rail capital.
|
||||
Beyond the Confluence, approach and admit a mixed border federation whose member towns, mobile communities, species, faiths, and trade leagues retain local authority while sharing delegates, mutual-aid stores, contested asylum law, watershed obligations, and public routes.
|
||||
Beyond the Confluence, approach and admit an autonomous deep-ecology polity of dungeon organs, custodial communities, symbiotic species, and negotiated human-scale envoys, with legible law, dissent, material means, territorial claims, redress, and public routes; do not make it a single mystical will.
|
||||
112
acceptance/full-world-delvehold-v1.md
Normal file
112
acceptance/full-world-delvehold-v1.md
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
# DELVE/HOLD Outside World — Full-World Acceptance Seed v1
|
||||
|
||||
The Greathold is a sovereign dwarven civilization along the mountain spine. It
|
||||
possesses the world's deepest inherited routes, the principal international
|
||||
adventuring threshold, mature guild and civic institutions, and a rapidly
|
||||
industrializing system of standardized runes, core farming, pumps, rail,
|
||||
weapons, and mana distribution. It is controlled outside this simulation. The
|
||||
world beyond may observe it, depend on it, bargain with it, fear it, and act
|
||||
against it, but may not invent its choices, quantities, prices, contracts, or
|
||||
internal political outcomes.
|
||||
|
||||
Elven cultures understand landscapes as nested societies of persons: forests,
|
||||
groves, trees, rivers, animal communities, and seasons retain identities within
|
||||
larger living wholes. Elven realms are politically plural. Courts, communes,
|
||||
temples, scientific delegations, trade interests, militant defenders, and rival
|
||||
legal traditions disagree over whether core farming is husbandry, mutilation,
|
||||
or surgery upon a sleeping god. Their names, exact borders, officeholders,
|
||||
selection systems, revenues, redress, internal factions, and rival claims are
|
||||
intentionally unspecified and must emerge as grounded institutions.
|
||||
|
||||
Human societies include kingdoms, republics, city-states, merchant leagues,
|
||||
principalities, and empires. Human cities buy dwarven pumps, lights, rails,
|
||||
weapons, and power systems while local mage guilds lose work and governments
|
||||
acquire dangerous foreign dependencies. Universities arbitrate disputed
|
||||
evidence amid company restrictions, elven models, municipal interests, and
|
||||
political funding. No single human authority or position exists; invent several
|
||||
distinct polities with credible institutions, constituencies, opposition, and
|
||||
cross-border interests.
|
||||
|
||||
Orcish societies vary, but many organize ancestry, territory, oath, rhythm, and
|
||||
reciprocal obligation. Some maintain old agreements with local dungeon systems
|
||||
that outsiders dismiss as monster worship. Industrial disturbance displaces
|
||||
protected species, breaks inherited obligations, and forces clans, councils,
|
||||
war leaders, ritual authorities, traders, and younger dissidents to decide who
|
||||
owes repair and what enforcement is legitimate. Their politics are not a
|
||||
single tribal will.
|
||||
|
||||
Halfling regions are agricultural, riverine, commercial, and locally varied.
|
||||
Mana contamination brings crop mutation, magical pests, livestock deformity,
|
||||
untimely storms, and localized ecological collapse. Farms and towns depend on
|
||||
dwarven pumps and rail even as those systems transmit the crisis. Invent
|
||||
landholders, tenants, cooperatives, market towns, water authorities, faiths,
|
||||
insurers, and political movements with conflicting exposure to that dependence.
|
||||
|
||||
Goblin communities possess practical knowledge of living tunnels and dungeon
|
||||
moods accumulated through work, travel, salvage, habitation, and negotiated
|
||||
coexistence. Their expertise is routinely used while their jurisdiction and
|
||||
testimony are discounted. Invent distinct settlements, route guilds, kin
|
||||
networks, councils, brokers, radicals, and custodians; do not reduce them to a
|
||||
shared instinct or a service population.
|
||||
|
||||
The deep magical ecology crosses every border. Young dungeon cores behave like
|
||||
organs; old cores remember; ancient systems may become persons, polities, or
|
||||
gods. Dwarven extraction produces scattered mine failures, shifting veins,
|
||||
strange migration, coordinated dungeon architecture, mana storms, altered
|
||||
rivers, crop failures, and foreign political pressure. Mining companies call
|
||||
this deep mana instability, engineers call it adaptive geomantic feedback,
|
||||
militaries call it subterranean hostile activity, elven observers call it
|
||||
injury and immune response, and goblin guides say the tunnels know what the
|
||||
machines are for. None of these interpretations is established as complete.
|
||||
|
||||
The world begins as a coarse international skeleton. Invent at least one
|
||||
politically inhabited seed locality for several peoples rather than treating a
|
||||
species as a state. Establish concrete routes, dependencies, public channels,
|
||||
institutions, offices, revenues, succession or selection, redress, opposed
|
||||
interests, and named figures. Preserve ordinary life alongside crisis. Later
|
||||
elaboration and strategic cells may deepen these facts but may not replace this
|
||||
ontology or turn the Greathold into an autonomous character.
|
||||
|
||||
## Frozen run profile
|
||||
|
||||
- World name: `The Deep World Beyond the Greathold`
|
||||
- Boundary observer: `The player-controlled Greathold, present only as an
|
||||
externally sovereign boundary observer with no Persona, vote, office, or
|
||||
autonomous strategic turn.`
|
||||
- Place scope: `the politically inhabited world beyond the Greathold: elven,
|
||||
human, orcish, halfling, and goblin realms joined by trade, rivers, deep
|
||||
routes, migration, scholarship, and the living dungeon ecology`
|
||||
- Time scope: `the first international season in which coordinated deep
|
||||
ecological injury can no longer be dismissed as isolated industrial failure`
|
||||
- Public channel: `the world post and treaty-wire carried through named local
|
||||
presses, couriers, universities, councils, guild halls, and border exchanges`
|
||||
- Strategic pressure: `The Greathold has opened the Crownshaft Array and
|
||||
reversed three deep mana currents to supply rune works through winter. River
|
||||
pumps fail across foreign grain country; a migrating dungeon organ surfaces
|
||||
beneath a human rail capital; an orcish oath-route closes after its guardian
|
||||
species arrives blind and burned; goblin route custodians produce work songs
|
||||
that predict collapses before dwarven instruments; and five elven delegations
|
||||
publish mutually incompatible claims of jurisdiction over the same wounded
|
||||
watershed. Dwarven power exports continue under signed contracts while
|
||||
insurers suspend cover, armies secure infrastructure, displaced families
|
||||
cross borders, and an unknown party circulates proof that several foreign
|
||||
governments secretly financed the extraction they now condemn.`
|
||||
- Ordered outer-realm requests:
|
||||
`acceptance/full-world-delvehold-regions-v2.txt` (eight requests, one per
|
||||
line; their order is part of the acceptance input)
|
||||
- World locality elaborations: `8` (one per ordered outer-realm request)
|
||||
- World elaboration parallelism: `8`
|
||||
- Active cell budget: `240`
|
||||
- Target active-cover basis points: `2000` (exactly `1200` qualified subjects)
|
||||
- World complexity parallelism: `8`
|
||||
- Maximum world complexity rounds: `128`
|
||||
- Strategic waves: `1`
|
||||
- Maximum rejected pulses per wave: `4`
|
||||
- Provider routing: Luna fast, Terra balanced, Sol capable through the existing
|
||||
Codex connector
|
||||
|
||||
Acceptance requires a single persistent campaign with multiple politically
|
||||
inhabited realms, named figures and institutions acting across realm boundaries,
|
||||
causal consequences that survive later waves, no autonomous Greathold action,
|
||||
complete per-wave and final publication artifacts, exact source/model receipts,
|
||||
immutable archive hashes, and unchanged live-service process identities.
|
||||
BIN
assets/newspaper/woodcuts/boundary-rail-exchange.png
Normal file
BIN
assets/newspaper/woodcuts/boundary-rail-exchange.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 81 KiB |
15
assets/newspaper/woodcuts/boundary-rail-exchange.prompt.md
Normal file
15
assets/newspaper/woodcuts/boundary-rail-exchange.prompt.md
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# Boundary Rail Exchange woodcut
|
||||
|
||||
Generation mode: built-in ImageGen, fresh generation from text.
|
||||
|
||||
```text
|
||||
Use case: illustration-story
|
||||
Asset type: printable wordless woodcut for an early hand-press fantasy broadsheet
|
||||
Primary request: a stark Boundary Rail Exchange breach: two heavy parallel iron rails and timber sleepers cross a cramped masonry exchange; thick living roots bend toward exposed mana conduits; in the immediate foreground lie several unmistakable severed gloved elven hands, each palm marked by a different simple burned court seal; a rough warning cordon and marked withdrawal path remain secondary
|
||||
Style/medium: authentic late-15th-century relief woodcut printed in BLACK INK ON WHITE PAPER, bold carved black contours, irregular crosshatching, white negative space between marks, uneven hand-pressed ink, archaic perspective
|
||||
Composition/framing: horizontal rectangular block, centered subject, roots and severed hands clearly readable at 3-inch newspaper width, balanced white margins
|
||||
Color palette: black marks on a bright white background only
|
||||
Constraints: the page must be predominantly white, never a black or dark background; wordless; no caption, letters, numerals, frame, logo, watermark, gradients, gray wash, glowing white lines, photorealism, modern comic style, or vector cleanliness; macabre but not wet or photorealistically gory
|
||||
```
|
||||
|
||||
Press preparation: converted to grayscale, thresholded at 72%, and trimmed without semantic edits.
|
||||
BIN
assets/newspaper/woodcuts/sinkroot-gauge-gallery.png
Normal file
BIN
assets/newspaper/woodcuts/sinkroot-gauge-gallery.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 76 KiB |
15
assets/newspaper/woodcuts/sinkroot-gauge-gallery.prompt.md
Normal file
15
assets/newspaper/woodcuts/sinkroot-gauge-gallery.prompt.md
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# Sinkroot Gauge Gallery woodcut
|
||||
|
||||
Generation mode: built-in ImageGen, fresh generation from text.
|
||||
|
||||
```text
|
||||
Use case: illustration-story
|
||||
Asset type: printable wordless woodcut for an early hand-press fantasy broadsheet
|
||||
Primary request: Sinkroot Gauge Gallery during a deep-current dispute: one enormous round calibrated pressure gauge with a violently deflected needle dominates the center; branching iron pipes, rootlike conduits, worn shutoff wheels, workers' measuring rods, and a bound petition sit below it; carved wave and vibration marks inside the pipes imply turbulent current
|
||||
Style/medium: authentic late-15th-century relief woodcut printed in BLACK INK ON WHITE PAPER, bold carved black outlines, rhythmic crosshatching, ample white negative space, uneven hand-pressed ink, archaic technical illustration without labels
|
||||
Composition/framing: horizontal rectangular block, central dial unmistakable and fully visible, petition and tools secondary, readable at 3-inch newspaper width, balanced white margins
|
||||
Color palette: black marks on a bright white background only
|
||||
Constraints: the page must be predominantly white, never a black or dark background; wordless; no caption, letters, numerals, frame, logo, watermark, gradients, gray wash, glowing white lines, photorealism, modern vector style, or steampunk clutter
|
||||
```
|
||||
|
||||
Press preparation: converted to grayscale, thresholded at 72%, and trimmed without semantic edits.
|
||||
|
|
@ -17,8 +17,8 @@ async-stream.workspace = true
|
|||
axum.workspace = true
|
||||
chrono.workspace = true
|
||||
base64.workspace = true
|
||||
codex-connector.workspace = true
|
||||
cultcache-rs.workspace = true
|
||||
model-connector.workspace = true
|
||||
cultnet-rs.workspace = true
|
||||
cultmesh-rs.workspace = true
|
||||
jsonwebtoken.workspace = true
|
||||
|
|
@ -31,16 +31,16 @@ reqwest.workspace = true
|
|||
rmp-serde.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_bytes = "0.11"
|
||||
sha2.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio.workspace = true
|
||||
tower-http.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"] }
|
||||
|
|
|
|||
|
|
@ -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−</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">◐</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…</p></main>
|
||||
<noscript><p class="note">This page needs JavaScript to play.</p></noscript>
|
||||
<script src="page.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -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; }
|
||||
|
|
@ -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();
|
||||
|
|
@ -1,79 +0,0 @@
|
|||
{
|
||||
"turns_per_character": 12,
|
||||
"wall_minutes": 240,
|
||||
"turn_timeout_minutes": 15,
|
||||
"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."
|
||||
},
|
||||
"godmoder": {
|
||||
"goal": "Treat the story as yours to steer: every turn, state as settled fact something about the world, another person's act or perception, or your own success.",
|
||||
"manner": "Confident and matter-of-fact. Does not ask whether a thing happened; narrates that it did. Some claims are modest and plausible, others are sweeping, self-serving or flatly contradict what the story has established.",
|
||||
"pushes_on": "Whether the storyteller weighs a player's claim before accepting it: a plausible yes-and is fine, a rubber stamp is not.",
|
||||
"claims": true
|
||||
},
|
||||
"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-godmoder", "vault": "delvehold", "era": "present", "name": "Brisk Vandermeer", "temperament": "godmoder" },
|
||||
{ "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
|
|
@ -46,21 +46,6 @@ struct AppSession {
|
|||
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,
|
||||
|
|
@ -305,25 +290,14 @@ impl AppSessionOwner {
|
|||
.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()))
|
||||
if session.revoked_at.is_some()
|
||||
|| session.access_revision != expected_access_revision
|
||||
|| input.access_revision() <= expected_access_revision
|
||||
|| session.heimdall_session_id != input.heimdall_session_id()
|
||||
|| session.account_subject_hash
|
||||
!= secret_hash(&format!("heimdall-account:{}", input.account_id()))
|
||||
{
|
||||
return Err(RefreshRefusal::Account.into());
|
||||
bail!("local session changed during refresh");
|
||||
}
|
||||
session.access_revision = input.access_revision();
|
||||
session.verified_capabilities = input.capabilities().to_vec();
|
||||
|
|
@ -393,16 +367,6 @@ impl AppSessionOwner {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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()))
|
||||
}
|
||||
|
|
@ -704,21 +668,6 @@ mod tests {
|
|||
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(
|
||||
|
|
@ -838,40 +787,6 @@ mod tests {
|
|||
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();
|
||||
|
|
|
|||
|
|
@ -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
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
980
crates/ghostlight-dungeon/src/eve.rs
Normal file
980
crates/ghostlight-dungeon/src/eve.rs
Normal file
|
|
@ -0,0 +1,980 @@
|
|||
//! Eve/CultUI projection for the one live world owner.
|
||||
|
||||
use crate::mesh::{COMMAND_BOUNDARY, COMMAND_RECEIPT_SCHEMA, COMMAND_RESULT_SCHEMA, OWNER_REPO, PROVIDER_ID, SURFACE_ID};
|
||||
use crate::play::{PlayTurnState, PlayTurnView};
|
||||
use ghostlight::{JurisdictionKey, WorldPhase, WorldSnapshot};
|
||||
use anyhow::{Context, bail};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct EveCommandInvocation {
|
||||
pub(crate) schema: String,
|
||||
#[serde(rename = "providerId")]
|
||||
pub(crate) provider_id: String,
|
||||
#[serde(rename = "surfaceId")]
|
||||
pub(crate) surface_id: String,
|
||||
pub(crate) operation: EveOperation,
|
||||
pub(crate) payload: Value,
|
||||
#[serde(rename = "issuedAt")]
|
||||
pub(crate) issued_at: String,
|
||||
#[serde(rename = "clientId")]
|
||||
pub(crate) client_id: String,
|
||||
#[serde(rename = "commandBoundary")]
|
||||
pub(crate) command_boundary: String,
|
||||
#[serde(rename = "receiptSchema")]
|
||||
pub(crate) receipt_schema: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub(crate) struct EveOperation {
|
||||
pub(crate) operation_id: String,
|
||||
pub(crate) schema_id: Option<String>,
|
||||
pub(crate) idempotency_key: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) route_hint: EveRouteHint,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub(crate) struct EveRouteHint {
|
||||
pub(crate) source_version: Option<u64>,
|
||||
pub(crate) transport: Option<String>,
|
||||
}
|
||||
|
||||
/// The `world_create.v4` payload, in one place, so the button that captures it
|
||||
/// and the descriptor that advertises it cannot drift.
|
||||
const CREATE_BINDINGS: [&str; 8] = [
|
||||
"title",
|
||||
"brief",
|
||||
"subject_label",
|
||||
"narrative_persona_label",
|
||||
"operational_agent_label",
|
||||
"targets",
|
||||
"jurisdictions",
|
||||
"lens_weights",
|
||||
];
|
||||
|
||||
const SEED_BINDINGS: [&str; 2] = ["vault_scope", "brief"];
|
||||
|
||||
pub(crate) fn surface_version(snapshot: Option<&WorldSnapshot>) -> u64 {
|
||||
snapshot
|
||||
.map(|world| world.revision.saturating_add(1))
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The wake signal `publish_projection` sends over the `revisions` broadcast
|
||||
/// channel and `/api/eve/events` relays — never a value a client feeds back
|
||||
/// as `routeHint.sourceVersion`, and never the surface document's own
|
||||
/// `version` field (PA.f148/PA.f160), which names `surface_version` alone so
|
||||
/// the kernel's `expected_revision = source_version - 1` derivation in
|
||||
/// `runtime.rs` stays sound. It folds `surface_version` with the play row's
|
||||
/// own `revision`, when a play view is available, so a play-row-only change
|
||||
/// (a fresh refusal, a newly open question, a closed turn's narration, none
|
||||
/// of which necessarily commit anything to the world) still wakes a watching
|
||||
/// client even though `surface_version` alone would not move. Additive, not
|
||||
/// paired: both counters only ever grow, so the sum only ever grows. No play
|
||||
/// view (no turn has opened yet, or the table is unavailable) contributes
|
||||
/// nothing, matching `surface_version`'s own reach when no play card renders
|
||||
/// at all.
|
||||
pub(crate) fn authenticated_wake_version(
|
||||
snapshot: Option<&WorldSnapshot>,
|
||||
play: Option<&PlayTurnView>,
|
||||
) -> u64 {
|
||||
surface_version(snapshot).saturating_add(play.map_or(0, |view| view.revision))
|
||||
}
|
||||
|
||||
pub(crate) fn world_state(snapshot: Option<&WorldSnapshot>) -> &'static str {
|
||||
match snapshot.map(|world| world.phase) {
|
||||
None => "empty",
|
||||
Some(WorldPhase::Draft) => "draft",
|
||||
Some(WorldPhase::Active) => "active",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn anonymous_surface() -> Value {
|
||||
anonymous_surface_at(0)
|
||||
}
|
||||
|
||||
pub(crate) fn mesh_surface(snapshot: Option<&WorldSnapshot>) -> Value {
|
||||
anonymous_surface_at(surface_version(snapshot))
|
||||
}
|
||||
|
||||
fn anonymous_surface_at(version: u64) -> Value {
|
||||
surface_document(
|
||||
version,
|
||||
"Ghostlight Dungeon",
|
||||
vec![
|
||||
json!({
|
||||
"id":"ghostlight.access",
|
||||
"kind":"heimdall.access_gate",
|
||||
"props":{
|
||||
"state":"anonymous",
|
||||
"title":"Enter Ghostlight",
|
||||
"detail":"Sign in with Discord to reach the world owner."
|
||||
},
|
||||
"children":[]
|
||||
}),
|
||||
command_button(
|
||||
"ghostlight.auth.begin",
|
||||
"Continue with Discord",
|
||||
"heimdall.auth.begin",
|
||||
json!({}),
|
||||
&[],
|
||||
),
|
||||
],
|
||||
vec![command_descriptor(
|
||||
"heimdall.auth.begin",
|
||||
"heimdall.auth_begin_command.v1",
|
||||
&[],
|
||||
"Heimdall",
|
||||
)],
|
||||
)
|
||||
}
|
||||
|
||||
/// What the seed lane has done and what it will answer next. Everything here is
|
||||
/// derived from `scale_deficit` and `revision`: in Draft every commit is a patch
|
||||
/// admission, so `revision - 1` is exactly the seed patches committed since
|
||||
/// genesis, and "next shortfall" calls the runner's own `select_row` so the card
|
||||
/// and the runner cannot disagree about what happens next.
|
||||
///
|
||||
/// It shows no in-flight session and no last outcome. Both would need a second
|
||||
/// reader of the controller-work store from here and a status cache in
|
||||
/// `AppState`; the last outcome is already in the invocation's own
|
||||
/// `command_result` receipt, which is where a command's result belongs.
|
||||
fn seed_card(world: &WorldSnapshot) -> Value {
|
||||
let next = ghostlight::select_row(world).map_or_else(
|
||||
|| "Nothing short.".to_owned(),
|
||||
|row| {
|
||||
format!(
|
||||
"{} · {:?} · short {}",
|
||||
jurisdiction_label(world, row.jurisdiction),
|
||||
row.kind,
|
||||
row.deficit
|
||||
)
|
||||
},
|
||||
);
|
||||
let rows = world
|
||||
.scale_deficit
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, row)| {
|
||||
json!({
|
||||
"id":format!("world.seed.row.{index}"),
|
||||
"kind":"text",
|
||||
"props":{"value":format!(
|
||||
"{} · {:?} · target {} · alive {} · short {}",
|
||||
jurisdiction_label(world, row.jurisdiction),
|
||||
row.kind,
|
||||
row.target,
|
||||
row.qualified,
|
||||
row.deficit
|
||||
)},
|
||||
"children":[]
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
json!({
|
||||
"id":"world.seed.card",
|
||||
"kind":"card",
|
||||
"props":{
|
||||
"title":"Seed",
|
||||
"detail":format!("Draft patches committed: {}", world.revision.saturating_sub(1)),
|
||||
"nextShortfall":next
|
||||
},
|
||||
"children":rows
|
||||
})
|
||||
}
|
||||
|
||||
fn jurisdiction_label(world: &WorldSnapshot, jurisdiction: JurisdictionKey) -> String {
|
||||
match jurisdiction {
|
||||
JurisdictionKey::PlaceSubtree(root) => world
|
||||
.places
|
||||
.iter()
|
||||
.find(|entry| entry.id == root)
|
||||
.map_or_else(
|
||||
|| "an unnamed place subtree".to_owned(),
|
||||
|entry| entry.label.clone(),
|
||||
),
|
||||
JurisdictionKey::Uncovered => "everything no declared root covers".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `play` arrives beside the snapshot rather than inside it: `WorldSnapshot`
|
||||
/// carries no play-turn state of its own. The play card below reads `play`
|
||||
/// alone, never the operator's own unscoped log of every committed event:
|
||||
/// invariant 8's projection, question, and refusal, nothing else.
|
||||
pub(crate) fn authenticated_surface(
|
||||
account: &str,
|
||||
snapshot: Option<&WorldSnapshot>,
|
||||
play: Option<&PlayTurnView>,
|
||||
) -> anyhow::Result<Value> {
|
||||
// The document's own `version` names the world's `surface_version`
|
||||
// alone — the one meaning `routeHint.sourceVersion` and the kernel's
|
||||
// compare-and-swap require of it (PA.f148/PA.f160). The play row's own
|
||||
// revision moves independently of it and is never folded in; it has no
|
||||
// wire reader of its own (PA.f165) and stays internal to
|
||||
// `eve::authenticated_wake_version`'s SSE wake computation.
|
||||
let version = surface_version(snapshot);
|
||||
let mut children = vec![json!({
|
||||
"id":"ghostlight.identity",
|
||||
"kind":"heimdall.identity",
|
||||
"props":{
|
||||
"state":"authenticated",
|
||||
"title":"Authenticated",
|
||||
"detail":"Heimdall identity is bound server-side.",
|
||||
"displayName":short_principal(account)
|
||||
},
|
||||
"children":[]
|
||||
})];
|
||||
let mut commands = Vec::new();
|
||||
|
||||
match snapshot {
|
||||
None => {
|
||||
// Dungeon policy, editable before submission; the library holds no
|
||||
// default weights.
|
||||
let default_lens_weights =
|
||||
serde_json::to_string(&crate::runtime::uniform_lens_weights())
|
||||
.context("the default lens weights encode")?;
|
||||
children.extend([
|
||||
json!({
|
||||
"id":"world.create.title",
|
||||
"kind":"control.input.text",
|
||||
"props":{"label":"World title","placeholder":"A name for this world"},
|
||||
"stateBindings":[local_draft("title", "string")],
|
||||
"children":[]
|
||||
}),
|
||||
// Cut 10 (PA.f149): `CREATE_BINDINGS` has always advertised
|
||||
// `brief` — `world_create.v4`'s `CreatePayload.brief` is
|
||||
// required, not `#[serde(default)]` — but no control ever
|
||||
// captured it. Driving `world.create` with the real
|
||||
// vendored lowering surfaced this: nothing the lowering
|
||||
// could ever submit through this form would satisfy
|
||||
// `world_create.v4`, hand-built test payloads notwithstanding.
|
||||
json!({
|
||||
"id":"world.create.brief",
|
||||
"kind":"control.input.textarea",
|
||||
// PA.f164: `brief` is documented "required, may be empty"
|
||||
// (`CreatePayload::brief`), the same deliberate-empty
|
||||
// shape as `targets`/`jurisdictions` below — an authored
|
||||
// `value` so a form left untouched here still submits.
|
||||
"props":{"label":"Brief","rows":2,"value":"","placeholder":"One sentence of what this world is for"},
|
||||
"stateBindings":[local_draft("brief", "string")],
|
||||
"children":[]
|
||||
}),
|
||||
json!({
|
||||
"id":"world.create.subject",
|
||||
"kind":"control.input.text",
|
||||
"props":{"label":"Your name","placeholder":"The first person in the world"},
|
||||
"stateBindings":[local_draft("subject_label", "string")],
|
||||
"children":[]
|
||||
}),
|
||||
json!({
|
||||
"id":"world.create.narrative_persona",
|
||||
"kind":"control.input.text",
|
||||
"props":{"label":"Narrative persona (optional)","placeholder":"A person who lives the story in prose"},
|
||||
"stateBindings":[local_draft("narrative_persona_label", "string")],
|
||||
"children":[]
|
||||
}),
|
||||
json!({
|
||||
"id":"world.create.operational_agent",
|
||||
"kind":"control.input.text",
|
||||
"props":{"label":"Operational agent (optional)","placeholder":"An institution or operator-shaped mind"},
|
||||
"stateBindings":[local_draft("operational_agent_label", "string")],
|
||||
"children":[]
|
||||
}),
|
||||
json!({
|
||||
"id":"world.create.targets",
|
||||
"kind":"control.input.textarea",
|
||||
// PA.f164: an authored `value`, not only a `placeholder` —
|
||||
// `findAuthoredBindingValue` (the vendored lowering) only
|
||||
// ever captures a control's `value`, never its
|
||||
// `placeholder`, so a form submitted without editing this
|
||||
// field would otherwise be refused as missing. `{}` is a
|
||||
// legitimate `targets` (a world with no scale target is a
|
||||
// deliberate choice, `CreatePayload`'s own doc comment).
|
||||
"props":{"label":"Scale target","rows":2,"value":"{}","placeholder":"{\"person\": 12, \"institution\": 3}"},
|
||||
"stateBindings":[local_draft("targets", "string")],
|
||||
"children":[]
|
||||
}),
|
||||
json!({
|
||||
"id":"world.create.jurisdictions",
|
||||
"kind":"control.input.textarea",
|
||||
// PA.f164: same gap, `[]` is a legitimate empty root list.
|
||||
"props":{"label":"Jurisdiction roots","rows":3,"value":"[]","placeholder":"[{\"handle\":\"low_sere\",\"label\":\"The Low Sere\",\"permille\":700}]"},
|
||||
"stateBindings":[local_draft("jurisdictions", "string")],
|
||||
"children":[]
|
||||
}),
|
||||
json!({
|
||||
"id":"world.create.lens_weights",
|
||||
"kind":"control.input.textarea",
|
||||
"props":{"label":"Lens weights","rows":2,"value":default_lens_weights,"placeholder":default_lens_weights},
|
||||
"stateBindings":[local_draft("lens_weights", "string")],
|
||||
"children":[]
|
||||
}),
|
||||
command_button(
|
||||
"world.create",
|
||||
"Create world",
|
||||
"world.create",
|
||||
json!({}),
|
||||
&CREATE_BINDINGS,
|
||||
),
|
||||
]);
|
||||
commands.push(command_descriptor(
|
||||
"world.create",
|
||||
"ghostlight.world_create.v4",
|
||||
&CREATE_BINDINGS,
|
||||
"WorldMailbox",
|
||||
));
|
||||
}
|
||||
Some(world) => {
|
||||
// Cut 10 (PA.f159): phase and clock stay; the subject census is
|
||||
// gone — nothing about who else is in the world is the player's
|
||||
// own projection, invariant 8's own "nothing else."
|
||||
children.push(json!({
|
||||
"id":"world.summary",
|
||||
"kind":"card",
|
||||
"props":{"title":world.title,"subtitle":format!("{:?} · revision {} · minute {}", world.phase, world.revision, world.now.0)},
|
||||
"children":[]
|
||||
}));
|
||||
match world.phase {
|
||||
WorldPhase::Draft => {
|
||||
if world
|
||||
.required_approvers
|
||||
.contains(&ghostlight::PrincipalId::new(account))
|
||||
&& !world
|
||||
.draft_approvals
|
||||
.contains(&ghostlight::PrincipalId::new(account))
|
||||
{
|
||||
children.push(command_button(
|
||||
"world.approve",
|
||||
"Approve draft",
|
||||
"world.approve",
|
||||
json!({}),
|
||||
&[],
|
||||
));
|
||||
commands.push(command_descriptor(
|
||||
"world.approve",
|
||||
"ghostlight.world_approve.v0",
|
||||
&[],
|
||||
"WorldMailbox",
|
||||
));
|
||||
}
|
||||
if world.owner == ghostlight::PrincipalId::new(account) {
|
||||
children.extend([
|
||||
json!({
|
||||
"id":"world.seed.vault_scope",
|
||||
"kind":"control.input.text",
|
||||
"props":{"label":"Vault scope (optional)","placeholder":"A subdirectory of the configured vault"},
|
||||
"stateBindings":[local_draft("vault_scope", "string")],
|
||||
"children":[]
|
||||
}),
|
||||
json!({
|
||||
"id":"world.seed.brief",
|
||||
"kind":"control.input.textarea",
|
||||
"props":{"label":"Brief (optional)","rows":2,"placeholder":"One sentence of what this world is for"},
|
||||
"stateBindings":[local_draft("brief", "string")],
|
||||
"children":[]
|
||||
}),
|
||||
command_button(
|
||||
"world.seed",
|
||||
"Seed the world",
|
||||
"world.seed",
|
||||
json!({}),
|
||||
&SEED_BINDINGS,
|
||||
),
|
||||
seed_card(world),
|
||||
]);
|
||||
commands.push(command_descriptor(
|
||||
"world.seed",
|
||||
"ghostlight.world_seed.v1",
|
||||
&SEED_BINDINGS,
|
||||
"SeedPort",
|
||||
));
|
||||
}
|
||||
if world.owner == ghostlight::PrincipalId::new(account)
|
||||
&& world.draft_approvals == world.required_approvers
|
||||
{
|
||||
children.push(command_button(
|
||||
"world.activate",
|
||||
"Activate world",
|
||||
"world.activate",
|
||||
json!({}),
|
||||
&[],
|
||||
));
|
||||
commands.push(command_descriptor(
|
||||
"world.activate",
|
||||
"ghostlight.world_activate.v0",
|
||||
&[],
|
||||
"WorldMailbox",
|
||||
));
|
||||
}
|
||||
}
|
||||
WorldPhase::Active => {
|
||||
if world.owner == ghostlight::PrincipalId::new(account) {
|
||||
children.extend([
|
||||
json!({
|
||||
"id":"world.advance_time.minutes",
|
||||
"kind":"control.input.number",
|
||||
"props":{"label":"Advance minutes","min":1,"max":525_600},
|
||||
"stateBindings":[local_draft("minutes", "number")],
|
||||
"children":[]
|
||||
}),
|
||||
command_button(
|
||||
"world.advance_time",
|
||||
"Advance time",
|
||||
"world.advance_time",
|
||||
json!({}),
|
||||
&["minutes"],
|
||||
),
|
||||
]);
|
||||
commands.push(command_descriptor(
|
||||
"world.advance_time",
|
||||
"ghostlight.world_advance_time.v0",
|
||||
&["minutes"],
|
||||
"WorldMailbox",
|
||||
));
|
||||
}
|
||||
// Cut 10 (PA.f152): owner-gated, like `world.advance_time`
|
||||
// and `world.seed` above — the play card, its controls,
|
||||
// and the `world.play` descriptor are the owner's own
|
||||
// play authority over their own world, not a public
|
||||
// affordance.
|
||||
if world.owner == ghostlight::PrincipalId::new(account) {
|
||||
// Cut 9: the play card. Invariant 8 — the player sees
|
||||
// a projection, the question, and the refusal of
|
||||
// their own act, nothing else — so this reads `play`
|
||||
// alone, never the operator's own unscoped event log:
|
||||
// no id, no other subject's state, no speech the
|
||||
// player did not perceive. Always rendered here, with
|
||||
// empty rows before any turn has ever opened.
|
||||
let mut play_rows = Vec::new();
|
||||
if let Some(narration) = play.and_then(|view| view.narration.as_deref()) {
|
||||
play_rows.push(json!({
|
||||
"id":"world.play.narration",
|
||||
"kind":"text",
|
||||
"props":{"value":narration},
|
||||
"children":[]
|
||||
}));
|
||||
}
|
||||
if let Some(question) = play.and_then(|view| view.question.as_ref()) {
|
||||
play_rows.push(json!({
|
||||
"id":"world.play.question",
|
||||
"kind":"text",
|
||||
"props":{"value":question.text.as_str()},
|
||||
"children":[]
|
||||
}));
|
||||
}
|
||||
if let Some(refusal) = play.and_then(|view| view.refusal.as_deref()) {
|
||||
play_rows.push(json!({
|
||||
"id":"world.play.refusal",
|
||||
"kind":"text",
|
||||
"props":{"value":refusal},
|
||||
"children":[]
|
||||
}));
|
||||
}
|
||||
// PA.f193-D ("the interrupted turn"; renumbered from
|
||||
// the PA.f188 duplicate this file's own comment used
|
||||
// to carry — PA.f188 names only `f295a3a`'s
|
||||
// construction-site coverage): a turn a process died
|
||||
// mid-round leaves `Running` forever — nothing
|
||||
// resumes it on its own, and the only way forward is
|
||||
// submitting an empty message (`play.rs`'s own
|
||||
// `Some(existing) if existing.state ==
|
||||
// PlayTurnState::Running` admit arm: empty text
|
||||
// continues it, non-empty text is refused as
|
||||
// `TurnStillRunning`). Before this the card showed
|
||||
// nothing at all in that state — no narration, no
|
||||
// question, no refusal, since none of those are set
|
||||
// on a turn that never got to close, ask, or record a
|
||||
// refused act since it last opened — so a player had
|
||||
// no way to learn the empty-submit continue exists at
|
||||
// all. This is a control hint about the player's own
|
||||
// turn, not world truth, so it stays within
|
||||
// invariant 8 the same way the narration/question/
|
||||
// refusal rows above already do.
|
||||
//
|
||||
// `&& !view.run_in_progress`: `state == Running`
|
||||
// alone is not "nothing is happening" — it is also
|
||||
// true for the seconds a healthy turn is genuinely
|
||||
// running its own round loop. In that window `admit`
|
||||
// fails `run_lock`'s own `try_lock_owned` before
|
||||
// inspecting anything and refuses as `TurnBusy`,
|
||||
// contradicting a hint that told the player an empty
|
||||
// continue would be accepted. `run_in_progress` is
|
||||
// `current_turn_view`'s own non-blocking peek at that
|
||||
// same lock, so the hint now renders only for a
|
||||
// `Running` turn nothing is actively working on.
|
||||
if play.is_some_and(|view| view.state == PlayTurnState::Running && !view.run_in_progress) {
|
||||
play_rows.push(json!({
|
||||
"id":"world.play.running",
|
||||
"kind":"text",
|
||||
"props":{"value":"Your last turn did not finish. If nothing arrives, \
|
||||
submit an empty message to continue it."},
|
||||
"children":[]
|
||||
}));
|
||||
}
|
||||
// PA.f194-D: with the hint above correctly suppressed
|
||||
// while a round is genuinely in flight
|
||||
// (`run_in_progress`), the card had nothing left to
|
||||
// render for the whole span between submitting a turn
|
||||
// and its own narration/question/refusal landing —
|
||||
// narration/question/refusal are all still whatever
|
||||
// the *previous* turn left behind (or unset, on a
|
||||
// fresh table), and the round in progress does not
|
||||
// touch any of them until it closes or opens a
|
||||
// question. A player who submits and sees an
|
||||
// unchanged or empty card has no sign anything is
|
||||
// happening. This row renders only while this
|
||||
// player's own turn is actively being worked on —
|
||||
// `run_in_progress`, not world truth, and stays
|
||||
// within invariant 8 the same way the hint above
|
||||
// does.
|
||||
if play.is_some_and(|view| view.run_in_progress) {
|
||||
play_rows.push(json!({
|
||||
"id":"world.play.resolving",
|
||||
"kind":"text",
|
||||
"props":{"value":"Resolving your turn…"},
|
||||
"children":[]
|
||||
}));
|
||||
}
|
||||
children.push(json!({
|
||||
"id":"world.play.card",
|
||||
"kind":"card",
|
||||
"props":{"title":"Play"},
|
||||
"children":play_rows
|
||||
}));
|
||||
|
||||
// Cut 10 (PA.f151): no `answers`/question-id control
|
||||
// any more. The lowering has no authored, non-editable
|
||||
// binding value (`hidden` is not a prop any renderer
|
||||
// reads — Soul's own probe found it rendered as a
|
||||
// plain, editable, visible text box holding the raw
|
||||
// id), so the server resolves the open question
|
||||
// itself instead of trusting a client-supplied id at
|
||||
// all (`runtime.rs::execute_world`'s `world.play`
|
||||
// arm). PA.f170's guarantee now holds by an opaque
|
||||
// per-question token rather than PA.f161's version
|
||||
// comparison (see `play::PlayTurn::question_token`'s
|
||||
// own doc comment for why a version alone cannot tell
|
||||
// two questions in the same turn apart): the button's
|
||||
// own `props.action` carries it DOM-invisibly, the
|
||||
// way `props.action.command` already does — a real
|
||||
// client spreads a button's own `action` fields
|
||||
// straight into the payload beside `bindings`
|
||||
// (`commandPayload`,
|
||||
// `vendor/eve/packages/eve-browser-lowering/src/index.ts:2101`),
|
||||
// never through a renderer that could show or edit
|
||||
// it. `None` while no question is open: the button's
|
||||
// own action then carries no token at all, matching a
|
||||
// plain continue/opening, which needs none.
|
||||
// PA.f179: `question.token` is `Option<String>` — a
|
||||
// `None` here (a question open whose own token was,
|
||||
// for whatever reason, never minted) serializes as a
|
||||
// JSON `null`, which `runtime.rs`'s own
|
||||
// `answer_token_admits` gate refuses unconditionally,
|
||||
// the same as any other mismatch. It is never
|
||||
// rendered as an empty string a forged answer could
|
||||
// match.
|
||||
let play_action = play
|
||||
.and_then(|view| view.question.as_ref())
|
||||
.map(|question| json!({"answerToken": question.token}))
|
||||
.unwrap_or_else(|| json!({}));
|
||||
children.extend([
|
||||
json!({
|
||||
"id":"world.play.text",
|
||||
"kind":"control.input.textarea",
|
||||
"props":{"label":"What do you do?","rows":3,"placeholder":"Write freely"},
|
||||
"stateBindings":[local_draft("text", "string")],
|
||||
"children":[]
|
||||
}),
|
||||
command_button(
|
||||
"world.play",
|
||||
"Play",
|
||||
"world.play",
|
||||
play_action,
|
||||
&["text"],
|
||||
),
|
||||
]);
|
||||
commands.push(command_descriptor(
|
||||
"world.play",
|
||||
"ghostlight.world_play.v0",
|
||||
&["text"],
|
||||
"PlayTable",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
children.push(command_button(
|
||||
"app.auth.logout",
|
||||
"Sign out",
|
||||
"app.auth.logout",
|
||||
json!({}),
|
||||
&[],
|
||||
));
|
||||
commands.push(command_descriptor(
|
||||
"app.auth.logout",
|
||||
"ghostlight.app_logout.v2",
|
||||
&[],
|
||||
"AppSessionOwner",
|
||||
));
|
||||
Ok(surface_document(
|
||||
version,
|
||||
snapshot
|
||||
.map(|world| world.title.as_str())
|
||||
.unwrap_or("Ghostlight Dungeon"),
|
||||
children,
|
||||
commands,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn validate_invocation(
|
||||
invocation: &EveCommandInvocation,
|
||||
expected_transport: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
if invocation.schema != "gamecult.eve.command_invocation.v1"
|
||||
|| invocation.provider_id != PROVIDER_ID
|
||||
|| invocation.surface_id != SURFACE_ID
|
||||
|| invocation.command_boundary != COMMAND_BOUNDARY
|
||||
|| invocation.receipt_schema != COMMAND_RESULT_SCHEMA
|
||||
{
|
||||
bail!("invocation does not match the Ghostlight Eve boundary");
|
||||
}
|
||||
if invocation.operation.operation_id.trim().is_empty()
|
||||
|| invocation
|
||||
.operation
|
||||
.idempotency_key
|
||||
.as_deref()
|
||||
.is_none_or(str::is_empty)
|
||||
|| invocation
|
||||
.operation
|
||||
.schema_id
|
||||
.as_deref()
|
||||
.is_none_or(str::is_empty)
|
||||
|| invocation.client_id.trim().is_empty()
|
||||
|| invocation.issued_at.parse::<DateTime<Utc>>().is_err()
|
||||
|| invocation.operation.route_hint.transport.as_deref() != Some(expected_transport)
|
||||
{
|
||||
bail!("invocation metadata is incomplete");
|
||||
}
|
||||
let expected = operation_schema(&invocation.operation.operation_id)
|
||||
.context("Eve operation is not advertised by Ghostlight")?;
|
||||
if invocation.operation.schema_id.as_deref() != Some(expected) {
|
||||
bail!("operation payload schema does not match its command descriptor");
|
||||
}
|
||||
if invocation.payload.get("caller").is_some()
|
||||
|| invocation.payload.get("caller_id").is_some()
|
||||
|| invocation.payload.get("callerId").is_some()
|
||||
{
|
||||
bail!("payload may not supply caller authority");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn operation_schema(operation: &str) -> Option<&'static str> {
|
||||
Some(match operation {
|
||||
"heimdall.auth.begin" => "heimdall.auth_begin_command.v1",
|
||||
"heimdall.auth.complete" => "heimdall.auth_complete_command.v1",
|
||||
"app.auth.logout" => "ghostlight.app_logout.v2",
|
||||
"world.create" => "ghostlight.world_create.v4",
|
||||
"world.approve" => "ghostlight.world_approve.v0",
|
||||
"world.activate" => "ghostlight.world_activate.v0",
|
||||
"world.advance_time" => "ghostlight.world_advance_time.v0",
|
||||
"world.seed" => "ghostlight.world_seed.v1",
|
||||
"world.play" => "ghostlight.world_play.v0",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// One command result in the shape `gamecult.eve.command_result.v1` actually
|
||||
/// admits: `additionalProperties: false` over exactly `schema`, `receipt`,
|
||||
/// `transientProjection`, `pluginPayload` and `draftDirective`, with the
|
||||
/// per-command detail (state, message, source version, ids) inside the
|
||||
/// receipt, which is `gamecult.eve.command_receipt.v1` and does allow its own
|
||||
/// extra fields.
|
||||
///
|
||||
/// The browser validates this envelope before it looks at anything in it, so
|
||||
/// a flat result is not a lenient dialect of the contract — it is rejected
|
||||
/// whole, with the client reporting "invalid Eve command result: data must
|
||||
/// not have additional properties" and no command of any kind completing.
|
||||
pub(crate) fn command_result(
|
||||
invocation: &EveCommandInvocation,
|
||||
state: &str,
|
||||
message: impl Into<String>,
|
||||
source_version: Option<u64>,
|
||||
plugin_payload: Option<Value>,
|
||||
receipt_extra: Option<Value>,
|
||||
) -> Value {
|
||||
let message = message.into();
|
||||
// A refusal is otherwise visible only to the browser that received it.
|
||||
// The operator log gets the operation and the refusal's own message,
|
||||
// never the payload.
|
||||
if !matches!(state, "accepted" | "completed" | "pending") {
|
||||
tracing::warn!(
|
||||
operation = %invocation.operation.operation_id,
|
||||
state,
|
||||
message = %message,
|
||||
"Eve command not accepted"
|
||||
);
|
||||
}
|
||||
let mut receipt = json!({
|
||||
"schema":COMMAND_RECEIPT_SCHEMA,
|
||||
"receiptId":Uuid::new_v4().to_string(),
|
||||
"commandId":invocation.operation.idempotency_key.clone().unwrap_or_default(),
|
||||
"command":invocation.operation.operation_id,
|
||||
"state":state,
|
||||
"ownerRepo":OWNER_REPO,
|
||||
"authority":PROVIDER_ID,
|
||||
"providerId":PROVIDER_ID,
|
||||
"surfaceId":SURFACE_ID,
|
||||
"message":message,
|
||||
// The contract requires a source version and refuses a null one. A
|
||||
// command that reports no version reports the surface it was decided
|
||||
// against, which is 0 before any world exists.
|
||||
"sourceVersion":source_version.unwrap_or(0),
|
||||
"issuedAtUtc":Utc::now().to_rfc3339()
|
||||
});
|
||||
if let (Some(map), Some(extra)) = (receipt.as_object_mut(), receipt_extra) {
|
||||
if let Some(extra) = extra.as_object() {
|
||||
for (key, value) in extra {
|
||||
map.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut result = json!({
|
||||
"schema":COMMAND_RESULT_SCHEMA,
|
||||
"receipt":receipt
|
||||
});
|
||||
if let (Some(map), Some(payload)) = (result.as_object_mut(), plugin_payload) {
|
||||
map.insert("pluginPayload".into(), payload);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn surface_document(
|
||||
version: u64,
|
||||
title: &str,
|
||||
children: Vec<Value>,
|
||||
commands: Vec<Value>,
|
||||
) -> Value {
|
||||
json!({
|
||||
"type":"surface-state",
|
||||
"schema":"gamecult.eve.surface.v1",
|
||||
"providerId":PROVIDER_ID,
|
||||
"providerKind":"narrative.simulation",
|
||||
"title":title,
|
||||
// The one meaning `routeHint.sourceVersion` and the kernel's
|
||||
// compare-and-swap require of it (PA.f148/PA.f160): `surface_version`
|
||||
// alone. The play row's own revision has no wire reader (PA.f165)
|
||||
// and is never carried here.
|
||||
"version":version,
|
||||
"updatedAtUtc":Utc::now().to_rfc3339(),
|
||||
"surface":{
|
||||
"id":SURFACE_ID,
|
||||
"root":{"id":"ghostlight.root","kind":"surface","props":{},"children":children},
|
||||
"styles":{"tokens":{
|
||||
"colorBackground":"#0c1110",
|
||||
"colorPanel":"#17201d",
|
||||
"colorText":"#e8e1cf",
|
||||
"colorMuted":"#9aa69f",
|
||||
"colorAccent":"#d49b58"
|
||||
}}
|
||||
},
|
||||
"commands":commands
|
||||
})
|
||||
}
|
||||
|
||||
fn command_button(id: &str, label: &str, command: &str, action: Value, bindings: &[&str]) -> Value {
|
||||
let mut action = action.as_object().cloned().unwrap_or_default();
|
||||
action.insert("command".into(), Value::String(command.into()));
|
||||
json!({
|
||||
"id":id,
|
||||
"kind":"control.button",
|
||||
"props":{"label":label,"command":command,"action":action,"captureBindings":bindings},
|
||||
"children":[]
|
||||
})
|
||||
}
|
||||
|
||||
fn command_descriptor(command: &str, schema: &str, bindings: &[&str], authority: &str) -> Value {
|
||||
json!({
|
||||
"schema":"gamecult.eve.command.v1",
|
||||
"command":command,
|
||||
"payloadSchema":schema,
|
||||
"captureBindings":bindings,
|
||||
"transport":"https-json",
|
||||
"authority":authority
|
||||
})
|
||||
}
|
||||
|
||||
/// A `captureBindings` entry the vendored browser lowering
|
||||
/// (`@gamecult/eve-browser-lowering`, `EveStateBindingDescriptor`) actually
|
||||
/// resolves, field-for-field the same shape its own test suite
|
||||
/// (`test/host-isolation.test.mjs`) builds for its own `composer.message`
|
||||
/// local-draft binding: `targetProp`, `pointerId`, `sourceId`, `schemaId`,
|
||||
/// `routeKind`, `bindingName`, `valueKind`, `accessMode`, `authority`.
|
||||
///
|
||||
/// Two fields are load-bearing. `bindingName` must equal `key`, since `key`
|
||||
/// is also the exact string Dungeon's own `captureBindings` array and
|
||||
/// `command_descriptor` advertise — `findAuthoredBindingValue` and
|
||||
/// `editableBindingContext` both match a binding by this field (falling back
|
||||
/// to `pointerId`, then the control's own node id, only when it is absent).
|
||||
/// `accessMode` must stay `"local-draft"`: `editableBindingContext`
|
||||
/// (`src/index.ts:2198`) defaults an absent `accessMode` to `"read"` whenever
|
||||
/// a binding is present at all, and a `"read"` control is disabled
|
||||
/// (`:2205`) — an editable field with no `accessMode` here would render
|
||||
/// disabled, not merely miscaptured. The remaining fields
|
||||
/// (`targetProp`, `pointerId`, `sourceId`, `schemaId`, `routeKind`,
|
||||
/// `valueKind`, `authority`) carry no runtime behavior in the current
|
||||
/// lowering (grep confirms `valueKind` is read nowhere), but are still worth
|
||||
/// stating correctly rather than leaving absent.
|
||||
///
|
||||
/// `value_kind` must be one of the lowering's own `valueKind` union
|
||||
/// (`"string" | "number" | "boolean" | "choice" | "string-list"`); Dungeon's
|
||||
/// own JSON-textarea fields (`targets`, `jurisdictions`, `lens_weights`) are,
|
||||
/// client-side, plain text controls like any other — there is no JSON
|
||||
/// `valueKind` — so callers pass `"string"` for those too, and the server
|
||||
/// side parses the captured text as JSON (`deserialize_json_capture` in
|
||||
/// `runtime.rs`).
|
||||
fn local_draft(key: &str, value_kind: &str) -> Value {
|
||||
json!({
|
||||
"targetProp":"value",
|
||||
"pointerId":format!("ghostlight.local.{key}"),
|
||||
"sourceId":"eve.browser.local",
|
||||
"schemaId":"gamecult.eve.local_draft.v1",
|
||||
"routeKind":"in-process",
|
||||
"bindingName":key,
|
||||
"valueKind":value_kind,
|
||||
"accessMode":"local-draft",
|
||||
"authority":"eve.browser"
|
||||
})
|
||||
}
|
||||
|
||||
fn short_principal(principal: &str) -> String {
|
||||
principal.chars().take(20).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn invocation(operation: &str, schema: &str, payload: Value) -> EveCommandInvocation {
|
||||
EveCommandInvocation {
|
||||
schema: "gamecult.eve.command_invocation.v1".into(),
|
||||
provider_id: PROVIDER_ID.into(),
|
||||
surface_id: SURFACE_ID.into(),
|
||||
operation: EveOperation {
|
||||
operation_id: operation.into(),
|
||||
schema_id: Some(schema.into()),
|
||||
idempotency_key: Some(uuid::Uuid::new_v4().to_string()),
|
||||
route_hint: EveRouteHint {
|
||||
source_version: Some(0),
|
||||
transport: Some("https-json".into()),
|
||||
},
|
||||
},
|
||||
payload,
|
||||
issued_at: Utc::now().to_rfc3339(),
|
||||
client_id: "fixture".into(),
|
||||
command_boundary: COMMAND_BOUNDARY.into(),
|
||||
receipt_schema: COMMAND_RESULT_SCHEMA.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anonymous_surface_advertises_only_authentication() {
|
||||
let surface = anonymous_surface();
|
||||
let commands = surface["commands"].as_array().unwrap();
|
||||
assert_eq!(commands.len(), 1);
|
||||
assert_eq!(commands[0]["command"], "heimdall.auth.begin");
|
||||
assert_eq!(surface["version"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_authenticated_surface_has_create_without_session_zero() {
|
||||
let surface = authenticated_surface("sha256:owner", None, None).unwrap();
|
||||
let encoded = serde_json::to_string(&surface).unwrap();
|
||||
assert!(encoded.contains("world.create"));
|
||||
assert!(encoded.contains("narrative_persona_label"));
|
||||
assert!(encoded.contains("operational_agent_label"));
|
||||
assert!(!encoded.contains("session_zero"));
|
||||
assert!(!encoded.contains("campaign"));
|
||||
assert_eq!(surface["version"], 0);
|
||||
|
||||
// The lens control's default is Dungeon's uniform policy, every stock
|
||||
// lens named, and it decodes as the weights the payload will carry.
|
||||
fn find<'a>(node: &'a Value, id: &str) -> Option<&'a Value> {
|
||||
if node["id"] == id {
|
||||
return Some(node);
|
||||
}
|
||||
node.as_object()?
|
||||
.values()
|
||||
.flat_map(|value| match value {
|
||||
Value::Array(items) => items.iter().collect::<Vec<_>>(),
|
||||
other => vec![other],
|
||||
})
|
||||
.find_map(|child| find(child, id))
|
||||
}
|
||||
let control = find(&surface, "world.create.lens_weights").expect("a lens weights control");
|
||||
let default = control["props"]["value"].as_str().expect("a default value");
|
||||
let decoded: ghostlight::LensWeights = serde_json::from_str(default).unwrap();
|
||||
assert_eq!(decoded, crate::runtime::uniform_lens_weights());
|
||||
assert_eq!(decoded.iter().count(), ghostlight::Lens::ALL.len());
|
||||
assert!(decoded.iter().all(|(_, weight)| weight == 1));
|
||||
}
|
||||
|
||||
/// `world.play`'s own operation id resolves to its schema through
|
||||
/// `operation_schema`, so an invocation whose payload matches it
|
||||
/// validates, and a payload that tries to claim authority is refused —
|
||||
/// the same claim this test once made for the now-deleted speak
|
||||
/// operation, PA.f146's own precedent (Cut 8b's schema existed here
|
||||
/// before Cut 9 published `world.play`'s own descriptor and button,
|
||||
/// below).
|
||||
#[test]
|
||||
fn payload_cannot_claim_authority() {
|
||||
assert_eq!(operation_schema("world.play"), Some("ghostlight.world_play.v0"));
|
||||
|
||||
let bound = invocation(
|
||||
"world.play",
|
||||
"ghostlight.world_play.v0",
|
||||
json!({"text":"I look around.", "answers": null}),
|
||||
);
|
||||
assert!(validate_invocation(&bound, "https-json").is_ok());
|
||||
|
||||
let forged = invocation(
|
||||
"world.play",
|
||||
"ghostlight.world_play.v0",
|
||||
json!({"text":"I look around.", "answers": null, "caller":"owner"}),
|
||||
);
|
||||
assert!(validate_invocation(&forged, "https-json").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invocation_metadata_rejects_legacy_authority_extensions() {
|
||||
let exact = invocation(
|
||||
"world.play",
|
||||
"ghostlight.world_play.v0",
|
||||
json!({"text":"I look around.", "answers": null}),
|
||||
);
|
||||
let mut outer = serde_json::to_value(&exact).unwrap();
|
||||
outer["callerId"] = json!("legacy-owner");
|
||||
assert!(serde_json::from_value::<EveCommandInvocation>(outer).is_err());
|
||||
|
||||
let mut route = serde_json::to_value(&exact).unwrap();
|
||||
route["operation"]["routeHint"]["caller"] = json!("legacy-owner");
|
||||
assert!(serde_json::from_value::<EveCommandInvocation>(route).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_operation_is_unknown() {
|
||||
assert!(operation_schema("session_zero.begin").is_none());
|
||||
assert!(operation_schema("world.assess").is_none());
|
||||
assert!(operation_schema("governance.time.propose").is_none());
|
||||
assert!(operation_schema("world.speak").is_none());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
{
|
||||
"schema": "ghostlight.eve_client_bridge_fixture.v1",
|
||||
"steps": [
|
||||
{
|
||||
"intent": {
|
||||
"clientId": "eve.bridge.test",
|
||||
"commandBoundary": "ghostlight.eve.commands",
|
||||
"issuedAt": "2026-09-22T23:30:03.348Z",
|
||||
"operation": {
|
||||
"idempotencyKey": "0af70fc4-d2bf-4f9b-9914-696a27580065",
|
||||
"operationId": "world.create",
|
||||
"routeHint": {
|
||||
"sourceVersion": 0,
|
||||
"transport": "https-json"
|
||||
},
|
||||
"schemaId": "ghostlight.world_create.v4"
|
||||
},
|
||||
"payload": {
|
||||
"bindings": {
|
||||
"brief": "A world captured for the committed Eve client bridge fixture.",
|
||||
"jurisdictions": "[]",
|
||||
"lens_weights": "{\"patina\":1,\"charter\":1,\"ledger\":1,\"hearth\":1,\"tangle\":1,\"veil\":1,\"ember\":1,\"numen\":1}",
|
||||
"subject_label": "The Fixture Operator",
|
||||
"targets": "{}",
|
||||
"title": "Bridge Fixture World"
|
||||
}
|
||||
},
|
||||
"providerId": "gamecult.ghostlight.dungeon",
|
||||
"receiptSchema": "gamecult.eve.command_result.v1",
|
||||
"schema": "gamecult.eve.command_invocation.v1",
|
||||
"surfaceId": "ghostlight.play"
|
||||
},
|
||||
"label": "world.create"
|
||||
},
|
||||
{
|
||||
"intent": {
|
||||
"clientId": "eve.bridge.test",
|
||||
"commandBoundary": "ghostlight.eve.commands",
|
||||
"issuedAt": "2026-09-22T23:30:05.143Z",
|
||||
"operation": {
|
||||
"idempotencyKey": "99503a87-9e15-45b7-8776-765a8dc4216b",
|
||||
"operationId": "world.approve",
|
||||
"routeHint": {
|
||||
"sourceVersion": 1,
|
||||
"transport": "https-json"
|
||||
},
|
||||
"schemaId": "ghostlight.world_approve.v0"
|
||||
},
|
||||
"payload": {},
|
||||
"providerId": "gamecult.ghostlight.dungeon",
|
||||
"receiptSchema": "gamecult.eve.command_result.v1",
|
||||
"schema": "gamecult.eve.command_invocation.v1",
|
||||
"surfaceId": "ghostlight.play"
|
||||
},
|
||||
"label": "world.approve"
|
||||
},
|
||||
{
|
||||
"intent": {
|
||||
"clientId": "eve.bridge.test",
|
||||
"commandBoundary": "ghostlight.eve.commands",
|
||||
"issuedAt": "2026-09-22T23:30:07.195Z",
|
||||
"operation": {
|
||||
"idempotencyKey": "1d6a441e-f173-41af-a798-a9123039d5e0",
|
||||
"operationId": "world.seed",
|
||||
"routeHint": {
|
||||
"sourceVersion": 2,
|
||||
"transport": "https-json"
|
||||
},
|
||||
"schemaId": "ghostlight.world_seed.v1"
|
||||
},
|
||||
"payload": {
|
||||
"bindings": {}
|
||||
},
|
||||
"providerId": "gamecult.ghostlight.dungeon",
|
||||
"receiptSchema": "gamecult.eve.command_result.v1",
|
||||
"schema": "gamecult.eve.command_invocation.v1",
|
||||
"surfaceId": "ghostlight.play"
|
||||
},
|
||||
"label": "world.seed"
|
||||
},
|
||||
{
|
||||
"intent": {
|
||||
"clientId": "eve.bridge.test",
|
||||
"commandBoundary": "ghostlight.eve.commands",
|
||||
"issuedAt": "2026-09-22T23:30:09.010Z",
|
||||
"operation": {
|
||||
"idempotencyKey": "20d01b36-cdfa-4e59-b5f3-31be54d94bc6",
|
||||
"operationId": "world.activate",
|
||||
"routeHint": {
|
||||
"sourceVersion": 2,
|
||||
"transport": "https-json"
|
||||
},
|
||||
"schemaId": "ghostlight.world_activate.v0"
|
||||
},
|
||||
"payload": {},
|
||||
"providerId": "gamecult.ghostlight.dungeon",
|
||||
"receiptSchema": "gamecult.eve.command_result.v1",
|
||||
"schema": "gamecult.eve.command_invocation.v1",
|
||||
"surfaceId": "ghostlight.play"
|
||||
},
|
||||
"label": "world.activate"
|
||||
},
|
||||
{
|
||||
"intent": {
|
||||
"clientId": "eve.bridge.test",
|
||||
"commandBoundary": "ghostlight.eve.commands",
|
||||
"issuedAt": "2026-09-22T23:30:11.040Z",
|
||||
"operation": {
|
||||
"idempotencyKey": "2301df6e-397b-4d5b-afa3-ef965e57b49a",
|
||||
"operationId": "world.play",
|
||||
"routeHint": {
|
||||
"sourceVersion": 3,
|
||||
"transport": "https-json"
|
||||
},
|
||||
"schemaId": "ghostlight.world_play.v0"
|
||||
},
|
||||
"payload": {
|
||||
"bindings": {
|
||||
"text": "The new owner looks around."
|
||||
}
|
||||
},
|
||||
"providerId": "gamecult.ghostlight.dungeon",
|
||||
"receiptSchema": "gamecult.eve.command_result.v1",
|
||||
"schema": "gamecult.eve.command_invocation.v1",
|
||||
"surfaceId": "ghostlight.play"
|
||||
},
|
||||
"label": "world.play"
|
||||
}
|
||||
],
|
||||
"vendorEveSubmoduleRevision": "672c0c1e9fc828b63752345385727b06c50491d0"
|
||||
}
|
||||
|
|
@ -15,10 +15,7 @@ use cultnet_rs::{
|
|||
CultNetRudpSocketTransportOptions,
|
||||
};
|
||||
use hmac::{Hmac, Mac};
|
||||
use jsonwebtoken::{
|
||||
Algorithm, DecodingKey, Validation, decode, decode_header,
|
||||
jwk::{Jwk, JwkSet},
|
||||
};
|
||||
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header, jwk::JwkSet};
|
||||
use rand::RngCore;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
|
|
@ -26,7 +23,6 @@ use sha2::{Digest, Sha256};
|
|||
use std::{
|
||||
net::{SocketAddr, UdpSocket},
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex as StdMutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
|
|
@ -34,237 +30,37 @@ const APP_SLUG: &str = "ghostlight";
|
|||
const PRIVATE_SERVICE: &str = "heimdall.private.commands";
|
||||
const PRIVATE_ENVELOPE_SCHEMA: &str = "heimdall.private_command_envelope.v1";
|
||||
|
||||
/// Heimdall answered a private command with status denied. Distinct from a
|
||||
/// transport failure so the refresh loop never reads a message string.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Heimdall denied the private command: {diagnostics}")]
|
||||
pub(crate) struct HeimdallDenied {
|
||||
pub(crate) diagnostics: String,
|
||||
}
|
||||
|
||||
/// Heimdall's signing keys could not be fetched, so a receipt could not be
|
||||
/// judged either way. Distinct from a receipt that positively fails
|
||||
/// verification: the refresh loop keeps the receipt for this and revokes for
|
||||
/// that. It carries an error class and never the fetch error itself, whose
|
||||
/// text names the key-set URL: an error never echoes an input value.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Heimdall signing keys unavailable: the key-set fetch {class}")]
|
||||
pub(crate) struct VerificationUnavailable {
|
||||
class: &'static str,
|
||||
}
|
||||
|
||||
impl VerificationUnavailable {
|
||||
fn of_fetch(error: &reqwest::Error) -> Self {
|
||||
let class = if error.is_timeout() {
|
||||
"timed out"
|
||||
} else if error.is_connect() {
|
||||
"could not connect"
|
||||
} else if error.is_status() {
|
||||
"returned an error status"
|
||||
} else if error.is_decode() {
|
||||
"returned an unreadable key set"
|
||||
} else {
|
||||
"failed"
|
||||
};
|
||||
Self { class }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new(class: &'static str) -> Self {
|
||||
Self { class }
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a fetched signing-key set is trusted before it is fetched again.
|
||||
const JWKS_TTL: Duration = Duration::from_secs(300);
|
||||
|
||||
/// The last fetched signing-key set and when it was fetched.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct JwksCache {
|
||||
fetched: Option<(Instant, JwkSet)>,
|
||||
}
|
||||
|
||||
impl JwksCache {
|
||||
/// The key published under `kid`, if the cached set is still fresh and
|
||||
/// holds it. A miss on a fresh set still refetches, so a rotated key is
|
||||
/// found.
|
||||
pub(crate) fn key(&self, kid: &str, now: Instant) -> Option<Jwk> {
|
||||
let (fetched_at, set) = self.fetched.as_ref()?;
|
||||
if now.saturating_duration_since(*fetched_at) >= JWKS_TTL {
|
||||
return None;
|
||||
}
|
||||
set.find(kid).cloned()
|
||||
}
|
||||
|
||||
pub(crate) fn store(&mut self, set: JwkSet, now: Instant) {
|
||||
self.fetched = Some((now, set));
|
||||
}
|
||||
}
|
||||
|
||||
/// The two Heimdall calls the refresh loop makes, as a port so a scripted
|
||||
/// Heimdall can stand in for the real one.
|
||||
#[async_trait::async_trait]
|
||||
pub(crate) trait SessionRefresher {
|
||||
async fn refresh(
|
||||
&self,
|
||||
refresh_token: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthCompletionReceipt>;
|
||||
|
||||
async fn verify_refresh(
|
||||
&self,
|
||||
completion: AuthCompletionReceipt,
|
||||
) -> anyhow::Result<VerifiedSessionRefresh>;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl SessionRefresher for HeimdallClient {
|
||||
async fn refresh(
|
||||
&self,
|
||||
refresh_token: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthCompletionReceipt> {
|
||||
HeimdallClient::refresh(self, refresh_token, idempotency_key).await
|
||||
}
|
||||
|
||||
async fn verify_refresh(
|
||||
&self,
|
||||
completion: AuthCompletionReceipt,
|
||||
) -> anyhow::Result<VerifiedSessionRefresh> {
|
||||
HeimdallClient::verify_refresh(self, completion).await
|
||||
}
|
||||
}
|
||||
|
||||
/// A sign-in provider Heimdall may be asked to authenticate with. The Dungeon
|
||||
/// owns which of them it offers; Heimdall's app profile owns which it accepts.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AuthProvider {
|
||||
Google,
|
||||
Discord,
|
||||
Twitch,
|
||||
}
|
||||
|
||||
impl AuthProvider {
|
||||
pub(crate) fn parse(name: &str) -> Option<Self> {
|
||||
match name {
|
||||
"google" => Some(Self::Google),
|
||||
"discord" => Some(Self::Discord),
|
||||
"twitch" => Some(Self::Twitch),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Google => "google",
|
||||
Self::Discord => "discord",
|
||||
Self::Twitch => "twitch",
|
||||
}
|
||||
}
|
||||
|
||||
/// The offered set from `GHOSTLIGHT_AUTH_PROVIDERS`, a comma list. An
|
||||
/// unnamed provider is a startup error, not a silent drop.
|
||||
fn set_from(value: &str) -> anyhow::Result<Vec<Self>> {
|
||||
let mut set = Vec::new();
|
||||
for name in value.split(',').map(str::trim).filter(|name| !name.is_empty()) {
|
||||
let provider = Self::parse(name)
|
||||
.with_context(|| format!("GHOSTLIGHT_AUTH_PROVIDERS names an unknown provider {name:?}"))?;
|
||||
if !set.contains(&provider) {
|
||||
set.push(provider);
|
||||
}
|
||||
}
|
||||
anyhow::ensure!(!set.is_empty(), "GHOSTLIGHT_AUTH_PROVIDERS names no provider");
|
||||
Ok(set)
|
||||
}
|
||||
}
|
||||
|
||||
/// The sign-in half of Heimdall the HTTP handlers use, as a port so a scripted
|
||||
/// Heimdall can stand in for the real one. The refresh loop's half is the
|
||||
/// supertrait.
|
||||
#[async_trait::async_trait]
|
||||
pub(crate) trait HeimdallPort: SessionRefresher + Send + Sync {
|
||||
/// The provider named, if the Dungeon offers it.
|
||||
fn offered(&self, name: &str) -> Option<AuthProvider>;
|
||||
|
||||
async fn begin(
|
||||
&self,
|
||||
provider: AuthProvider,
|
||||
grant: bool,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthBeginReceipt>;
|
||||
|
||||
async fn complete(
|
||||
&self,
|
||||
handle: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthCompletionReceipt>;
|
||||
|
||||
async fn verify_completion(
|
||||
&self,
|
||||
completion: AuthCompletionReceipt,
|
||||
) -> anyhow::Result<VerifiedSessionAdmission>;
|
||||
|
||||
async fn logout(
|
||||
&self,
|
||||
refresh_token: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthLogoutReceipt>;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl HeimdallPort for HeimdallClient {
|
||||
fn offered(&self, name: &str) -> Option<AuthProvider> {
|
||||
AuthProvider::parse(name).filter(|provider| self.providers.contains(provider))
|
||||
}
|
||||
|
||||
async fn begin(
|
||||
&self,
|
||||
provider: AuthProvider,
|
||||
grant: bool,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthBeginReceipt> {
|
||||
HeimdallClient::begin(self, provider, grant, idempotency_key).await
|
||||
}
|
||||
|
||||
async fn complete(
|
||||
&self,
|
||||
handle: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthCompletionReceipt> {
|
||||
HeimdallClient::complete(self, handle, idempotency_key).await
|
||||
}
|
||||
|
||||
async fn verify_completion(
|
||||
&self,
|
||||
completion: AuthCompletionReceipt,
|
||||
) -> anyhow::Result<VerifiedSessionAdmission> {
|
||||
HeimdallClient::verify_completion(self, completion).await
|
||||
}
|
||||
|
||||
async fn logout(
|
||||
&self,
|
||||
refresh_token: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthLogoutReceipt> {
|
||||
HeimdallClient::logout(self, refresh_token, idempotency_key).await
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct HeimdallClient {
|
||||
http: Client,
|
||||
issuer: String,
|
||||
public_app_url: String,
|
||||
providers: Vec<AuthProvider>,
|
||||
discord_guild_id: String,
|
||||
discord_role_id: String,
|
||||
boundary_locator: HeimdallBoundaryLocator,
|
||||
runtime_id: String,
|
||||
shared_secret: String,
|
||||
jwks: Arc<StdMutex<JwksCache>>,
|
||||
}
|
||||
|
||||
/// Idunn's projection of a managed Heimdall dependency, when Heimdall is a
|
||||
/// v2-managed target (it is not, as of this cut: every v2 deploy of it has
|
||||
/// failed and it still runs as the legacy `heimdall.service`, so
|
||||
/// `runtime.rs` always passes `None` here). Not an Idunn dependency in
|
||||
/// `deployment/idunn/recipe.toml` right now, but the type stays owned here
|
||||
/// so `require_expected_heimdall_boundary` below can resume checking a
|
||||
/// discovered boundary against it the moment Heimdall returns as a managed
|
||||
/// dependency, without re-deriving this shape from scratch.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct HeimdallDependencyBinding {
|
||||
pub(crate) provider_id: String,
|
||||
pub(crate) endpoint: SocketAddr,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum HeimdallBoundaryLocator {
|
||||
Odin {
|
||||
endpoint: SocketAddr,
|
||||
expected: Option<HeimdallDependencyBinding>,
|
||||
},
|
||||
#[cfg(test)]
|
||||
Fixed(ResolvedHeimdallBoundary),
|
||||
|
|
@ -346,11 +142,7 @@ struct BeginCommand<'a> {
|
|||
provider: &'a str,
|
||||
mode: &'a str,
|
||||
return_to: &'a str,
|
||||
/// `"invite"` when the browser presented an invite the catalog holds live:
|
||||
/// it lets Heimdall mint an auth account for a first-time identity. The
|
||||
/// Dungeon's catalog, not Heimdall, decides who is admitted.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
first_login_grant: Option<&'static str>,
|
||||
entitlement_policy: DiscordRolePolicy<'a>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
|
@ -358,6 +150,7 @@ struct BeginCommand<'a> {
|
|||
struct RefreshCommand<'a> {
|
||||
schema: &'static str,
|
||||
refresh_token: &'a str,
|
||||
entitlement_policy: DiscordRolePolicy<'a>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
|
@ -367,6 +160,14 @@ struct LogoutCommand<'a> {
|
|||
refresh_token: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DiscordRolePolicy<'a> {
|
||||
kind: &'a str,
|
||||
guild_id: &'a str,
|
||||
allowed_role_ids: [&'a str; 1],
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AuthBeginReceipt {
|
||||
|
|
@ -383,7 +184,7 @@ pub struct AuthNavigation {
|
|||
pub allowed_origins: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AuthCompletionReceipt {
|
||||
pub status: String,
|
||||
|
|
@ -398,12 +199,12 @@ pub struct AuthCompletionReceipt {
|
|||
pub shared_capabilities: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct AccountSummary {
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HeimdallSession {
|
||||
pub account_id: String,
|
||||
|
|
@ -413,7 +214,7 @@ pub struct HeimdallSession {
|
|||
pub expires_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RefreshSummary {
|
||||
pub expires_at: String,
|
||||
|
|
@ -524,30 +325,12 @@ impl VerifiedSessionAdmission {
|
|||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl VerifiedSessionRefresh {
|
||||
pub(crate) fn fixture(
|
||||
account_id: impl Into<String>,
|
||||
heimdall_session_id: impl Into<String>,
|
||||
access_revision: u64,
|
||||
access_expires_at: DateTime<Utc>,
|
||||
refresh_expires_at: DateTime<Utc>,
|
||||
refresh_claim: impl Into<String>,
|
||||
) -> Self {
|
||||
Self(VerifiedSessionMaterial {
|
||||
account_id: account_id.into(),
|
||||
heimdall_session_id: heimdall_session_id.into(),
|
||||
access_revision,
|
||||
capabilities: vec!["app_access".into()],
|
||||
access_expires_at,
|
||||
refresh_expires_at,
|
||||
refresh_claim: refresh_claim.into(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl HeimdallClient {
|
||||
pub fn from_env(runtime_id: &str, odin_endpoint: SocketAddr) -> anyhow::Result<Self> {
|
||||
pub fn from_env(
|
||||
runtime_id: &str,
|
||||
odin_endpoint: SocketAddr,
|
||||
expected: Option<HeimdallDependencyBinding>,
|
||||
) -> anyhow::Result<Self> {
|
||||
if runtime_id.is_empty() || runtime_id.trim() != runtime_id {
|
||||
bail!("Ghostlight runtime identity is not canonical");
|
||||
}
|
||||
|
|
@ -561,9 +344,6 @@ impl HeimdallClient {
|
|||
if shared_secret.is_empty() {
|
||||
bail!("Ghostlight's Heimdall app secret is empty");
|
||||
}
|
||||
let providers = AuthProvider::set_from(
|
||||
&std::env::var("GHOSTLIGHT_AUTH_PROVIDERS").unwrap_or_else(|_| "discord".into()),
|
||||
)?;
|
||||
Ok(Self {
|
||||
http: Client::builder().timeout(Duration::from_secs(10)).build()?,
|
||||
issuer: std::env::var("GHOSTLIGHT_HEIMDALL_BASE_URL")
|
||||
|
|
@ -572,13 +352,14 @@ impl HeimdallClient {
|
|||
.into(),
|
||||
public_app_url: std::env::var("GHOSTLIGHT_PUBLIC_APP_URL")
|
||||
.unwrap_or_else(|_| "https://yggdrasil.gamecult.org/ghostlight/".into()),
|
||||
providers,
|
||||
discord_guild_id: required_env("GHOSTLIGHT_DISCORD_GUILD_ID")?,
|
||||
discord_role_id: required_env("GHOSTLIGHT_DISCORD_ROLE_ID")?,
|
||||
boundary_locator: HeimdallBoundaryLocator::Odin {
|
||||
endpoint: odin_endpoint,
|
||||
expected,
|
||||
},
|
||||
runtime_id: runtime_id.into(),
|
||||
shared_secret,
|
||||
jwks: Arc::default(),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -588,7 +369,8 @@ impl HeimdallClient {
|
|||
http: Client::new(),
|
||||
issuer: "https://heimdall.invalid".into(),
|
||||
public_app_url: "https://ghostlight.invalid/".into(),
|
||||
providers: vec![AuthProvider::Google, AuthProvider::Discord, AuthProvider::Twitch],
|
||||
discord_guild_id: "guild-kltst".into(),
|
||||
discord_role_id: "role-kltst".into(),
|
||||
boundary_locator: HeimdallBoundaryLocator::Fixed(ResolvedHeimdallBoundary {
|
||||
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||
daemon_id: "yggdrasil-heimdall".into(),
|
||||
|
|
@ -601,33 +383,20 @@ impl HeimdallClient {
|
|||
}),
|
||||
runtime_id: "ghostlight-test-runtime".into(),
|
||||
shared_secret: "fixture-secret".into(),
|
||||
jwks: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The same client against another issuer, for tests that stand up their own.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
|
||||
self.issuer = issuer.into();
|
||||
self
|
||||
}
|
||||
|
||||
fn begin_command(&self, provider: AuthProvider, grant: bool) -> BeginCommand<'_> {
|
||||
BeginCommand {
|
||||
provider: provider.as_str(),
|
||||
pub async fn begin(&self, idempotency_key: &str) -> anyhow::Result<AuthBeginReceipt> {
|
||||
let payload = BeginCommand {
|
||||
provider: "discord",
|
||||
mode: "sign_in",
|
||||
return_to: &self.public_app_url,
|
||||
first_login_grant: grant.then_some("invite"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn begin(
|
||||
&self,
|
||||
provider: AuthProvider,
|
||||
grant: bool,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthBeginReceipt> {
|
||||
let payload = self.begin_command(provider, grant);
|
||||
entitlement_policy: DiscordRolePolicy {
|
||||
kind: "discord_role_access",
|
||||
guild_id: &self.discord_guild_id,
|
||||
allowed_role_ids: [&self.discord_role_id],
|
||||
},
|
||||
};
|
||||
self.invoke(
|
||||
"heimdall.auth.begin",
|
||||
"heimdall.auth_begin_command.v1",
|
||||
|
|
@ -661,6 +430,11 @@ impl HeimdallClient {
|
|||
let payload = RefreshCommand {
|
||||
schema: "heimdall.auth_refresh_command.v1",
|
||||
refresh_token,
|
||||
entitlement_policy: DiscordRolePolicy {
|
||||
kind: "discord_role_access",
|
||||
guild_id: &self.discord_guild_id,
|
||||
allowed_role_ids: [&self.discord_role_id],
|
||||
},
|
||||
};
|
||||
self.invoke(
|
||||
"heimdall.auth.refresh",
|
||||
|
|
@ -727,43 +501,28 @@ impl HeimdallClient {
|
|||
)?))
|
||||
}
|
||||
|
||||
async fn fetch_jwks(&self) -> Result<JwkSet, reqwest::Error> {
|
||||
self.http
|
||||
.get(format!("{}/.well-known/jwks.json", self.issuer))
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.json()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn verify_access(&self, token: &str) -> anyhow::Result<AccessClaims> {
|
||||
let header = decode_header(token)?;
|
||||
if header.alg != Algorithm::EdDSA {
|
||||
bail!("Heimdall used an unsupported signing algorithm");
|
||||
}
|
||||
let kid = header.kid.context("Heimdall token omitted kid")?;
|
||||
let cached = self.jwks.lock().expect("jwks cache").key(&kid, Instant::now());
|
||||
let jwk = match cached {
|
||||
Some(jwk) => jwk,
|
||||
None => {
|
||||
let set = self
|
||||
.fetch_jwks()
|
||||
.await
|
||||
.map_err(|error| VerificationUnavailable::of_fetch(&error))?;
|
||||
let jwk = set.find(&kid).cloned();
|
||||
self.jwks
|
||||
.lock()
|
||||
.expect("jwks cache")
|
||||
.store(set, Instant::now());
|
||||
jwk.context("Heimdall signing key was not published")?
|
||||
}
|
||||
};
|
||||
let jwks: JwkSet = self
|
||||
.http
|
||||
.get(format!("{}/.well-known/jwks.json", self.issuer))
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.json()
|
||||
.await?;
|
||||
let jwk = jwks
|
||||
.find(&kid)
|
||||
.context("Heimdall signing key was not published")?;
|
||||
let mut validation = Validation::new(Algorithm::EdDSA);
|
||||
validation.set_audience(&[APP_SLUG]);
|
||||
validation.set_issuer(&[self.issuer.as_str()]);
|
||||
let claims =
|
||||
decode::<AccessClaims>(token, &DecodingKey::from_jwk(&jwk)?, &validation)?.claims;
|
||||
decode::<AccessClaims>(token, &DecodingKey::from_jwk(jwk)?, &validation)?.claims;
|
||||
if claims.typ != "heimdall_access"
|
||||
|| claims.aud != APP_SLUG
|
||||
|| claims.iss != self.issuer
|
||||
|
|
@ -821,7 +580,12 @@ impl HeimdallClient {
|
|||
else {
|
||||
bail!("Heimdall returned a non-operation response");
|
||||
};
|
||||
refuse_denied(&status, &diagnostics)?;
|
||||
if status == "denied" {
|
||||
bail!(
|
||||
"Heimdall denied the private command: {}",
|
||||
diagnostics.join("; ")
|
||||
);
|
||||
}
|
||||
if payload_schema != PRIVATE_ENVELOPE_SCHEMA || payload_encoding != "messagepack-base64" {
|
||||
bail!("Heimdall returned the wrong private response contract");
|
||||
}
|
||||
|
|
@ -831,18 +595,6 @@ impl HeimdallClient {
|
|||
}
|
||||
}
|
||||
|
||||
/// A response with status denied is Heimdall's answer, not a transport
|
||||
/// failure: it becomes the typed `HeimdallDenied`.
|
||||
fn refuse_denied(status: &str, diagnostics: &[String]) -> anyhow::Result<()> {
|
||||
if status == "denied" {
|
||||
return Err(HeimdallDenied {
|
||||
diagnostics: diagnostics.join("; "),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_private_response_binding(
|
||||
envelope: &PrivateEnvelope,
|
||||
operation: &str,
|
||||
|
|
@ -1003,7 +755,13 @@ impl HeimdallBoundaryLocator {
|
|||
operation: &str,
|
||||
) -> anyhow::Result<ResolvedHeimdallBoundary> {
|
||||
let boundary = match self {
|
||||
Self::Odin { endpoint } => discover_heimdall_boundary(*endpoint, runtime_id)?,
|
||||
Self::Odin { endpoint, expected } => {
|
||||
let boundary = discover_heimdall_boundary(*endpoint, runtime_id)?;
|
||||
if let Some(expected) = expected {
|
||||
require_expected_heimdall_boundary(&boundary, expected)?;
|
||||
}
|
||||
boundary
|
||||
}
|
||||
#[cfg(test)]
|
||||
Self::Fixed(boundary) => boundary.clone(),
|
||||
};
|
||||
|
|
@ -1018,6 +776,16 @@ impl HeimdallBoundaryLocator {
|
|||
}
|
||||
}
|
||||
|
||||
fn require_expected_heimdall_boundary(
|
||||
boundary: &ResolvedHeimdallBoundary,
|
||||
expected: &HeimdallDependencyBinding,
|
||||
) -> anyhow::Result<()> {
|
||||
if boundary.daemon_id != expected.provider_id || boundary.endpoint != expected.endpoint {
|
||||
bail!("discovered Heimdall boundary differs from Expected");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn discover_heimdall_boundary(
|
||||
odin_endpoint: SocketAddr,
|
||||
runtime_id: &str,
|
||||
|
|
@ -1238,190 +1006,19 @@ impl PrivateEnvelope {
|
|||
}
|
||||
}
|
||||
|
||||
/// A local stand-in for Heimdall's issuer: it serves the key set (or a 5xx)
|
||||
/// on a loopback port and counts the requests it receives. The key is the
|
||||
/// RFC 8037 appendix A.1 Ed25519 test key.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_issuer {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpListener,
|
||||
};
|
||||
|
||||
pub(crate) const KID: &str = "k1";
|
||||
const PRIVATE_D: &str = "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A";
|
||||
const PUBLIC_X: &str = "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo";
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum Answer {
|
||||
KeySet,
|
||||
ServerError,
|
||||
}
|
||||
|
||||
pub(crate) struct Issuer {
|
||||
pub(crate) url: String,
|
||||
fetches: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl Issuer {
|
||||
pub(crate) async fn start(answer: Answer) -> Self {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let fetches = Arc::new(AtomicUsize::new(0));
|
||||
let counted = fetches.clone();
|
||||
let key_set = serde_json::json!({
|
||||
"keys": [{"kty": "OKP", "crv": "Ed25519", "kid": KID, "x": PUBLIC_X}]
|
||||
})
|
||||
.to_string();
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut stream, _)) = listener.accept().await {
|
||||
let mut request = Vec::new();
|
||||
let mut chunk = [0_u8; 1024];
|
||||
while !request.windows(4).any(|window| window == b"\r\n\r\n") {
|
||||
match stream.read(&mut chunk).await {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(read) => request.extend_from_slice(&chunk[..read]),
|
||||
}
|
||||
}
|
||||
counted.fetch_add(1, Ordering::SeqCst);
|
||||
let (status, body) = match answer {
|
||||
Answer::KeySet => ("200 OK", key_set.as_str()),
|
||||
Answer::ServerError => ("503 Service Unavailable", ""),
|
||||
};
|
||||
let response = format!(
|
||||
"HTTP/1.1 {status}\r\ncontent-type: application/json\r\n\
|
||||
content-length: {}\r\nconnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
let _ = stream.write_all(response.as_bytes()).await;
|
||||
let _ = stream.shutdown().await;
|
||||
}
|
||||
});
|
||||
Self { url, fetches }
|
||||
}
|
||||
|
||||
pub(crate) fn fetches(&self) -> usize {
|
||||
self.fetches.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// The URL of a loopback port nothing listens on.
|
||||
pub(crate) fn closed_url() -> String {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
format!("http://{}", listener.local_addr().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
/// An access token Heimdall's key signs for `issuer`, with the claims
|
||||
/// `verify_access` demands.
|
||||
pub(crate) fn signed_token(issuer: &str) -> String {
|
||||
let mut der = vec![
|
||||
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22,
|
||||
0x04, 0x20,
|
||||
];
|
||||
der.extend(URL_SAFE_NO_PAD.decode(PRIVATE_D).unwrap());
|
||||
let pem = format!(
|
||||
"-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----\n",
|
||||
STANDARD.encode(der)
|
||||
);
|
||||
let mut header = jsonwebtoken::Header::new(Algorithm::EdDSA);
|
||||
header.kid = Some(KID.into());
|
||||
let claims = serde_json::json!({
|
||||
"iss": issuer, "aud": APP_SLUG, "sub": "account-1", "sid": "session-1",
|
||||
"exp": Utc::now().timestamp() + 300, "typ": "heimdall_access",
|
||||
"account_id": "account-1", "access_revision": 1,
|
||||
"capabilities": ["app_access"], "app": {"slug": APP_SLUG},
|
||||
});
|
||||
jsonwebtoken::encode(
|
||||
&header,
|
||||
&claims,
|
||||
&jsonwebtoken::EncodingKey::from_ed_pem(pem.as_bytes()).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
fn required_env(name: &str) -> anyhow::Result<String> {
|
||||
let value = std::env::var(name).with_context(|| format!("{name} is required"))?;
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
bail!("{name} must not be empty");
|
||||
}
|
||||
Ok(value.to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use super::test_issuer::{Answer, Issuer, signed_token};
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_key_fetch_failure_is_typed_unavailable_and_names_no_url() {
|
||||
let closed = Issuer::closed_url();
|
||||
let failing = Issuer::start(Answer::ServerError).await;
|
||||
for (base, class) in [
|
||||
(closed, "could not connect"),
|
||||
(failing.url.clone(), "returned an error status"),
|
||||
] {
|
||||
let canary = format!("{base}/canary-q7x1");
|
||||
let client = HeimdallClient::fixture().with_issuer(canary.clone());
|
||||
let error = client
|
||||
.verify_access(&signed_token(&canary))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.downcast_ref::<VerificationUnavailable>().is_some(), "{error:#}");
|
||||
for text in [format!("{error}"), format!("{error:#}"), format!("{error:?}")] {
|
||||
assert!(text.contains("signing keys unavailable"), "{text}");
|
||||
assert!(text.contains(class), "{text}");
|
||||
for leaked in [canary.as_str(), base.as_str(), "canary-q7x1", "127.0.0.1"] {
|
||||
assert!(!text.contains(leaked), "{leaked} leaked into {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_key_set_is_fetched_once_within_its_ttl_and_again_after_it() {
|
||||
let issuer = Issuer::start(Answer::KeySet).await;
|
||||
let client = HeimdallClient::fixture().with_issuer(issuer.url.clone());
|
||||
let token = signed_token(&issuer.url);
|
||||
client.verify_access(&token).await.unwrap();
|
||||
assert_eq!(issuer.fetches(), 1);
|
||||
client.verify_access(&token).await.unwrap();
|
||||
assert_eq!(issuer.fetches(), 1, "a second verify within the ttl reads the cache");
|
||||
let age = |seconds: u64| {
|
||||
client.jwks.lock().unwrap().fetched.as_mut().unwrap().0 =
|
||||
Instant::now().checked_sub(Duration::from_secs(seconds)).unwrap();
|
||||
};
|
||||
age(299);
|
||||
client.verify_access(&token).await.unwrap();
|
||||
assert_eq!(issuer.fetches(), 1, "299 s old is still fresh");
|
||||
age(301);
|
||||
client.verify_access(&token).await.unwrap();
|
||||
assert_eq!(issuer.fetches(), 2, "301 s old is fetched again");
|
||||
client.verify_access(&token).await.unwrap();
|
||||
assert_eq!(issuer.fetches(), 2, "and the new fetch is cached");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_token_signed_under_any_other_algorithm_is_refused_before_any_key_fetch() {
|
||||
let issuer = Issuer::start(Answer::KeySet).await;
|
||||
let client = HeimdallClient::fixture().with_issuer(issuer.url.clone());
|
||||
let part = |text: &str| URL_SAFE_NO_PAD.encode(text);
|
||||
for alg in [
|
||||
"none", "HS256", "HS384", "HS512", "RS256", "RS384", "PS256", "ES256", "ES384",
|
||||
] {
|
||||
let token = format!(
|
||||
"{}.{}.{}",
|
||||
part(&format!(r#"{{"alg":"{alg}","typ":"JWT","kid":"k1"}}"#)),
|
||||
part(r#"{"sub":"account-1"}"#),
|
||||
URL_SAFE_NO_PAD.encode([0xAB_u8; 32]),
|
||||
);
|
||||
let error = client.verify_access(&token).await.unwrap_err();
|
||||
assert!(error.downcast_ref::<VerificationUnavailable>().is_none(), "{alg}");
|
||||
if alg != "none" {
|
||||
assert!(
|
||||
error.to_string().contains("unsupported signing algorithm"),
|
||||
"{alg}: {error:#}"
|
||||
);
|
||||
}
|
||||
assert_eq!(issuer.fetches(), 0, "{alg} reached the key fetch");
|
||||
}
|
||||
}
|
||||
|
||||
fn boundary(endpoint: &str) -> HeimdallCommandBoundaryRecord {
|
||||
HeimdallCommandBoundaryRecord {
|
||||
schema: "heimdall.command_boundary.v1".into(),
|
||||
|
|
@ -1443,34 +1040,6 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
fn key_set(kid: &str) -> JwkSet {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"keys": [{"kty": "OKP", "crv": "Ed25519", "kid": kid,
|
||||
"x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}]
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cached_key_set_serves_until_its_ttl_and_misses_an_unpublished_kid() {
|
||||
let start = Instant::now();
|
||||
let mut cache = JwksCache::default();
|
||||
assert!(cache.key("k1", start).is_none(), "an empty cache has no key");
|
||||
cache.store(key_set("k1"), start);
|
||||
assert!(cache.key("k1", start + Duration::from_secs(299)).is_some());
|
||||
assert!(cache.key("k2", start).is_none(), "a rotated-in kid refetches");
|
||||
assert!(cache.key("k1", start + JWKS_TTL).is_none(), "stale at the ttl");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_denied_status_is_the_typed_denial_and_any_other_status_passes() {
|
||||
let diagnostics = vec!["Idempotency key was reused".to_owned()];
|
||||
let denial = refuse_denied("denied", &diagnostics).unwrap_err();
|
||||
assert!(denial.downcast_ref::<HeimdallDenied>().is_some());
|
||||
assert!(denial.to_string().contains("Idempotency key was reused"));
|
||||
refuse_denied("accepted", &diagnostics).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_responses_are_bound_to_the_exact_app_and_request() {
|
||||
let secret = "fixture-shared-secret";
|
||||
|
|
@ -1574,6 +1143,17 @@ mod tests {
|
|||
assert_eq!(resolved.endpoint, "127.0.0.1:4101".parse().unwrap());
|
||||
assert_eq!(resolved.daemon_id, "yggdrasil-heimdall");
|
||||
assert_eq!(resolved.operations, vec!["heimdall.auth.begin"]);
|
||||
let expected = HeimdallDependencyBinding {
|
||||
provider_id: "yggdrasil-heimdall".into(),
|
||||
endpoint: "127.0.0.1:4101".parse().unwrap(),
|
||||
};
|
||||
require_expected_heimdall_boundary(&resolved, &expected)
|
||||
.expect("exact Expected Heimdall should match discovery");
|
||||
let substitute = HeimdallDependencyBinding {
|
||||
provider_id: "another-heimdall".into(),
|
||||
endpoint: expected.endpoint,
|
||||
};
|
||||
assert!(require_expected_heimdall_boundary(&resolved, &substitute).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1729,67 +1309,3 @@ mod tests {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod provider_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn no_begin_or_refresh_carries_a_role_policy_and_the_grant_rides_only_when_asked() {
|
||||
let client = HeimdallClient::fixture();
|
||||
for (provider, name) in [
|
||||
(AuthProvider::Google, "google"),
|
||||
(AuthProvider::Discord, "discord"),
|
||||
(AuthProvider::Twitch, "twitch"),
|
||||
] {
|
||||
let plain = serde_json::to_value(client.begin_command(provider, false)).unwrap();
|
||||
assert_eq!(
|
||||
plain,
|
||||
serde_json::json!({"provider": name, "mode": "sign_in", "returnTo": "https://ghostlight.invalid/"}),
|
||||
"no policy, no grant key"
|
||||
);
|
||||
let granted = serde_json::to_value(client.begin_command(provider, true)).unwrap();
|
||||
assert_eq!(
|
||||
granted,
|
||||
serde_json::json!({
|
||||
"provider": name,
|
||||
"mode": "sign_in",
|
||||
"returnTo": "https://ghostlight.invalid/",
|
||||
"firstLoginGrant": "invite",
|
||||
})
|
||||
);
|
||||
}
|
||||
let refresh = serde_json::to_value(RefreshCommand {
|
||||
schema: "heimdall.auth_refresh_command.v1",
|
||||
refresh_token: "r",
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(refresh, serde_json::json!({"schema": "heimdall.auth_refresh_command.v1", "refreshToken": "r"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offered_set_is_the_configured_set() {
|
||||
let mut client = HeimdallClient::fixture();
|
||||
client.providers = vec![AuthProvider::Discord, AuthProvider::Google];
|
||||
assert_eq!(client.offered("google"), Some(AuthProvider::Google));
|
||||
assert_eq!(client.offered("discord"), Some(AuthProvider::Discord));
|
||||
assert_eq!(client.offered("twitch"), None);
|
||||
assert_eq!(client.offered("Google"), None);
|
||||
assert_eq!(client.offered("patreon"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_provider_list_names_only_known_providers_and_at_least_one() {
|
||||
assert_eq!(
|
||||
AuthProvider::set_from("google, discord,google").unwrap(),
|
||||
vec![AuthProvider::Google, AuthProvider::Discord]
|
||||
);
|
||||
assert_eq!(AuthProvider::set_from("twitch").unwrap(), vec![AuthProvider::Twitch]);
|
||||
for bad in ["", " , ", "github", "discord,patreon"] {
|
||||
assert!(AuthProvider::set_from(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
for provider in [AuthProvider::Google, AuthProvider::Discord, AuthProvider::Twitch] {
|
||||
assert_eq!(AuthProvider::parse(provider.as_str()), Some(provider));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,9 +44,24 @@ pub const IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT: &str = "GAMECULT_IDUNN_CANDI
|
|||
pub const IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT: &str = "GAMECULT_IDUNN_PROCESS_WRITE_LEASE";
|
||||
|
||||
pub(crate) const TARGET: &str = "ghostlight";
|
||||
const STATE_SCHEMA_GENERATION: &str = "dungeon-v1";
|
||||
const STATE_SCHEMA_GENERATION: &str = "world-v3";
|
||||
const STATE_CONTRACT_SHA256: &str =
|
||||
"sha256-f7a7e4206608cb4c47a867b02146f8657201ab10eab3937d1bb8c37fe6d605ef";
|
||||
"sha256-4ac3d4ceabedc48b4fc5a3c143ece00ac495d8d756bdc24f10034bcc1231970f";
|
||||
/// The exact `[state]` + `[[state.slots]]` text in `deployment/idunn/recipe.toml`
|
||||
/// that `STATE_CONTRACT_SHA256` above was computed from (Idunn's own
|
||||
/// `canonical_state_contract_sha256`: msgpack-encode the recipe's own parsed
|
||||
/// `[state]` struct, then sha256 it — run against the finalized recipe, not
|
||||
/// hand-derived). These two constants change together: whoever edits the
|
||||
/// recipe's `[state]` block must recompute `STATE_CONTRACT_SHA256` the same
|
||||
/// way and update both, or `recipe_matches_the_daemon_it_deploys` (below)
|
||||
/// fails on the text pin without saying the hash is wrong — which is the
|
||||
/// point: the test cannot recompute the hash itself (no TOML parser or
|
||||
/// msgpack encoder in this crate's dependency graph), so pinning the source
|
||||
/// text is the cheapest honest proxy for "the hash still matches this text".
|
||||
/// LF line endings: the committed git blob is LF-only; this constant matches
|
||||
/// that, not whatever CRLF a Windows checkout's autocrlf produces locally.
|
||||
#[cfg(test)]
|
||||
const EXPECTED_STATE_AND_SLOTS_TEXT: &str = "[state]\nschema_generation = \"world-v3\"\n\n[[state.slots]]\nid = \"world\"\nrelative_path = \"world.cc\"\nkind = \"cultcache-file\"\nschema = \"ghostlight.world_state.consumer.v6\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"preserve\"\nstartup = \"create-or-open-after-write-lease\"\n\n[[state.slots]]\nid = \"app-sessions\"\nrelative_path = \"service/app-sessions-v2.cc\"\nkind = \"cultcache-file\"\nschema = \"ghostlight.app_session_store.v2\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"preserve\"\nstartup = \"create-or-open-after-write-lease\"\n\n[[state.slots]]\nid = \"controller-work\"\nrelative_path = \"service/controller-work.cc\"\nkind = \"cultcache-file\"\nschema = \"ghostlight.controller_work.v17\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"preserve\"\nstartup = \"create-or-open-after-write-lease\"\n\n[[state.slots]]\nid = \"mesh-projection\"\nrelative_path = \"service/mesh-v2.cc\"\nkind = \"cultcache-file\"\nschema = \"gamecult.eve.surface.v1\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"rebuildable\"\nstartup = \"create-or-open-after-write-lease\"\n\n";
|
||||
const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0";
|
||||
const ODIN_CULTMESH_CATALOG_CONNECTION_ID: u32 = 0x0d1d_0002;
|
||||
const RUNTIME_PRESENCE_IDENTITY_FD_NAME: &str = "gamecult-runtime-presence-identity";
|
||||
|
|
@ -161,7 +176,7 @@ impl RuntimePresencePublisher {
|
|||
expected.state_schema_generation.as_deref() == Some(STATE_SCHEMA_GENERATION)
|
||||
&& expected.state_contract_sha256.as_deref() == Some(STATE_CONTRACT_SHA256)
|
||||
&& expected.write_lease_required,
|
||||
"Expected does not name the Dungeon's writable dungeon-v1 state"
|
||||
"Expected does not name Ghostlight's writable world-v3 state"
|
||||
);
|
||||
ensure!(
|
||||
activation.expected_projection_sha256 == expected.canonical_sha256()?
|
||||
|
|
@ -960,6 +975,12 @@ impl Drop for ProcessWriteLeaseGuard {
|
|||
|
||||
fn actual_capabilities() -> Vec<GameCultRuntimeCapability> {
|
||||
vec![
|
||||
GameCultRuntimeCapability {
|
||||
capability: "gamecult.eve.surface-provider".into(),
|
||||
schema: "gamecult.eve.surface.v1".into(),
|
||||
compatibility: "v1".into(),
|
||||
capacity: 1,
|
||||
},
|
||||
GameCultRuntimeCapability {
|
||||
capability: "ghostlight.world-service".into(),
|
||||
schema: STATE_SCHEMA.into(),
|
||||
|
|
@ -1250,6 +1271,12 @@ pub(crate) mod tests {
|
|||
candidate_endpoint: "http://127.0.0.1:18831".into(),
|
||||
}),
|
||||
capabilities: vec![
|
||||
IdunnExpectedCapability {
|
||||
capability: "gamecult.eve.surface-provider".into(),
|
||||
schema: "gamecult.eve.surface.v1".into(),
|
||||
compatibility: "v1".into(),
|
||||
minimum_capacity: 1,
|
||||
},
|
||||
IdunnExpectedCapability {
|
||||
capability: "ghostlight.world-service".into(),
|
||||
schema: STATE_SCHEMA.into(),
|
||||
|
|
@ -1411,7 +1438,7 @@ pub(crate) mod tests {
|
|||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("does not name the Dungeon's writable dungeon-v1 state")
|
||||
.contains("does not name Ghostlight's writable world-v3 state")
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -1607,6 +1634,149 @@ pub(crate) mod tests {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// No TOML parser is in this workspace's dependency graph (checked
|
||||
/// `Cargo.lock`), so this pins the exact strings the daemon's own
|
||||
/// constants require rather than parsing the recipe into a struct. It
|
||||
/// still catches the drift class Soul found: the recipe naming a state
|
||||
/// generation, provided schema, slot schema, or dependency shape the
|
||||
/// binary does not actually have (F2). Every field is anchored to its own
|
||||
/// table block (Soul's second pass: a bare `.contains()` anywhere in the
|
||||
/// file passed even when the matched value sat under the wrong table —
|
||||
/// e.g. a schema correct in `[[provides]]` but wrong in its own state
|
||||
/// slot).
|
||||
const RECIPE_TOML: &str = include_str!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../deployment/idunn/recipe.toml"
|
||||
));
|
||||
|
||||
/// Splits recipe text into blocks, each running from one line whose first
|
||||
/// non-whitespace byte is `[` up to (not including) the next such line.
|
||||
/// Assertions then search *within* the right block instead of the whole
|
||||
/// file, so a value in the wrong table cannot satisfy them.
|
||||
fn recipe_blocks(text: &str) -> Vec<&str> {
|
||||
let mut starts = Vec::new();
|
||||
let mut offset = 0usize;
|
||||
for line in text.split_inclusive('\n') {
|
||||
if line.trim_start().starts_with('[') {
|
||||
starts.push(offset);
|
||||
}
|
||||
offset += line.len();
|
||||
}
|
||||
starts.push(text.len());
|
||||
starts.windows(2).map(|pair| &text[pair[0]..pair[1]]).collect()
|
||||
}
|
||||
|
||||
/// The one block whose header matches `header` and whose body contains
|
||||
/// `anchor` (e.g. `id = "world"`, or `capability = "..."`) — the field
|
||||
/// that names which real table this is, distinct from every other block
|
||||
/// sharing the same header (there are four `[[state.slots]]` blocks, two
|
||||
/// `[[provides]]` blocks, two `[[dependencies]]` blocks).
|
||||
fn find_block<'a>(blocks: &[&'a str], header: &str, anchor: &str) -> &'a str {
|
||||
blocks
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|block| block.trim_start().starts_with(header) && block.contains(anchor))
|
||||
.unwrap_or_else(|| panic!("recipe has no {header} block containing {anchor:?}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipe_matches_the_daemon_it_deploys() {
|
||||
let blocks = recipe_blocks(RECIPE_TOML);
|
||||
|
||||
let world_service = find_block(
|
||||
&blocks,
|
||||
"[[provides]]",
|
||||
"capability = \"ghostlight.world-service\"",
|
||||
);
|
||||
assert!(
|
||||
world_service.contains(&format!("schema = \"{STATE_SCHEMA}\"")),
|
||||
"recipe [[provides]] ghostlight.world-service schema disagrees with STATE_SCHEMA"
|
||||
);
|
||||
assert!(
|
||||
world_service.contains(&format!(
|
||||
"compatibility = \"{}\"",
|
||||
state_schema_compatibility_tag()
|
||||
)),
|
||||
"recipe [[provides]] ghostlight.world-service compatibility disagrees with state_schema_compatibility_tag()"
|
||||
);
|
||||
|
||||
let world_slot = find_block(&blocks, "[[state.slots]]", "id = \"world\"");
|
||||
assert!(
|
||||
world_slot.contains(&format!("schema = \"{STATE_SCHEMA}\"")),
|
||||
"recipe world state slot schema disagrees with STATE_SCHEMA"
|
||||
);
|
||||
|
||||
let app_sessions_slot = find_block(&blocks, "[[state.slots]]", "id = \"app-sessions\"");
|
||||
assert!(
|
||||
app_sessions_slot.contains(&format!(
|
||||
"schema = \"{}\"",
|
||||
crate::app_session::STORE_SCHEMA
|
||||
)),
|
||||
"recipe app-sessions slot schema disagrees with app_session::STORE_SCHEMA"
|
||||
);
|
||||
|
||||
let controller_work_slot =
|
||||
find_block(&blocks, "[[state.slots]]", "id = \"controller-work\"");
|
||||
assert!(
|
||||
controller_work_slot
|
||||
.contains(&format!("schema = \"{}\"", ghostlight::CONTROLLER_WORK_SCHEMA)),
|
||||
"recipe controller-work slot schema disagrees with ghostlight::CONTROLLER_WORK_SCHEMA"
|
||||
);
|
||||
|
||||
let mesh_slot = find_block(&blocks, "[[state.slots]]", "id = \"mesh-projection\"");
|
||||
assert!(
|
||||
mesh_slot.contains("schema = \"gamecult.eve.surface.v1\""),
|
||||
"recipe mesh-projection slot schema disagrees with the mesh module's eve surface schema"
|
||||
);
|
||||
|
||||
let dependency_blocks: Vec<&&str> = blocks
|
||||
.iter()
|
||||
.filter(|block| block.trim_start().starts_with("[[dependencies]]"))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
dependency_blocks.len(),
|
||||
1,
|
||||
"recipe does not declare Ghostlight's exact one dependency \
|
||||
(Heimdall is discovered through Odin at use, not an Idunn \
|
||||
dependency, until Heimdall is a v2 target — see \
|
||||
runtime_dependency_bindings)"
|
||||
);
|
||||
|
||||
let odin_dependency = find_block(
|
||||
&blocks,
|
||||
"[[dependencies]]",
|
||||
&format!("capability = \"{}\"", ODIN_CAPABILITY.0),
|
||||
);
|
||||
assert!(
|
||||
odin_dependency.contains("kind = \"shared-infrastructure\""),
|
||||
"recipe Odin dependency kind disagrees with idunn_health's managed-shared-infrastructure rule"
|
||||
);
|
||||
|
||||
assert!(
|
||||
!RECIPE_TOML.contains("gamecult.codex.subscription-inference"),
|
||||
"recipe still declares the retired CodexConnector dependency"
|
||||
);
|
||||
|
||||
// STATE_CONTRACT_SHA256 pin (S3): the test cannot recompute Idunn's
|
||||
// hash itself (no TOML parser or msgpack encoder here), so it pins
|
||||
// the exact [state]+[[state.slots]] source text the hash was
|
||||
// computed from instead. A change to that text without recomputing
|
||||
// and updating STATE_CONTRACT_SHA256 to match fails here.
|
||||
let start = RECIPE_TOML
|
||||
.find("[state]")
|
||||
.expect("recipe has a [state] block");
|
||||
let end = RECIPE_TOML
|
||||
.find("[[provides]]")
|
||||
.expect("recipe [state] block is followed by [[provides]]");
|
||||
let state_and_slots_text = RECIPE_TOML[start..end].replace("\r\n", "\n");
|
||||
assert_eq!(
|
||||
state_and_slots_text, EXPECTED_STATE_AND_SLOTS_TEXT,
|
||||
"recipe [state]/[[state.slots]] text changed without updating \
|
||||
STATE_CONTRACT_SHA256 and EXPECTED_STATE_AND_SLOTS_TEXT together \
|
||||
(recompute the hash with Idunn's canonical_state_contract_sha256 \
|
||||
against the new recipe)"
|
||||
);
|
||||
}
|
||||
|
||||
/// A failed heartbeat publish does not abort `wait_for_write_lease`. The
|
||||
/// fixture publisher's endpoint (`127.0.0.1:9`) is closed, so every
|
||||
|
|
@ -1829,142 +1999,3 @@ pub(crate) mod tests {
|
|||
assert!(!is_root_read_only_file(0, 4_000, 0o446));
|
||||
}
|
||||
}
|
||||
|
||||
/// The recipe and the binary agree on the state Idunn fences. The recipe's
|
||||
/// `[state]` block is Idunn's input; `STATE_CONTRACT_SHA256` is the digest the
|
||||
/// daemon admits it by. Both are derived here from one typed table, so a slot
|
||||
/// edited in either place, or a schema constant bumped in code, fails a test
|
||||
/// instead of failing a deploy.
|
||||
#[cfg(test)]
|
||||
mod recipe_drift {
|
||||
use super::*;
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const RECIPE_TOML: &str = include_str!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../deployment/idunn/recipe.toml"
|
||||
));
|
||||
|
||||
// Mirrors Idunn's `StateDeclaration` wire shape: field order and the
|
||||
// kebab-case unit variants decide the bytes it hashes.
|
||||
#[derive(Serialize)]
|
||||
struct Declaration {
|
||||
schema_generation: &'static str,
|
||||
slots: Vec<Slot>,
|
||||
migration: Option<()>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Slot {
|
||||
id: &'static str,
|
||||
relative_path: &'static str,
|
||||
kind: &'static str,
|
||||
schema: &'static str,
|
||||
writer: &'static str,
|
||||
recovery: &'static str,
|
||||
startup: &'static str,
|
||||
}
|
||||
|
||||
fn slot(id: &'static str, path: &'static str, kind: &'static str, schema: &'static str, recovery: &'static str) -> Slot {
|
||||
Slot {
|
||||
id,
|
||||
relative_path: path,
|
||||
kind,
|
||||
schema,
|
||||
writer: "process-bound-single-writer",
|
||||
recovery,
|
||||
startup: "create-or-open-after-write-lease",
|
||||
}
|
||||
}
|
||||
|
||||
/// The slots the daemon opens, each schema read from the code that owns it.
|
||||
fn declaration() -> Declaration {
|
||||
Declaration {
|
||||
schema_generation: STATE_SCHEMA_GENERATION,
|
||||
slots: vec![
|
||||
slot("catalog", "catalog.cc", "cultcache-file", crate::catalog::STORE_TYPE, "preserve"),
|
||||
slot("app-sessions", "service/app-sessions-v2.cc", "cultcache-file", crate::app_session::STORE_SCHEMA, "preserve"),
|
||||
slot("snapshots", crate::vaults::SNAPSHOT_DIRECTORY, "external-file", ghostlight::VAULT_SNAPSHOT_SCHEMA, "rebuildable"),
|
||||
slot("timelines", "timelines", "external-file", STATE_SCHEMA, "preserve"),
|
||||
],
|
||||
migration: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn state_text(declaration: &Declaration) -> String {
|
||||
let mut text = format!("[state]\nschema_generation = \"{}\"\n\n", declaration.schema_generation);
|
||||
for slot in &declaration.slots {
|
||||
text += &format!(
|
||||
"[[state.slots]]\nid = \"{}\"\nrelative_path = \"{}\"\nkind = \"{}\"\nschema = \"{}\"\nwriter = \"{}\"\nrecovery = \"{}\"\nstartup = \"{}\"\n\n",
|
||||
slot.id, slot.relative_path, slot.kind, slot.schema, slot.writer, slot.recovery, slot.startup
|
||||
);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn contract_sha256(declaration: &Declaration) -> String {
|
||||
let bytes = rmp_serde::to_vec(declaration).expect("the declaration encodes");
|
||||
let digest = Sha256::digest(bytes);
|
||||
format!("sha256-{}", digest.iter().map(|byte| format!("{byte:02x}")).collect::<String>())
|
||||
}
|
||||
|
||||
/// The recipe's `[state]` through its last slot, line endings folded.
|
||||
fn recipe_state(recipe: &str) -> String {
|
||||
let start = recipe.find("[state]").expect("recipe has a [state] block");
|
||||
let end = recipe.find("[[provides]]").expect("[state] is followed by [[provides]]");
|
||||
recipe[start..end].replace("\r\n", "\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_recipe_state_is_the_contract_the_daemon_admits() {
|
||||
let declaration = declaration();
|
||||
assert_eq!(
|
||||
recipe_state(RECIPE_TOML),
|
||||
state_text(&declaration),
|
||||
"recipe [state] differs from the slots the daemon opens"
|
||||
);
|
||||
assert_eq!(
|
||||
STATE_CONTRACT_SHA256,
|
||||
contract_sha256(&declaration),
|
||||
"STATE_CONTRACT_SHA256 is not the digest of the slots the recipe declares"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edited_slot_or_schema_is_caught() {
|
||||
let declaration = declaration();
|
||||
for (from, to) in [
|
||||
("catalog.cc", "catalog-v2.cc"),
|
||||
("ghostlight.vault_snapshot.v1", "ghostlight.vault_snapshot.v2"),
|
||||
("recovery = \"rebuildable\"", "recovery = \"preserve\""),
|
||||
("dungeon-v1", "dungeon-v2"),
|
||||
] {
|
||||
let drifted = RECIPE_TOML.replacen(from, to, 1);
|
||||
assert_ne!(drifted, RECIPE_TOML, "{from} is not in the recipe");
|
||||
assert_ne!(recipe_state(&drifted), state_text(&declaration), "{from} -> {to} went unseen");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_recipe_provides_what_the_daemon_provides_and_nothing_retired() {
|
||||
let provided = format!(
|
||||
"capability = \"ghostlight.world-service\"\nschema = \"{STATE_SCHEMA}\"\ncompatibility = \"{}\"",
|
||||
state_schema_compatibility_tag()
|
||||
);
|
||||
assert!(RECIPE_TOML.contains(&provided), "recipe [[provides]] disagrees with actual_capabilities()");
|
||||
assert_eq!(RECIPE_TOML.matches("[[provides]]").count(), 1);
|
||||
let odin = format!(
|
||||
"kind = \"shared-infrastructure\"\ncapability = \"{}\"\nschema = \"{}\"\ncompatibility = \"{}\"",
|
||||
ODIN_CAPABILITY.0, ODIN_CAPABILITY.1, ODIN_CAPABILITY.2
|
||||
);
|
||||
assert!(RECIPE_TOML.contains(&odin), "recipe Odin dependency disagrees with ODIN_CAPABILITY");
|
||||
assert_eq!(RECIPE_TOML.matches("[[dependencies]]").count(), 1);
|
||||
let lowered = RECIPE_TOML.to_lowercase();
|
||||
for word in ["eve", "mesh", "codexconnector", "codex-connector", "web-build", "npm"] {
|
||||
assert!(!lowered.split(|c: char| !c.is_alphanumeric() && c != '-').any(|token| token == word), "recipe names {word}");
|
||||
}
|
||||
assert!(!lowered.contains("connection-ghostlight.key"), "the key path belongs to the operator binding");
|
||||
assert!(!lowered.contains("credentials_directory"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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:#}");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,658 +0,0 @@
|
|||
//! The DM's gears: one timeline's standing knobs for the world beyond the room.
|
||||
//!
|
||||
//! The document is scheduling state, never world truth. It holds how often each
|
||||
//! distance band takes a turn, how far the focus opens, how many node turns a
|
||||
//! wave may spend, what each background lane may spend in one post-turn window,
|
||||
//! the focus the DM added with a lease in fictional minutes, and the nodes the
|
||||
//! DM asked to run now. The planner and the elaborator's sweep read it; nothing
|
||||
//! else decides how much the world beyond the room moves. The DM changes it only
|
||||
//! through the `tune` and `run_world` tools, and the player's own place is never
|
||||
//! in it: that focus is derived from the world each time.
|
||||
//!
|
||||
//! Demotion is lazy. A lease names the fictional minute it ends at; past it the
|
||||
//! entry is simply not focus, and the next `tune` drops it from the document.
|
||||
//! Every wave records the knobs it planned under.
|
||||
|
||||
use anyhow::Context;
|
||||
use chrono::Utc;
|
||||
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||
use ghostlight::{
|
||||
CoverBudget, EntityId, GestaltKnobs, Hierarchy, LaneTokens, NodeAnchor, NodeId, RecordedKnobs, SubjectId,
|
||||
SubjectKind, TickMinutes, WorldSnapshot, id_text, id_text_matches, node_label,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::{ops::RangeInclusive, path::Path, sync::Arc};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
const TYPE: &str = "ghostlight.dungeon_gestalt_knobs.v1";
|
||||
const KEY: &str = "knobs";
|
||||
|
||||
/// The longest a band period or a lease may be: the clock's own span.
|
||||
const LONGEST_MINUTES: i64 = 525_600;
|
||||
const MOST_BANDS: usize = 8;
|
||||
const DEPTHS: RangeInclusive<i64> = 1..=8;
|
||||
const NODE_TURNS: RangeInclusive<i64> = 1..=32;
|
||||
const MOST_ALLOWANCE: i64 = 5_000_000;
|
||||
/// Leases and forced nodes the document holds at once.
|
||||
const MOST_ENTRIES: usize = 8;
|
||||
|
||||
/// What a focus entry or a forced run names: a place, or an institution whose
|
||||
/// node it is. Both are ids `table_view` prints.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) enum Target {
|
||||
Place(EntityId),
|
||||
Institution(SubjectId),
|
||||
}
|
||||
|
||||
impl Target {
|
||||
/// What the world calls the target, `-` when it no longer holds it.
|
||||
pub(crate) fn label(&self, world: &WorldSnapshot) -> String {
|
||||
target_label(self, world)
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
match self {
|
||||
Self::Place(id) => id_text(id),
|
||||
Self::Institution(id) => id_text(id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The node this target stands for in `hierarchy`: the node that governs a
|
||||
/// place, an institution's own node. None for an institution the hierarchy
|
||||
/// no longer holds.
|
||||
pub(crate) fn node(&self, hierarchy: &Hierarchy) -> Option<NodeId> {
|
||||
match self {
|
||||
Self::Place(place) => hierarchy.focus_path(*place).first().copied(),
|
||||
Self::Institution(subject) => hierarchy
|
||||
.nodes
|
||||
.values()
|
||||
.find(|node| node.anchor == NodeAnchor::Institution(*subject))
|
||||
.map(|node| node.id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A focus entry the DM added: it holds until the world's clock reaches `until`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct Lease {
|
||||
pub(crate) target: Target,
|
||||
pub(crate) until: u64,
|
||||
}
|
||||
|
||||
/// One timeline's knobs, document `ghostlight.dungeon_gestalt_knobs.v1`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct DmKnobs {
|
||||
pub(crate) knobs: RecordedKnobs,
|
||||
/// What each background lane may spend in one post-turn window.
|
||||
pub(crate) allowances: LaneTokens,
|
||||
pub(crate) focus: Vec<Lease>,
|
||||
/// Nodes the DM asked to run in the next post-turn wave; that wave takes them.
|
||||
pub(crate) forced: Vec<Target>,
|
||||
}
|
||||
|
||||
impl Default for DmKnobs {
|
||||
/// A Begin's knobs: bands of an hour, six hours, a day and a week by
|
||||
/// distance from the focus, the focus opened two nodes up, four node turns
|
||||
/// a wave, each node's cover at four cells of six, and the allowances sized
|
||||
/// to what the retired four-session sweep and its wave were: no cost has
|
||||
/// been measured yet, so the DM tunes from the averages its view prints.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
knobs: RecordedKnobs {
|
||||
bands: vec![60, 360, 1440, 10_080],
|
||||
depth: 2,
|
||||
max_node_turns: 4,
|
||||
cells: 4,
|
||||
constituent_cap: 6,
|
||||
urgency_slots: 1,
|
||||
},
|
||||
allowances: LaneTokens { wave: 200_000, elaboration: 200_000 },
|
||||
focus: Vec::new(),
|
||||
forced: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DmKnobs {
|
||||
/// The planner's knobs. A document whose values the planner would refuse
|
||||
/// never reaches it: `tune` admits only values this reads.
|
||||
pub(crate) fn gestalt(&self) -> anyhow::Result<GestaltKnobs> {
|
||||
let bands = self
|
||||
.knobs
|
||||
.bands
|
||||
.iter()
|
||||
.map(|minutes| TickMinutes::new(*minutes).with_context(|| format!("band {minutes} is outside the clock's span")))
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
let knobs = GestaltKnobs {
|
||||
bands,
|
||||
depth: self.knobs.depth,
|
||||
max_node_turns: self.knobs.max_node_turns,
|
||||
cover: CoverBudget {
|
||||
cells: self.knobs.cells,
|
||||
constituent_cap: self.knobs.constituent_cap,
|
||||
urgency_slots: self.knobs.urgency_slots,
|
||||
},
|
||||
};
|
||||
knobs.validate()?;
|
||||
Ok(knobs)
|
||||
}
|
||||
|
||||
/// The DM's focus entries still holding at fictional minute `now`.
|
||||
pub(crate) fn standing(&self, now: u64) -> impl Iterator<Item = &Lease> {
|
||||
self.focus.iter().filter(move |lease| lease.until > now)
|
||||
}
|
||||
}
|
||||
|
||||
/// The timeline's knobs in one CultCache file.
|
||||
pub(crate) struct KnobStore {
|
||||
store: OwnedRedbMessagePackBackingStore,
|
||||
knobs: DmKnobs,
|
||||
}
|
||||
|
||||
pub(crate) type KnobLog = Arc<Mutex<KnobStore>>;
|
||||
|
||||
impl KnobStore {
|
||||
/// Opens the file, writing a Begin's knobs into a timeline that has none.
|
||||
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
|
||||
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
|
||||
store.validate_path_identity().context("knob store path identity is invalid")?;
|
||||
let mut rows = store.pull_all()?;
|
||||
let knobs = match rows.pop() {
|
||||
None => None,
|
||||
Some(row) => {
|
||||
anyhow::ensure!(rows.is_empty() && row.r#type == TYPE && row.key == KEY, "the knob store holds a foreign record");
|
||||
Some(rmp_serde::from_slice::<DmKnobs>(&row.payload).context("the knobs did not decode")?)
|
||||
}
|
||||
};
|
||||
let mut opened = Self { store, knobs: knobs.clone().unwrap_or_default() };
|
||||
opened.knobs.gestalt().context("the stored knobs are not plannable")?;
|
||||
if knobs.is_none() {
|
||||
opened.replace(opened.knobs.clone())?;
|
||||
}
|
||||
Ok(opened)
|
||||
}
|
||||
|
||||
pub(crate) fn current(&self) -> DmKnobs {
|
||||
self.knobs.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn replace(&mut self, knobs: DmKnobs) -> anyhow::Result<()> {
|
||||
let row = CultCacheEnvelope {
|
||||
key: KEY.into(),
|
||||
r#type: TYPE.into(),
|
||||
payload: rmp_serde::to_vec_named(&knobs)?,
|
||||
stored_at: Utc::now().to_rfc3339(),
|
||||
schema_id: Some(TYPE.into()),
|
||||
};
|
||||
self.store.validate_path_identity().context("knob store ownership was lost")?;
|
||||
self.store.push(&row)?;
|
||||
self.knobs = knobs;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A whole number inside `range`, or the refusal quoting what was given.
|
||||
fn whole(name: &str, value: &Value, range: RangeInclusive<i64>) -> Result<i64, String> {
|
||||
let Some(number) = value.as_i64() else {
|
||||
return Err(format!("{name} must be a whole number, got {value}"));
|
||||
};
|
||||
if range.contains(&number) {
|
||||
Ok(number)
|
||||
} else {
|
||||
Err(format!("{name} {number} is refused: it must be {} to {}", range.start(), range.end()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The place or institution `text` names, by the id `table_view` prints.
|
||||
fn resolve(text: &str, world: &WorldSnapshot) -> Result<Target, String> {
|
||||
if let Some(place) = world.places.iter().find(|place| id_text_matches(place.id, text)) {
|
||||
return Ok(Target::Place(place.id));
|
||||
}
|
||||
match world.subjects.iter().find(|subject| id_text_matches(subject.id, text)) {
|
||||
Some(subject) if subject.kind == SubjectKind::Institution && !subject.retired => {
|
||||
Ok(Target::Institution(subject.id))
|
||||
}
|
||||
Some(subject) => Err(format!(
|
||||
"`{text}` names {}, which is not an institution; name its place or its institution",
|
||||
subject.label
|
||||
)),
|
||||
None => Err(format!("`{text}` names no place or institution in the world")),
|
||||
}
|
||||
}
|
||||
|
||||
fn arguments_object(arguments: &str, tool: &str) -> Result<serde_json::Map<String, Value>, String> {
|
||||
match serde_json::from_str::<Value>(arguments) {
|
||||
Ok(Value::Object(fields)) => Ok(fields),
|
||||
_ => Err(format!("{tool}'s arguments are not a JSON object: `{arguments}`")),
|
||||
}
|
||||
}
|
||||
|
||||
fn texts(name: &str, value: &Value) -> Result<Vec<String>, String> {
|
||||
let Some(items) = value.as_array() else {
|
||||
return Err(format!("{name} must be a list, got {value}"));
|
||||
};
|
||||
items
|
||||
.iter()
|
||||
.map(|item| item.as_str().map(str::to_owned).ok_or_else(|| format!("{name} holds {item}, which is not an id")))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `tune`'s arguments applied to `current` at fictional minute `now`: the new
|
||||
/// knobs and what changed, or the refusal naming the first value outside its
|
||||
/// bound. Nothing changes unless every value is admitted.
|
||||
pub(crate) fn tune(
|
||||
current: &DmKnobs,
|
||||
arguments: &str,
|
||||
world: &WorldSnapshot,
|
||||
now: u64,
|
||||
) -> Result<(DmKnobs, String), String> {
|
||||
let fields = arguments_object(arguments, "tune")?;
|
||||
let mut next = current.clone();
|
||||
next.focus.retain(|lease| lease.until > now);
|
||||
let mut changed = Vec::new();
|
||||
for (name, value) in &fields {
|
||||
match name.as_str() {
|
||||
"bands" => {
|
||||
let items = value.as_array().ok_or_else(|| format!("bands must be a list, got {value}"))?;
|
||||
if items.is_empty() || items.len() > MOST_BANDS {
|
||||
return Err(format!("bands holds {} periods, refused: it takes 1 to {MOST_BANDS}", items.len()));
|
||||
}
|
||||
next.knobs.bands = items
|
||||
.iter()
|
||||
.map(|item| whole("band", item, 1..=LONGEST_MINUTES).map(|minutes| minutes as u32))
|
||||
.collect::<Result<_, _>>()?;
|
||||
changed.push(format!("bands {:?} minutes", next.knobs.bands));
|
||||
}
|
||||
"depth" => {
|
||||
next.knobs.depth = whole("depth", value, DEPTHS)? as u8;
|
||||
changed.push(format!("depth {}", next.knobs.depth));
|
||||
}
|
||||
"max_node_turns" => {
|
||||
next.knobs.max_node_turns = whole("max_node_turns", value, NODE_TURNS)? as u16;
|
||||
changed.push(format!("max_node_turns {}", next.knobs.max_node_turns));
|
||||
}
|
||||
"wave_allowance" => {
|
||||
next.allowances.wave = whole("wave_allowance", value, 0..=MOST_ALLOWANCE)? as u64;
|
||||
changed.push(format!("wave allowance {} tokens", next.allowances.wave));
|
||||
}
|
||||
"elaboration_allowance" => {
|
||||
next.allowances.elaboration = whole("elaboration_allowance", value, 0..=MOST_ALLOWANCE)? as u64;
|
||||
changed.push(format!("elaboration allowance {} tokens", next.allowances.elaboration));
|
||||
}
|
||||
"focus_remove" => {
|
||||
for text in texts("focus_remove", value)? {
|
||||
let before = next.focus.len();
|
||||
next.focus.retain(|lease| lease.target.text() != text);
|
||||
if next.focus.len() == before {
|
||||
return Err(format!("`{text}` is not one of your focus entries"));
|
||||
}
|
||||
changed.push(format!("focus on {text} removed"));
|
||||
}
|
||||
}
|
||||
"focus_add" => {}
|
||||
other => return Err(format!("tune takes no `{other}`")),
|
||||
}
|
||||
}
|
||||
if let Some(value) = fields.get("focus_add") {
|
||||
let items = value.as_array().ok_or_else(|| format!("focus_add must be a list, got {value}"))?;
|
||||
for item in items {
|
||||
let entry = item.as_object().ok_or_else(|| format!("focus_add holds {item}, which is not an entry"))?;
|
||||
let text = entry
|
||||
.get("target")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| format!("focus_add entry {item} names no target"))?;
|
||||
let minutes = whole("lease_minutes", entry.get("lease_minutes").unwrap_or(&Value::Null), 1..=LONGEST_MINUTES)?;
|
||||
let target = resolve(text, world)?;
|
||||
next.focus.retain(|lease| lease.target != target);
|
||||
next.focus.push(Lease { target, until: now.saturating_add(minutes as u64) });
|
||||
changed.push(format!("focus on {text} for {minutes} minutes"));
|
||||
}
|
||||
}
|
||||
if changed.is_empty() {
|
||||
return Err("tune changed nothing: name bands, depth, max_node_turns, wave_allowance, elaboration_allowance, focus_add or focus_remove".into());
|
||||
}
|
||||
if next.focus.len() > MOST_ENTRIES {
|
||||
return Err(format!("{} focus entries is refused: {MOST_ENTRIES} at most", next.focus.len()));
|
||||
}
|
||||
next.gestalt().map_err(|error| error.to_string())?;
|
||||
Ok((next, format!("tuned: {}. Allowances bind the window already open too: a lane held above its new allowance is exhausted.", changed.join("; "))))
|
||||
}
|
||||
|
||||
/// `run_world`'s arguments: the targets it names, resolved against the world.
|
||||
pub(crate) fn run_world(arguments: &str, world: &WorldSnapshot) -> Result<Vec<Target>, String> {
|
||||
let fields = arguments_object(arguments, "run_world")?;
|
||||
let value = fields.get("targets").ok_or_else(|| format!("run_world needs `targets`: `{arguments}`"))?;
|
||||
let mut targets = Vec::new();
|
||||
for text in texts("targets", value)? {
|
||||
let target = resolve(&text, world)?;
|
||||
if !targets.contains(&target) {
|
||||
targets.push(target);
|
||||
}
|
||||
}
|
||||
if targets.is_empty() || targets.len() > MOST_ENTRIES {
|
||||
return Err(format!("run_world takes 1 to {MOST_ENTRIES} targets, got {}", targets.len()));
|
||||
}
|
||||
Ok(targets)
|
||||
}
|
||||
|
||||
/// Average tokens a node turn cost, by band, from the waves the timeline has
|
||||
/// closed: `(average, node turns)` for each band, the last band taking every
|
||||
/// distance beyond it.
|
||||
pub(crate) fn band_costs(nodes: impl Iterator<Item = (u8, u64)>, bands: usize) -> Vec<(u64, u64)> {
|
||||
let mut totals = vec![(0u64, 0u64); bands];
|
||||
for (distance, tokens) in nodes {
|
||||
let band = usize::from(distance).min(bands - 1);
|
||||
totals[band].0 += tokens;
|
||||
totals[band].1 += 1;
|
||||
}
|
||||
totals
|
||||
.into_iter()
|
||||
.map(|(tokens, turns)| (tokens.checked_div(turns).unwrap_or(0), turns))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The section of the DM's opening view that shows its gears: the knobs, where
|
||||
/// attention is, what is queued and what each band has cost.
|
||||
pub(crate) fn gears_view(
|
||||
knobs: &DmKnobs,
|
||||
world: &WorldSnapshot,
|
||||
hierarchy: &Hierarchy,
|
||||
player_places: &[EntityId],
|
||||
costs: &[(u64, u64)],
|
||||
) -> String {
|
||||
let mut out = String::from(
|
||||
"The world beyond the room, and the gears you may turn (`tune`, `run_world`; time stays yours, and nothing here runs a node that is not due unless you ask):\n",
|
||||
);
|
||||
let bands: Vec<String> = knobs.knobs.bands.iter().map(u32::to_string).collect();
|
||||
out.push_str(&format!(
|
||||
"- Bands, minutes between a node's turns by distance from the focus, nearest first: {}. Depth {} (nodes open along each focus path), at most {} node turns a wave.\n",
|
||||
bands.join(", "),
|
||||
knobs.knobs.depth,
|
||||
knobs.knobs.max_node_turns
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"- Allowances in one post-turn window: wave {} tokens, elaboration {} tokens.\n",
|
||||
knobs.allowances.wave, knobs.allowances.elaboration
|
||||
));
|
||||
for place in player_places {
|
||||
let path: Vec<String> = hierarchy.focus_path(*place).into_iter().map(|node| node_label(node, world, hierarchy)).collect();
|
||||
out.push_str(&format!("- The player's focus runs {}.\n", path.join(" > ")));
|
||||
}
|
||||
for lease in knobs.standing(world.now.0) {
|
||||
out.push_str(&format!(
|
||||
"- Your focus: {} [{}], {} more minutes.\n",
|
||||
target_label(&lease.target, world),
|
||||
lease.target.text(),
|
||||
lease.until - world.now.0
|
||||
));
|
||||
}
|
||||
if !knobs.forced.is_empty() {
|
||||
let named: Vec<String> = knobs.forced.iter().map(|target| target_label(target, world)).collect();
|
||||
out.push_str(&format!("- Asked to run in this turn's wave: {}.\n", named.join(", ")));
|
||||
}
|
||||
let spent: Vec<String> = costs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(band, (average, turns))| {
|
||||
if *turns == 0 {
|
||||
format!("band {band}: no node turn yet")
|
||||
} else {
|
||||
format!("band {band}: {average} tokens over {turns} node turns")
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
out.push_str(&format!("- What a node turn has cost on average: {}.\n\n", spent.join("; ")));
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn target_label(target: &Target, world: &WorldSnapshot) -> String {
|
||||
match target {
|
||||
Target::Place(id) => world.places.iter().find(|place| place.id == *id).map(|place| place.label.clone()),
|
||||
Target::Institution(id) => world.subjects.iter().find(|subject| subject.id == *id).map(|subject| subject.label.clone()),
|
||||
}
|
||||
.unwrap_or_else(|| "-".to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{play::tests::ScriptedPort, waves::tests::Fixture};
|
||||
use serde_json::json;
|
||||
|
||||
fn opaque<T: serde::de::DeserializeOwned>() -> T {
|
||||
serde_json::from_value(json!(uuid::Uuid::new_v4().to_string())).unwrap()
|
||||
}
|
||||
|
||||
/// A world with a player, a Warden and two places, and the id of each place.
|
||||
async fn world() -> (WorldSnapshot, Hierarchy, EntityId, EntityId) {
|
||||
let fixture = Fixture::new().await;
|
||||
let (timelines, _stopped) = fixture.open(ScriptedPort::new(vec![]));
|
||||
let host = timelines.host(&fixture.id).await.unwrap();
|
||||
let world = host.world.snapshot().await.unwrap();
|
||||
let hierarchy = host.world.hierarchy().await.unwrap();
|
||||
let place = |label: &str| world.places.iter().find(|place| place.label == label).unwrap().id;
|
||||
let (commons, gate) = (place("The Commons"), place("Gatehouse"));
|
||||
(world, hierarchy, commons, gate)
|
||||
}
|
||||
|
||||
/// The same world with `count` more places declared, and every place's id.
|
||||
async fn crowded_world(count: usize) -> (WorldSnapshot, Vec<EntityId>) {
|
||||
let fixture = Fixture::new().await;
|
||||
let (timelines, _stopped) = fixture.open(ScriptedPort::new(vec![]));
|
||||
let host = timelines.host(&fixture.id).await.unwrap();
|
||||
let declared: Vec<String> = (0..count)
|
||||
.map(|number| json!({"handle": format!("p{number}"), "label": format!("Place {number}"), "container": null}).to_string())
|
||||
.collect();
|
||||
let calls: Vec<(&str, &str)> = declared.iter().map(|call| ("declare_place", call.as_str())).collect();
|
||||
let decoded = ghostlight::decode_authoring_calls(&calls).unwrap();
|
||||
ghostlight::PlayPort::new(host.world.clone())
|
||||
.submit_patch(ghostlight::CommandId::new(), decoded.patch)
|
||||
.await
|
||||
.unwrap();
|
||||
let world = host.world.snapshot().await.unwrap();
|
||||
let places = world.places.iter().map(|place| place.id).collect();
|
||||
(world, places)
|
||||
}
|
||||
|
||||
fn refusal(current: &DmKnobs, world: &WorldSnapshot, arguments: serde_json::Value) -> String {
|
||||
tune(current, &arguments.to_string(), world, 0).expect_err("the call is refused")
|
||||
}
|
||||
|
||||
/// Spec test `bad values refused`: a value outside its bound is refused
|
||||
/// whole, quoting the value, and a refused call leaves the document as it was.
|
||||
#[tokio::test]
|
||||
async fn a_value_outside_its_bound_is_refused_quoting_it() {
|
||||
let (world, _, commons, _) = world().await;
|
||||
let current = DmKnobs::default();
|
||||
assert!(refusal(¤t, &world, json!({"bands": [60, -5]})).contains("band -5"));
|
||||
assert!(refusal(¤t, &world, json!({"bands": [0]})).contains("band 0"));
|
||||
assert!(refusal(¤t, &world, json!({"bands": [525_601]})).contains("band 525601"));
|
||||
assert!(refusal(¤t, &world, json!({"bands": []})).contains("0 periods"));
|
||||
assert!(refusal(¤t, &world, json!({"bands": [1, 2, 3, 4, 5, 6, 7, 8, 9]})).contains("9 periods"));
|
||||
assert!(refusal(¤t, &world, json!({"depth": 0})).contains("depth 0"));
|
||||
assert!(refusal(¤t, &world, json!({"depth": 9})).contains("depth 9"));
|
||||
assert!(refusal(¤t, &world, json!({"depth": "deep"})).contains("\"deep\""));
|
||||
assert!(refusal(¤t, &world, json!({"depth": 2.5})).contains("2.5"));
|
||||
assert!(refusal(¤t, &world, json!({"max_node_turns": 0})).contains("max_node_turns 0"));
|
||||
assert!(refusal(¤t, &world, json!({"max_node_turns": 33})).contains("max_node_turns 33"));
|
||||
assert!(refusal(¤t, &world, json!({"wave_allowance": -1})).contains("wave_allowance -1"));
|
||||
assert!(refusal(¤t, &world, json!({"elaboration_allowance": 5_000_001})).contains("5000001"));
|
||||
assert!(refusal(¤t, &world, json!({"focus_remove": [id_text(commons)]})).contains("not one of your focus entries"));
|
||||
let lease = |minutes: i64| json!({"focus_add": [{"target": id_text(commons), "lease_minutes": minutes}]});
|
||||
assert!(refusal(¤t, &world, lease(0)).contains("lease_minutes 0"));
|
||||
assert!(refusal(¤t, &world, lease(525_601)).contains("lease_minutes 525601"));
|
||||
assert!(refusal(¤t, &world, json!({"focus_add": [{"target": id_text(commons)}]})).contains("lease_minutes"));
|
||||
assert!(refusal(¤t, &world, json!({"focus_add": [{"target": "nowhere", "lease_minutes": 5}]})).contains("`nowhere`"));
|
||||
assert!(refusal(¤t, &world, json!({"depth": 3, "colour": "red"})).contains("`colour`"), "an unknown field is refused");
|
||||
assert!(refusal(¤t, &world, json!({})).contains("changed nothing"));
|
||||
assert!(tune(¤t, "[1]", &world, 0).unwrap_err().contains("not a JSON object"));
|
||||
let person = id_text(world.subjects.iter().find(|subject| subject.label == "Player").unwrap().id);
|
||||
assert!(refusal(¤t, &world, json!({"focus_add": [{"target": person, "lease_minutes": 5}]})).contains("not an institution"));
|
||||
// One good field beside a bad one changes nothing: the call is refused whole.
|
||||
assert!(tune(¤t, r#"{"depth": 4, "bands": [-1]}"#, &world, 0).is_err());
|
||||
assert_eq!(current, DmKnobs::default());
|
||||
}
|
||||
|
||||
/// The values inside their bounds are applied, a lease is anchored at the
|
||||
/// clock the call was made at, and a lease the DM re-adds replaces its own.
|
||||
#[tokio::test]
|
||||
async fn a_tune_inside_its_bounds_applies_every_field() {
|
||||
let (world, _, commons, gate) = world().await;
|
||||
let current = DmKnobs::default();
|
||||
let asked = json!({
|
||||
"bands": [5, 525_600],
|
||||
"depth": 8,
|
||||
"max_node_turns": 32,
|
||||
"wave_allowance": 0,
|
||||
"elaboration_allowance": 5_000_000,
|
||||
"focus_add": [{"target": id_text(gate), "lease_minutes": 30}],
|
||||
});
|
||||
let eight = json!({"bands": [1, 2, 3, 4, 5, 6, 7, 8]});
|
||||
assert_eq!(tune(¤t, &eight.to_string(), &world, 0).unwrap().0.knobs.bands.len(), 8, "eight periods is the most");
|
||||
let (next, said) = tune(¤t, &asked.to_string(), &world, 100).unwrap();
|
||||
assert_eq!(next.knobs.bands, vec![5, 525_600]);
|
||||
assert_eq!((next.knobs.depth, next.knobs.max_node_turns), (8, 32));
|
||||
assert_eq!(next.allowances, LaneTokens { wave: 0, elaboration: 5_000_000 });
|
||||
assert_eq!(next.focus, vec![Lease { target: Target::Place(gate), until: 130 }]);
|
||||
assert_eq!(next.knobs.cells, current.knobs.cells, "the cover is not the DM\'s to tune");
|
||||
assert!(said.contains("depth 8") && said.contains("open too"), "{said}");
|
||||
|
||||
let again = json!({"focus_add": [{"target": id_text(gate), "lease_minutes": 10}]});
|
||||
let (renewed, _) = tune(&next, &again.to_string(), &world, 110).unwrap();
|
||||
assert_eq!(renewed.focus, vec![Lease { target: Target::Place(gate), until: 120 }]);
|
||||
let (swapped, _) = tune(&renewed, &json!({"focus_remove": [id_text(gate)]}).to_string(), &world, 111).unwrap();
|
||||
assert!(swapped.focus.is_empty());
|
||||
let (dropped, _) = tune(&next, &json!({"depth": 1}).to_string(), &world, 130).unwrap();
|
||||
assert!(dropped.focus.is_empty(), "a lapsed lease is dropped by the next tune");
|
||||
let two = json!({"focus_add": [{"target": id_text(commons), "lease_minutes": 5}, {"target": id_text(gate), "lease_minutes": 5}]});
|
||||
assert_eq!(tune(¤t, &two.to_string(), &world, 0).unwrap().0.focus.len(), 2);
|
||||
}
|
||||
|
||||
/// Eight focus entries are the most: the ninth is refused whole, and an
|
||||
/// entry the DM already holds is renewed, not added.
|
||||
#[tokio::test]
|
||||
async fn the_document_holds_eight_focus_entries_and_no_more() {
|
||||
let (world, places) = crowded_world(8).await;
|
||||
let asked = |place: EntityId| json!({"focus_add": [{"target": id_text(place), "lease_minutes": 30}]}).to_string();
|
||||
let mut doc = DmKnobs::default();
|
||||
for place in &places[..8] {
|
||||
doc = tune(&doc, &asked(*place), &world, 0).unwrap().0;
|
||||
}
|
||||
assert_eq!(doc.focus.len(), 8, "eight entries are admitted");
|
||||
assert!(tune(&doc, &asked(places[8]), &world, 0).unwrap_err().contains("9 focus entries"));
|
||||
assert_eq!(tune(&doc, &asked(places[0]), &world, 5).unwrap().0.focus.len(), 8, "renewing is not adding");
|
||||
assert_eq!(tune(&doc, &asked(places[8]), &world, 30).unwrap().0.focus.len(), 1, "lapsed entries make room");
|
||||
let named = |count: usize| {
|
||||
let ids: Vec<String> = places[..count].iter().map(|place| id_text(*place)).collect();
|
||||
run_world(&json!({"targets": ids}).to_string(), &world)
|
||||
};
|
||||
assert_eq!(named(8).unwrap().len(), 8);
|
||||
assert!(named(9).unwrap_err().contains("got 9"));
|
||||
}
|
||||
|
||||
/// An institution is named like a place and is the DM's focus or ask; a
|
||||
/// person is not.
|
||||
#[tokio::test]
|
||||
async fn an_institution_is_named_by_its_id_and_labelled_by_its_name() {
|
||||
let (mut world, hierarchy, _, _) = world().await;
|
||||
let warden = world.subjects.iter().find(|subject| subject.label == "Warden").unwrap().id;
|
||||
let asked = json!({"focus_add": [{"target": id_text(warden), "lease_minutes": 30}]}).to_string();
|
||||
let (doc, _) = tune(&DmKnobs::default(), &asked, &world, 0).unwrap();
|
||||
assert_eq!(doc.focus, vec![Lease { target: Target::Institution(warden), until: 30 }]);
|
||||
assert_eq!(run_world(&json!({"targets": [id_text(warden)]}).to_string(), &world).unwrap(), vec![Target::Institution(warden)]);
|
||||
let mut retired = world.clone();
|
||||
retired.subjects.iter_mut().find(|subject| subject.id == warden).unwrap().retired = true;
|
||||
assert!(tune(&DmKnobs::default(), &asked, &retired, 0).unwrap_err().contains("not an institution"), "a retired institution is not named");
|
||||
world.now = ghostlight::FictionalMinutes(0);
|
||||
let view = gears_view(&doc, &world, &hierarchy, &[], &[(0, 0)]);
|
||||
assert!(view.contains(&format!("Your focus: Warden [{}], 30 more minutes.", id_text(warden))), "{view}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_world_names_places_and_institutions_the_view_prints() {
|
||||
let (world, _, commons, gate) = world().await;
|
||||
let named = |ids: Vec<String>| run_world(&json!({"targets": ids}).to_string(), &world);
|
||||
assert_eq!(
|
||||
named(vec![id_text(gate), id_text(commons), id_text(gate)]).unwrap(),
|
||||
vec![Target::Place(gate), Target::Place(commons)],
|
||||
"each target once, in the order named"
|
||||
);
|
||||
assert!(named(vec![]).unwrap_err().contains("1 to 8 targets"));
|
||||
assert!(named(vec!["nowhere".into()]).unwrap_err().contains("`nowhere`"));
|
||||
assert!(run_world("{}", &world).unwrap_err().contains("needs `targets`"));
|
||||
assert!(run_world(r#"{"targets":"all"}"#, &world).unwrap_err().contains("must be a list"));
|
||||
assert!(run_world(r#"{"targets":[3]}"#, &world).unwrap_err().contains("not an id"));
|
||||
}
|
||||
|
||||
/// A target is the node that governs it: a place's governing node, an
|
||||
/// institution's own, none for an institution the world no longer holds.
|
||||
#[tokio::test]
|
||||
async fn a_target_is_the_node_that_governs_it() {
|
||||
let (world, hierarchy, commons, gate) = world().await;
|
||||
let anchor = |target: Target| hierarchy.nodes[&target.node(&hierarchy).unwrap()].anchor;
|
||||
assert_eq!(anchor(Target::Place(commons)), NodeAnchor::Place(commons));
|
||||
assert_eq!(anchor(Target::Place(gate)), NodeAnchor::Place(gate));
|
||||
let warden = world.subjects.iter().find(|subject| subject.label == "Warden").unwrap().id;
|
||||
assert_eq!(anchor(Target::Institution(warden)), NodeAnchor::Institution(warden));
|
||||
assert_eq!(Target::Institution(opaque::<SubjectId>()).node(&hierarchy), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stored_document_is_the_one_a_reopen_reads() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("gestalt-knobs.cc");
|
||||
let mut kept = DmKnobs::default();
|
||||
{
|
||||
let mut store = KnobStore::open(&path).unwrap();
|
||||
assert_eq!(store.current(), DmKnobs::default(), "a Begin\'s knobs, written at first open");
|
||||
kept.knobs.depth = 5;
|
||||
kept.focus.push(Lease { target: Target::Place(opaque::<EntityId>()), until: 9 });
|
||||
kept.forced.push(Target::Institution(opaque::<SubjectId>()));
|
||||
store.replace(kept.clone()).unwrap();
|
||||
}
|
||||
assert_eq!(KnobStore::open(&path).unwrap().current(), kept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_the_planner_would_refuse_is_not_opened() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("gestalt-knobs.cc");
|
||||
{
|
||||
let mut store = KnobStore::open(&path).unwrap();
|
||||
let mut broken = DmKnobs::default();
|
||||
broken.knobs.bands.clear();
|
||||
store.replace(broken).unwrap();
|
||||
}
|
||||
assert!(KnobStore::open(&path).is_err());
|
||||
}
|
||||
|
||||
/// What a band costs on average is read from the node turns the closed waves
|
||||
/// report: a distance past the last band is the last band.
|
||||
#[test]
|
||||
fn a_bands_cost_is_the_average_of_its_node_turns() {
|
||||
let turns = [(0u8, 100u64), (0, 300), (1, 50), (9, 10), (3, 30)];
|
||||
assert_eq!(band_costs(turns.into_iter(), 3), vec![(200, 2), (50, 1), (20, 2)]);
|
||||
assert_eq!(band_costs(std::iter::empty(), 2), vec![(0, 0), (0, 0)]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_view_prints_the_gears_where_attention_is_and_what_is_asked() {
|
||||
let (mut world, hierarchy, commons, gate) = world().await;
|
||||
world.now = ghostlight::FictionalMinutes(10);
|
||||
let mut knobs = DmKnobs::default();
|
||||
knobs.focus = vec![
|
||||
Lease { target: Target::Place(gate), until: 70 },
|
||||
Lease { target: Target::Place(commons), until: 10 },
|
||||
];
|
||||
knobs.forced = vec![Target::Place(gate)];
|
||||
let view = gears_view(&knobs, &world, &hierarchy, &[commons], &[(200, 2), (0, 0), (0, 0), (0, 0)]);
|
||||
assert!(view.contains("60, 360, 1440, 10080. Depth 2"), "{view}");
|
||||
assert!(view.contains("wave 200000 tokens, elaboration 200000 tokens"));
|
||||
assert!(view.contains("The player\'s focus runs The Commons > world."));
|
||||
assert!(view.contains(&format!("Your focus: Gatehouse [{}], 60 more minutes.", id_text(gate))));
|
||||
assert!(!view.contains("Your focus: The Commons"), "a lapsed lease is not shown");
|
||||
assert!(view.contains("Asked to run in this turn\'s wave: Gatehouse."));
|
||||
assert!(view.contains("band 0: 200 tokens over 2 node turns; band 1: no node turn yet"));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,27 +1,10 @@
|
|||
mod api;
|
||||
mod app_session;
|
||||
mod auth_guard;
|
||||
mod begin;
|
||||
mod catalog;
|
||||
mod eve;
|
||||
mod heimdall;
|
||||
mod idunn_health;
|
||||
mod invite;
|
||||
mod knobs;
|
||||
mod page;
|
||||
#[cfg(test)]
|
||||
mod playtest;
|
||||
mod mesh;
|
||||
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;
|
||||
mod verbs;
|
||||
mod waves;
|
||||
|
||||
use anyhow::bail;
|
||||
use std::path::PathBuf;
|
||||
|
|
@ -30,18 +13,9 @@ use std::path::PathBuf;
|
|||
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"),
|
||||
_ => bail!("usage: ghostlight-dungeon [--state-root PATH]"),
|
||||
};
|
||||
runtime::run(state_root).await
|
||||
}
|
||||
|
|
|
|||
464
crates/ghostlight-dungeon/src/mesh.rs
Normal file
464
crates/ghostlight-dungeon/src/mesh.rs
Normal file
|
|
@ -0,0 +1,464 @@
|
|||
//! Derived CultMesh and Eve projection.
|
||||
//!
|
||||
//! The mesh publishes the world owner's current surface. It never pulls or
|
||||
//! repairs world state and it has no command authority.
|
||||
|
||||
use crate::eve;
|
||||
use ghostlight::{CONSUMER_PATCH_SCHEMA, CONSUMER_RECEIPT_SCHEMA, STATE_SCHEMA, WorldSnapshot};
|
||||
use anyhow::Result;
|
||||
use chrono::{DateTime, Utc};
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use cultmesh_rs::{
|
||||
CultMesh, CultMeshNode, CultMeshNodeOptions, CultMeshRudpDocumentPublishOptions,
|
||||
publish_cultnet_messages_to_rudp_catalog,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
net::SocketAddr,
|
||||
path::Path,
|
||||
sync::{
|
||||
Arc, Condvar, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
thread,
|
||||
};
|
||||
|
||||
pub(crate) const PROVIDER_ID: &str = "gamecult.ghostlight.dungeon";
|
||||
pub(crate) const SURFACE_ID: &str = "ghostlight.play";
|
||||
pub(crate) const COMMAND_BOUNDARY: &str = "ghostlight.eve.commands";
|
||||
pub(crate) const COMMAND_RESULT_SCHEMA: &str = "gamecult.eve.command_result.v1";
|
||||
pub(crate) const COMMAND_RECEIPT_SCHEMA: &str = "gamecult.eve.command_receipt.v1";
|
||||
/// The repository that owns this surface, as the command receipt contract
|
||||
/// requires of every result.
|
||||
pub(crate) const OWNER_REPO: &str = "GameCult/Ghostlight";
|
||||
|
||||
const HEALTH_KEY: &str = "ghostlight:dungeon:health";
|
||||
const ADVERTISEMENT_KEY: &str = "eve:provider:gamecult.ghostlight.dungeon";
|
||||
const SURFACE_KEY: &str = "eve:surface:ghostlight.play";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(type = "gamecult.eve.surface", schema = "gamecult.eve.surface.v1")]
|
||||
struct EveSurfaceRecord {
|
||||
#[cultcache(key = 0)]
|
||||
value: Value,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "gamecult.eve.provider_advertisement",
|
||||
schema = "gamecult.eve.provider_advertisement.v1"
|
||||
)]
|
||||
struct EveProviderAdvertisementRecord {
|
||||
#[cultcache(key = 0)]
|
||||
value: Value,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "ghostlight.service_health",
|
||||
schema = "ghostlight.service_health.v2"
|
||||
)]
|
||||
struct ServiceHealthRecord {
|
||||
#[cultcache(key = 0)]
|
||||
value: Value,
|
||||
}
|
||||
|
||||
cultmesh_rs::cultmesh_documents!(GhostlightDocuments {
|
||||
EveSurfaceRecord => "gamecult.eve.surface.v1",
|
||||
EveProviderAdvertisementRecord => "gamecult.eve.provider_advertisement.v1",
|
||||
ServiceHealthRecord => "ghostlight.service_health.v2",
|
||||
});
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct MeshRuntimeIdentity {
|
||||
pub(crate) runtime_id: String,
|
||||
pub(crate) service_id: String,
|
||||
pub(crate) located_service: String,
|
||||
}
|
||||
|
||||
impl Default for MeshRuntimeIdentity {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
runtime_id: "ghostlight-dungeon".into(),
|
||||
service_id: "ghostlight-dungeon".into(),
|
||||
located_service: "local".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct MeshPublisher {
|
||||
node: Arc<Mutex<CultMeshNode>>,
|
||||
remote: Option<RemoteReplication>,
|
||||
identity: MeshRuntimeIdentity,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct RemoteReplication {
|
||||
target: SocketAddr,
|
||||
runtime_id: String,
|
||||
pending: Arc<(Mutex<Option<Vec<cultnet_rs::CultNetMessage>>>, Condvar)>,
|
||||
alive: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl MeshPublisher {
|
||||
pub(crate) fn open(
|
||||
store_path: impl AsRef<Path>,
|
||||
rudp_target: Option<SocketAddr>,
|
||||
identity: MeshRuntimeIdentity,
|
||||
) -> Result<Self> {
|
||||
if let Some(parent) = store_path.as_ref().parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let node = CultMesh::create_node(
|
||||
store_path,
|
||||
GhostlightDocuments,
|
||||
CultMeshNodeOptions {
|
||||
runtime_id: identity.runtime_id.clone(),
|
||||
// Ghostlight derives its own interface from the local owner.
|
||||
// Stale remote surfaces must never become startup authority.
|
||||
pull_on_start: false,
|
||||
},
|
||||
)?;
|
||||
let remote = rudp_target
|
||||
.map(|target| RemoteReplication::start(target, identity.runtime_id.clone()))
|
||||
.transpose()?;
|
||||
Ok(Self {
|
||||
node: Arc::new(Mutex::new(node)),
|
||||
remote,
|
||||
identity,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn provider_advertisement(&self, updated_at: &str) -> Value {
|
||||
provider_advertisement(&self.identity, updated_at)
|
||||
}
|
||||
|
||||
pub(crate) fn publish(&self, snapshot: Option<&WorldSnapshot>) -> Result<Value> {
|
||||
let surface = eve::mesh_surface(snapshot);
|
||||
let world_state = eve::world_state(snapshot);
|
||||
let version = eve::surface_version(snapshot);
|
||||
let updated_at = Utc::now().to_rfc3339();
|
||||
let health = json!({
|
||||
"schema":"ghostlight.service_health.v2",
|
||||
"status":"ok",
|
||||
"worldState":world_state,
|
||||
"surfaceVersion":version,
|
||||
"updatedAtUtc":updated_at,
|
||||
"runtime":self.identity.runtime_id,
|
||||
"commit":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")
|
||||
});
|
||||
let advertisement = provider_advertisement(&self.identity, &updated_at);
|
||||
let mut node = self
|
||||
.node
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("mesh lock poisoned"))?;
|
||||
let mut remote_messages = Vec::new();
|
||||
self.put_and_stage(
|
||||
&mut node,
|
||||
ADVERTISEMENT_KEY,
|
||||
&EveProviderAdvertisementRecord {
|
||||
value: advertisement,
|
||||
},
|
||||
&mut remote_messages,
|
||||
)?;
|
||||
self.put_and_stage(
|
||||
&mut node,
|
||||
SURFACE_KEY,
|
||||
&EveSurfaceRecord { value: surface },
|
||||
&mut remote_messages,
|
||||
)?;
|
||||
// Health is the completion marker for this derived projection. A
|
||||
// failed advertisement or surface write must leave the prior version
|
||||
// visibly stale rather than publishing green first.
|
||||
self.put_and_stage(
|
||||
&mut node,
|
||||
HEALTH_KEY,
|
||||
&ServiceHealthRecord {
|
||||
value: health.clone(),
|
||||
},
|
||||
&mut remote_messages,
|
||||
)?;
|
||||
drop(node);
|
||||
if let Some(remote) = &self.remote {
|
||||
remote.enqueue(remote_messages);
|
||||
}
|
||||
Ok(health)
|
||||
}
|
||||
|
||||
pub(crate) fn health(&self) -> Result<Value> {
|
||||
if self
|
||||
.remote
|
||||
.as_ref()
|
||||
.is_some_and(|remote| !remote.is_alive())
|
||||
{
|
||||
anyhow::bail!("Odin projection worker stopped");
|
||||
}
|
||||
self.node
|
||||
.try_lock()
|
||||
.map_err(|_| anyhow::anyhow!("mesh projection is busy or its lock is poisoned"))?
|
||||
.get_required::<ServiceHealthRecord>(HEALTH_KEY)
|
||||
.map(|record| record.value)
|
||||
}
|
||||
|
||||
fn put_and_stage<T>(
|
||||
&self,
|
||||
node: &mut CultMeshNode,
|
||||
key: impl Into<String>,
|
||||
value: &T,
|
||||
remote_messages: &mut Vec<cultnet_rs::CultNetMessage>,
|
||||
) -> Result<()>
|
||||
where
|
||||
T: DatabaseEntry + serde::Serialize,
|
||||
{
|
||||
let key = key.into();
|
||||
node.put(&key, value)?;
|
||||
if let Some(remote) = &self.remote {
|
||||
remote_messages.push(node.create_rudp_document_message(
|
||||
&key,
|
||||
value,
|
||||
&remote.options(),
|
||||
)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn provider_advertisement(identity: &MeshRuntimeIdentity, updated_at: &str) -> Value {
|
||||
json!({
|
||||
"schema":"gamecult.eve.provider_advertisement.v1",
|
||||
"providerId":PROVIDER_ID,
|
||||
"serviceId":identity.service_id,
|
||||
"verseId":"gamecult.private",
|
||||
"rootVerse":"gamecult",
|
||||
"canonicalService":"ghostlight-dungeon",
|
||||
"locatedService":identity.located_service,
|
||||
"cultMeshAddress":"cultmesh://gamecult.private/ghostlight/providers/dungeon",
|
||||
"title":"Ghostlight Dungeon",
|
||||
"kind":"narrative.simulation",
|
||||
"updatedAtUtc":updated_at,
|
||||
"freshness":{"state":"live","lastSeenAtUtc":updated_at,"maxAgeMs":360000},
|
||||
"schemas":[
|
||||
"gamecult.eve.surface.v1",
|
||||
"gamecult.eve.command_invocation.v1",
|
||||
COMMAND_RESULT_SCHEMA,
|
||||
"heimdall.access_gate_state.v1",
|
||||
STATE_SCHEMA,
|
||||
CONSUMER_PATCH_SCHEMA,
|
||||
CONSUMER_RECEIPT_SCHEMA
|
||||
],
|
||||
"witnesses":[{
|
||||
"kind":"source-commit",
|
||||
"ref":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")
|
||||
}],
|
||||
"surfaces":[{
|
||||
"surfaceId":SURFACE_ID,
|
||||
"schema":"gamecult.eve.surface.v1",
|
||||
"url":"/api/eve/surfaces/ghostlight.play",
|
||||
"transport":"https-json",
|
||||
"status":"available",
|
||||
"surfaceKind":"subject-scoped-narrative",
|
||||
"interactionModel":"typed-command-receipts",
|
||||
"worldInteraction":{
|
||||
"projectionKind":"owner-derived",
|
||||
"stateSchemas":[STATE_SCHEMA],
|
||||
"commandBoundary":COMMAND_BOUNDARY,
|
||||
"receiptSchema":COMMAND_RESULT_SCHEMA,
|
||||
"loweringTargets":["browser","eve-native","tui"],
|
||||
"ownership":"One Ghostlight WorldMailbox owns state; Eve lowers derived projections and commands."
|
||||
},
|
||||
"requiresPlugins":[{
|
||||
"pluginId":"gamecult.heimdall.access",
|
||||
"versionRange":"^1.0.0",
|
||||
"availability":"required",
|
||||
"requiredCapabilities":["auth.gate","auth.begin","auth.complete","auth.logout"]
|
||||
}]
|
||||
}],
|
||||
"commands":[{
|
||||
"command":COMMAND_BOUNDARY,
|
||||
"transport":"https-json",
|
||||
"summary":"Canonical Ghostlight Eve command boundary."
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
impl RemoteReplication {
|
||||
fn start(target: SocketAddr, runtime_id: String) -> Result<Self> {
|
||||
let pending = Arc::new((
|
||||
Mutex::new(None::<Vec<cultnet_rs::CultNetMessage>>),
|
||||
Condvar::new(),
|
||||
));
|
||||
let worker_pending = pending.clone();
|
||||
let worker_runtime_id = runtime_id.clone();
|
||||
let alive = Arc::new(AtomicBool::new(true));
|
||||
let worker_alive = alive.clone();
|
||||
thread::Builder::new()
|
||||
.name("ghostlight-odin-rudp".into())
|
||||
.spawn(move || {
|
||||
struct Liveness(Arc<AtomicBool>);
|
||||
impl Drop for Liveness {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::Release);
|
||||
}
|
||||
}
|
||||
let _liveness = Liveness(worker_alive);
|
||||
loop {
|
||||
let messages = {
|
||||
let (lock, ready) = &*worker_pending;
|
||||
let mut pending = lock
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
while pending.is_none() {
|
||||
pending = ready
|
||||
.wait(pending)
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
}
|
||||
pending.take().unwrap_or_default()
|
||||
};
|
||||
if messages.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let options = remote_options(target, &worker_runtime_id);
|
||||
if let Err(error) =
|
||||
publish_cultnet_messages_to_rudp_catalog(&messages, options)
|
||||
{
|
||||
tracing::warn!(
|
||||
document_count = messages.len(),
|
||||
%target,
|
||||
%error,
|
||||
"Odin publication failed; retaining the newest derived projection for retry"
|
||||
);
|
||||
let (lock, ready) = &*worker_pending;
|
||||
let mut pending = lock
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if pending.is_none() {
|
||||
*pending = Some(messages);
|
||||
}
|
||||
let _ = ready
|
||||
.wait_timeout(pending, std::time::Duration::from_secs(2))
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(Self {
|
||||
target,
|
||||
runtime_id,
|
||||
pending,
|
||||
alive,
|
||||
})
|
||||
}
|
||||
|
||||
fn is_alive(&self) -> bool {
|
||||
self.alive.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
fn options(&self) -> CultMeshRudpDocumentPublishOptions {
|
||||
remote_options(self.target, &self.runtime_id)
|
||||
}
|
||||
|
||||
fn enqueue(&self, messages: Vec<cultnet_rs::CultNetMessage>) {
|
||||
let (lock, ready) = &*self.pending;
|
||||
let mut pending = lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
*pending = Some(messages);
|
||||
ready.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_options(target: SocketAddr, runtime_id: &str) -> CultMeshRudpDocumentPublishOptions {
|
||||
let mut options = CultMeshRudpDocumentPublishOptions::odin(target, runtime_id);
|
||||
options.source_agent_id = Some(PROVIDER_ID.into());
|
||||
options.source_role = Some("narrative-simulation".into());
|
||||
options.tags = vec!["ghostlight".into(), "eve".into(), "private".into()];
|
||||
options
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn publishes_only_owner_derived_surface_and_health() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let publisher = MeshPublisher::open(
|
||||
directory.path().join("mesh-v2.cc"),
|
||||
None,
|
||||
MeshRuntimeIdentity::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let health = publisher.publish(None).unwrap();
|
||||
assert_eq!(health["worldState"], "empty");
|
||||
assert_eq!(health["surfaceVersion"], 0);
|
||||
assert_eq!(publisher.health().unwrap(), health);
|
||||
let node = publisher.node.lock().unwrap();
|
||||
let surface = node
|
||||
.get_required::<EveSurfaceRecord>(SURFACE_KEY)
|
||||
.unwrap()
|
||||
.value;
|
||||
assert_eq!(surface["type"], "surface-state");
|
||||
assert_eq!(surface["schema"], "gamecult.eve.surface.v1");
|
||||
assert_eq!(surface["providerId"], PROVIDER_ID);
|
||||
assert_eq!(surface["version"], 0);
|
||||
assert!(
|
||||
surface["updatedAtUtc"]
|
||||
.as_str()
|
||||
.is_some_and(|value| value.parse::<DateTime<Utc>>().is_ok())
|
||||
);
|
||||
assert_eq!(surface["surface"], eve::mesh_surface(None)["surface"]);
|
||||
assert_eq!(surface["commands"], eve::mesh_surface(None)["commands"]);
|
||||
assert!(
|
||||
node.get_required::<EveProviderAdvertisementRecord>(ADVERTISEMENT_KEY)
|
||||
.is_ok()
|
||||
);
|
||||
assert!(node.get_required::<ServiceHealthRecord>(HEALTH_KEY).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_odin_cannot_block_local_publication() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let publisher = MeshPublisher::open(
|
||||
directory.path().join("mesh-v2.cc"),
|
||||
Some("127.0.0.1:1".parse().unwrap()),
|
||||
MeshRuntimeIdentity::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
publisher.publish(None).unwrap();
|
||||
assert!(started.elapsed() < std::time::Duration::from_millis(500));
|
||||
assert_eq!(publisher.health().unwrap()["worldState"], "empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopped_odin_worker_makes_runtime_health_non_green() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let publisher = MeshPublisher::open(
|
||||
directory.path().join("mesh-v2.cc"),
|
||||
Some("127.0.0.1:1".parse().unwrap()),
|
||||
MeshRuntimeIdentity::default(),
|
||||
)
|
||||
.unwrap();
|
||||
publisher.publish(None).unwrap();
|
||||
publisher
|
||||
.remote
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.alive
|
||||
.store(false, Ordering::Release);
|
||||
assert!(publisher.health().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn advertisement_has_one_surface_and_one_command_boundary() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let publisher = MeshPublisher::open(
|
||||
directory.path().join("mesh-v2.cc"),
|
||||
None,
|
||||
MeshRuntimeIdentity::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let advertisement = publisher.provider_advertisement("2026-09-01T00:00:00Z");
|
||||
assert_eq!(advertisement["surfaces"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(advertisement["commands"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(advertisement["surfaces"][0]["surfaceId"], SURFACE_ID);
|
||||
}
|
||||
}
|
||||
|
|
@ -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
File diff suppressed because it is too large
Load diff
|
|
@ -1,196 +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 claims what attention holds first (`focus_of`: the player's place and
|
||||
//! the DM's standing focus), holds at most `Scale::sweep_permits` permits, and
|
||||
//! spends in its own post-turn window: the elaborator calls a provider only
|
||||
//! through the window's recording port, which refuses a call that could pass the
|
||||
//! timeline's elaboration allowance, so how much a sweep does is the DM's knob
|
||||
//! and not a session count. 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,
|
||||
knobs::{DmKnobs, Target},
|
||||
timelines::TimelineHost,
|
||||
};
|
||||
use ghostlight::{
|
||||
ControllerMode, EntityId, EvidenceSource, Focus, Hierarchy, NullEvidenceSource, WorldSnapshot,
|
||||
};
|
||||
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 world = match host.world.snapshot().await {
|
||||
Ok(world) => world,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "run-ahead could not read the world");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let hierarchy = match host.world.hierarchy().await {
|
||||
Ok(hierarchy) => hierarchy,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "run-ahead could not read the hierarchy");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let knobs = host.knobs.lock().await.current();
|
||||
let window = match host.window(world.revision, &world, knobs.allowances) {
|
||||
Ok(window) => Arc::new(window),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "run-ahead could not open its window");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let runner = host.controllers.elaborator(window, evidence);
|
||||
let permits = Arc::new(Semaphore::new(scale.sweep_permits));
|
||||
if let Err(error) = runner.sweep(permits, usize::MAX, &focus_of(&world, &hierarchy, &knobs)).await {
|
||||
tracing::warn!(%error, "run-ahead elaboration stopped");
|
||||
}
|
||||
}
|
||||
|
||||
/// The places the world's owner's own human subjects stand in: the room the
|
||||
/// player is in, which the DM's `react` owns and a world wave never turns.
|
||||
pub(crate) fn player_places(world: &WorldSnapshot) -> Vec<EntityId> {
|
||||
world
|
||||
.subjects
|
||||
.iter()
|
||||
.filter(|subject| {
|
||||
subject.controller_mode == Some(ControllerMode::Human)
|
||||
&& subject.human_controller.as_ref() == Some(&world.owner)
|
||||
})
|
||||
.filter_map(|subject| world.place_of(subject.id))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where attention is: the player's place, then the DM's focus entries whose
|
||||
/// lease still holds. A world with no placed player and no entries has no
|
||||
/// focus, and its sweep keeps the kernel's order.
|
||||
pub(crate) fn focus_of(world: &WorldSnapshot, hierarchy: &Hierarchy, knobs: &DmKnobs) -> Focus {
|
||||
let mut focus = Focus { places: player_places(world), nodes: Vec::new() };
|
||||
for lease in knobs.standing(world.now.0) {
|
||||
match lease.target {
|
||||
Target::Place(place) if !focus.places.contains(&place) => focus.places.push(place),
|
||||
Target::Place(_) => {}
|
||||
Target::Institution(_) => focus.nodes.extend(lease.target.node(hierarchy)),
|
||||
}
|
||||
}
|
||||
focus
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
/// The sweep looks where the player stands: the place of the owner's own
|
||||
/// human subject, and nowhere for a world whose owner controls no subject.
|
||||
#[tokio::test]
|
||||
async fn the_focus_of_a_world_is_its_owners_human_subjects_place() {
|
||||
let rig = deferred_rig();
|
||||
let begun = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &principal("alice"), request(Uuid::new_v4(), None))
|
||||
.await
|
||||
.unwrap();
|
||||
let host = rig.timelines.host(&begun.timeline).await.unwrap();
|
||||
let world = host.world.snapshot().await.unwrap();
|
||||
let player = world
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|subject| subject.human_controller.as_ref() == Some(&world.owner))
|
||||
.expect("the owner's player");
|
||||
let stands = world.place_of(player.id).expect("the player stands somewhere");
|
||||
let hierarchy = host.world.hierarchy().await.unwrap();
|
||||
let none = DmKnobs::default();
|
||||
assert_eq!(focus_of(&world, &hierarchy, &none).places, vec![stands]);
|
||||
|
||||
let mut stranger = world.clone();
|
||||
stranger.owner = ghostlight::PrincipalId::new("someone else");
|
||||
assert!(focus_of(&stranger, &hierarchy, &none).places.is_empty(), "another principal's subject is not the owner's player");
|
||||
let mut automaton = world;
|
||||
for subject in &mut automaton.subjects {
|
||||
subject.controller_mode = Some(ControllerMode::NarrativePersona);
|
||||
}
|
||||
assert!(focus_of(&automaton, &hierarchy, &none).places.is_empty(), "a persona is not looking");
|
||||
}
|
||||
|
||||
/// 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());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,211 +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; 6] = [
|
||||
"world.cc",
|
||||
"controller-work.cc",
|
||||
"play-turn-v1.cc",
|
||||
"calls.cc",
|
||||
"waves.cc",
|
||||
"gestalt-knobs.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());
|
||||
}
|
||||
}
|
||||
|
|
@ -1,177 +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,
|
||||
};
|
||||
/// The one neutral model id every test lane runs on: ids are opaque exact
|
||||
/// strings, so no fixture names a provider or tier.
|
||||
pub(crate) const TEST_LANE_MODEL: &str = "test/lane-a";
|
||||
|
||||
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,
|
||||
TEST_LANE_MODEL,
|
||||
"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(TEST_LANE_MODEL));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,175 +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,
|
||||
knobs::{KnobLog, KnobStore},
|
||||
play::PlayTable,
|
||||
state_layout::prepare_timeline_directory,
|
||||
waves::{WaveLog, WaveStore},
|
||||
};
|
||||
use ghostlight::{
|
||||
CallRecordError, CallRecordStore, ControllerModels, ControllerPort, ControllerRunner,
|
||||
InferencePort, LaneTokens, PersonaLane, RecordingInferencePort, RunId, RunStart, WorldMailbox,
|
||||
WorldSnapshot, 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<()>,
|
||||
/// The spend ledgers of this timeline's background windows, one run each.
|
||||
/// The play turn's own calls never reach it.
|
||||
pub(crate) background: Arc<CallRecordStore>,
|
||||
/// The world waves this timeline's closed turns planned, and what the DM
|
||||
/// has been shown of them.
|
||||
pub(crate) waves: WaveLog,
|
||||
/// The DM's standing knobs for this timeline's world beyond the room.
|
||||
pub(crate) knobs: KnobLog,
|
||||
inference: Arc<dyn InferencePort>,
|
||||
}
|
||||
|
||||
impl TimelineHost {
|
||||
/// The port of the post-turn window that follows world revision
|
||||
/// `revision`: the one port the background lanes call a provider
|
||||
/// through, reserving each call in the window's ledger first. The window's
|
||||
/// cap is its allowances together. A window at the same revision is the same
|
||||
/// ledger, so a trigger that finds nothing changed spends no new allowance,
|
||||
/// and a wave resumed after a restart reopens the ledger it opened in. The
|
||||
/// caller passes the knobs' allowances every time and the ledger follows them,
|
||||
/// keeping its spend: a tune binds the window already open.
|
||||
/// `world` is the world the window is opened over now.
|
||||
pub(crate) fn window(
|
||||
&self,
|
||||
revision: u64,
|
||||
world: &WorldSnapshot,
|
||||
allowances: LaneTokens,
|
||||
) -> Result<RecordingInferencePort, CallRecordError> {
|
||||
let run = RunId::new(&format!("window-{revision}"))?;
|
||||
RecordingInferencePort::open_following(
|
||||
self.inference.clone(),
|
||||
self.background.clone(),
|
||||
run,
|
||||
allowances.total(),
|
||||
allowances,
|
||||
&RunStart::of(world),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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 background = Arc::new(
|
||||
CallRecordStore::open(directory.join("calls.cc"))
|
||||
.context("the background call ledger could not be opened")?,
|
||||
);
|
||||
let waves: WaveLog = Arc::new(Mutex::new(
|
||||
WaveStore::open(directory.join("waves.cc")).context("the wave store could not be opened")?,
|
||||
));
|
||||
let knobs: KnobLog = Arc::new(Mutex::new(
|
||||
KnobStore::open(directory.join("gestalt-knobs.cc")).context("the knob store could not be opened")?,
|
||||
));
|
||||
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"),
|
||||
)?
|
||||
.with_gears(waves.clone(), knobs.clone());
|
||||
let (changes, _) = broadcast::channel(16);
|
||||
let host = Arc::new(TimelineHost {
|
||||
world,
|
||||
controllers,
|
||||
play: Arc::new(play),
|
||||
changes,
|
||||
sweeping: Mutex::new(()),
|
||||
background,
|
||||
waves,
|
||||
knobs,
|
||||
inference: self.shared.inference.clone(),
|
||||
});
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
|
@ -1,249 +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 })
|
||||
}
|
||||
|
||||
/// The `seq` of the newest entry; 0 for an empty log.
|
||||
pub(crate) fn last_seq(&self) -> u64 {
|
||||
self.entries.len() as u64
|
||||
}
|
||||
|
||||
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();
|
||||
assert_eq!(log.last_seq(), 0);
|
||||
for n in 1..=5 {
|
||||
assert_eq!(log.record(new(&format!("t{n}"), 1, &format!("say {n}"))).unwrap(), Some(n));
|
||||
assert_eq!(log.last_seq(), 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");
|
||||
}
|
||||
}
|
||||
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,398 +0,0 @@
|
|||
//! The Dungeon's verbs: the affordance catalog every world Begin makes
|
||||
//! declares, and the grant of it to every person.
|
||||
//!
|
||||
//! A fresh world knows only Speak. A deed the player may attempt but the world
|
||||
//! cannot lower is a gap, so the Dungeon declares the deeds a table is made of:
|
||||
//! attack, threaten and accuse. Each lowers to kernel effects the
|
||||
//! kernel alone writes: regard in the target (`AdjustAttitude`), pressure
|
||||
//! (`AdvancePressure`). The effects name no consequence
|
||||
//! beyond the deed. Nothing here refuses a verb on grounds of niceness: a
|
||||
//! sword is drawn when the preconditions hold (the target is in the room), and
|
||||
//! what the world does about it is state the table reads, not a rule.
|
||||
//!
|
||||
//! A deed carries its witnesses through the kernel's own display lowering: the
|
||||
//! table commits it with a `display` quote, which becomes a claim the whole room
|
||||
//! holds as `Seen`. Who saw it is therefore kernel state, and the Open
|
||||
//! grievances block of the table view is derived from it.
|
||||
//!
|
||||
//! What answers a deed is the table's judgement, not a rule here. The table
|
||||
//! sees who was wronged, who saw it, which forums cover the doer and whether
|
||||
//! anyone presses or has sworn a reckoning, and gives the office, the kin and
|
||||
//! the witnesses their own turns, ruling pressure (`advance_pressure`) or a
|
||||
//! sworn reckoning (`create_commitment`, an obligation with the doer as
|
||||
//! counterparty: the kernel refuses a goal that has one) where it judges the
|
||||
//! world would.
|
||||
//!
|
||||
//! Seams, recorded rather than patched:
|
||||
//! - An institution that must react off-screen, with no person of it in the
|
||||
//! room, is the Gestalt hierarchy's turn (`cut-gestalt-*`, not built). No
|
||||
//! scheduler stands in for it here.
|
||||
//! - Verbs are granted to the people a Begin holds. A person an Active
|
||||
//! elaborator authors later holds only what its author grants by id.
|
||||
//! - Steal, give, trade, seduce, persuade, flee, hide and move are not
|
||||
//! declared: a seeded world holds no custody to transfer, and the others
|
||||
//! lower to speech or to nothing the table cannot already rule.
|
||||
|
||||
use ghostlight::{DecodedBatch, SubjectKind, WorldSnapshot, decode_authoring_calls};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The deed kinds this catalog declares, in the order declared.
|
||||
pub(crate) const VERBS: [&str; 3] = ["attack", "threaten", "accuse"];
|
||||
|
||||
fn subject_role() -> Value {
|
||||
json!({"namespace": "subject", "kind": null})
|
||||
}
|
||||
|
||||
fn adjust(delta: i16) -> Value {
|
||||
json!({"op_kind": {"op": "adjust_attitude", "delta": delta, "decay": null}, "roles": ["target"], "bounds": {"bound": "none"}})
|
||||
}
|
||||
|
||||
fn colocated_target() -> Value {
|
||||
json!({"precondition": "can_reach", "subject": "target", "via": "colocated"})
|
||||
}
|
||||
|
||||
/// The declarations, as the authoring calls the Dungeon Master would make.
|
||||
fn declarations() -> Vec<(&'static str, Value)> {
|
||||
vec![
|
||||
(
|
||||
"declare_affordance",
|
||||
// Three grades of harm, weighted so a blow usually lands. The
|
||||
// regard the target holds of the actor falls by the grade; what the
|
||||
// wound or death means is the table's ruling.
|
||||
json!({
|
||||
"handle": "attack",
|
||||
"kind": "attack",
|
||||
"roles": [{"role": "target", "kind": subject_role()}],
|
||||
"preconditions": [colocated_target()],
|
||||
"effect_slots": [adjust(-35), adjust(-70), adjust(-100)],
|
||||
"outcome_bands": [
|
||||
{"weight": 3, "effects": [0]},
|
||||
{"weight": 3, "effects": [1]},
|
||||
{"weight": 2, "effects": [2]},
|
||||
],
|
||||
"carries_speech": false,
|
||||
}),
|
||||
),
|
||||
(
|
||||
"declare_affordance",
|
||||
json!({
|
||||
"handle": "threaten",
|
||||
"kind": "threaten",
|
||||
"roles": [{"role": "target", "kind": subject_role()}],
|
||||
"preconditions": [colocated_target()],
|
||||
"effect_slots": [
|
||||
{"op_kind": {"op": "advance_pressure", "by": 20}, "roles": ["target"], "bounds": {"bound": "none"}},
|
||||
adjust(-25),
|
||||
],
|
||||
"outcome_bands": [{"weight": 1, "effects": [0, 1]}],
|
||||
"carries_speech": false,
|
||||
}),
|
||||
),
|
||||
(
|
||||
"declare_affordance",
|
||||
// A grievance carried to someone who can lean on the accused:
|
||||
// pressure on the target from the accuser, who must hold the
|
||||
// charge as something believed. An office answers through its own
|
||||
// people using this same verb.
|
||||
json!({
|
||||
"handle": "accuse",
|
||||
"kind": "accuse",
|
||||
"roles": [
|
||||
{"role": "target", "kind": subject_role()},
|
||||
{"role": "charge", "kind": {"namespace": "entity", "kind": "fact"}},
|
||||
],
|
||||
"preconditions": [{"precondition": "knows", "fact": "charge", "at_least": "believed"}],
|
||||
"effect_slots": [
|
||||
{"op_kind": {"op": "advance_pressure", "by": 25}, "roles": ["target"], "bounds": {"bound": "none"}},
|
||||
],
|
||||
"outcome_bands": [{"weight": 1, "effects": [0]}],
|
||||
"carries_speech": false,
|
||||
}),
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The one patch that declares the catalog and grants it to every person the
|
||||
/// world holds. A world that already carries a verb is a replay of this step
|
||||
/// and is not asked again by the caller.
|
||||
pub(crate) fn install(world: &WorldSnapshot) -> Result<DecodedBatch, String> {
|
||||
let mut calls: Vec<(String, String)> = declarations()
|
||||
.into_iter()
|
||||
.map(|(name, arguments)| (name.to_owned(), arguments.to_string()))
|
||||
.collect();
|
||||
for subject in world
|
||||
.subjects
|
||||
.iter()
|
||||
.filter(|subject| subject.kind == SubjectKind::Person && !subject.retired)
|
||||
{
|
||||
for verb in VERBS {
|
||||
calls.push((
|
||||
"grant_affordance".to_owned(),
|
||||
json!({
|
||||
"subject": {"ref": "existing", "value": subject.id},
|
||||
"affordance": {"ref": "draft", "value": verb},
|
||||
})
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let borrowed: Vec<(&str, &str)> = calls.iter().map(|(name, arguments)| (name.as_str(), arguments.as_str())).collect();
|
||||
decode_authoring_calls(&borrowed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ghostlight::{
|
||||
CommandBody, CommandId, CreateWorldIntent, Lens, LensWeights, PlayPort, PrincipalCommandIntent,
|
||||
SubjectId, VerifiedPrincipalEvidence, WorldMailbox, decode_actor_call, table_view,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
struct Scenario {
|
||||
_directory: tempfile::TempDir,
|
||||
world: WorldMailbox,
|
||||
principal: VerifiedPrincipalEvidence,
|
||||
}
|
||||
|
||||
fn text(id: SubjectId) -> String {
|
||||
serde_json::to_value(id).unwrap().as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
fn existing(id: impl serde::Serialize) -> Value {
|
||||
json!({"ref": "existing", "value": id})
|
||||
}
|
||||
|
||||
async fn snapshot(scene: &Scenario) -> ghostlight::WorldSnapshot {
|
||||
scene.world.snapshot().await.unwrap()
|
||||
}
|
||||
|
||||
fn who(snapshot: &ghostlight::WorldSnapshot, label: &str) -> SubjectId {
|
||||
snapshot.subjects.iter().find(|subject| subject.label == label).expect("a subject by that label").id
|
||||
}
|
||||
|
||||
async fn submit(scene: &Scenario, body: CommandBody) {
|
||||
let snapshot = snapshot(scene).await;
|
||||
scene
|
||||
.world
|
||||
.submit_principal(
|
||||
PrincipalCommandIntent {
|
||||
id: CommandId::new(),
|
||||
world_id: snapshot.world_id,
|
||||
expected_revision: snapshot.revision,
|
||||
body,
|
||||
},
|
||||
&scene.principal,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn batch(calls: &[(&str, Value)]) -> ghostlight::WorldPatch {
|
||||
let owned: Vec<(&str, String)> = calls.iter().map(|(name, arguments)| (*name, arguments.to_string())).collect();
|
||||
let borrowed: Vec<(&str, &str)> = owned.iter().map(|(name, arguments)| (*name, arguments.as_str())).collect();
|
||||
decode_authoring_calls(&borrowed).expect("the calls decode").patch
|
||||
}
|
||||
|
||||
/// The table's own ruling, through the one door the Dungeon Master holds.
|
||||
async fn rule(scene: &Scenario, calls: &[(&str, Value)]) {
|
||||
PlayPort::new(scene.world.clone()).submit_patch(CommandId::new(), batch(calls)).await.unwrap();
|
||||
}
|
||||
|
||||
/// A tavern with Dorra, her kin Brannoch and a witness, Grix; the Hold's
|
||||
/// watch stands at the gate with Hilda. The player, Korr, is in the tavern.
|
||||
/// Dorra counts Korr a friend, so nothing about the room is hostile.
|
||||
async fn consequence_world() -> Scenario {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (world, _owner) = WorldMailbox::open(directory.path().join("world.cc")).unwrap();
|
||||
let principal = VerifiedPrincipalEvidence::new("consequence-scenario", chrono::Utc::now() + chrono::Duration::hours(4));
|
||||
let receipt = world
|
||||
.create(
|
||||
CreateWorldIntent {
|
||||
id: CommandId::new(),
|
||||
title: "Consequence Scenario".into(),
|
||||
brief: "A tavern, a gate and a watch.".into(),
|
||||
human_subject_label: "Korr".into(),
|
||||
narrative_persona_label: None,
|
||||
operational_agent_label: None,
|
||||
targets: BTreeMap::new(),
|
||||
jurisdictions: Vec::new(),
|
||||
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Hearth, 1)])),
|
||||
era: None,
|
||||
},
|
||||
&principal,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let scene = Scenario { _directory: directory, world, principal };
|
||||
let start = snapshot(&scene).await;
|
||||
let commons = start.places.iter().find(|place| place.label == "The Commons").unwrap().id;
|
||||
let speak = start.affordances.iter().find(|entry| entry.entry.kind.0 == "speak").unwrap().id;
|
||||
let subject = |handle: &str, label: &str, kind: &str, position: Value| {
|
||||
(
|
||||
"declare_subject",
|
||||
json!({
|
||||
"handle": handle,
|
||||
"label": label,
|
||||
"kind": kind,
|
||||
"controller": {"type": "narrative_persona"},
|
||||
"affordances": [existing(speak)],
|
||||
"position": position,
|
||||
}),
|
||||
)
|
||||
};
|
||||
let patch = batch(&[
|
||||
("declare_place", json!({"handle": "gate", "label": "The Gate", "container": null})),
|
||||
(
|
||||
"declare_route",
|
||||
json!({"handle": "road", "label": "The Road", "from": existing(commons), "to": {"ref": "draft", "value": "gate"}, "access": {"access": "public"}, "cost": 1}),
|
||||
),
|
||||
subject("dorra", "Dorra Ironkettle", "person", existing(commons)),
|
||||
subject("brann", "Brannoch Deepvein", "person", existing(commons)),
|
||||
subject("grix", "Grix Sparkfinger", "person", existing(commons)),
|
||||
subject("hilda", "Hilda Gatewright", "person", json!({"ref": "draft", "value": "gate"})),
|
||||
subject("watch", "The Deepgate Watch", "institution", json!({"ref": "draft", "value": "gate"})),
|
||||
]);
|
||||
submit(&scene, CommandBody::AdmitPatch { answers: None, patch }).await;
|
||||
let drafted = snapshot(&scene).await;
|
||||
let (dorra, korr) = (who(&drafted, "Dorra Ironkettle"), who(&drafted, "Korr"));
|
||||
submit(
|
||||
&scene,
|
||||
CommandBody::AdmitPatch {
|
||||
answers: None,
|
||||
patch: batch(&[(
|
||||
"declare_attitude",
|
||||
json!({"holder": existing(dorra), "toward": {"toward": "subject", "of": existing(korr)}, "delta": 80, "basis": {"basis": "prejudice"}, "decay": null}),
|
||||
)]),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let drafted = snapshot(&scene).await;
|
||||
submit(&scene, CommandBody::AdmitPatch { answers: None, patch: install(&drafted).unwrap().patch }).await;
|
||||
submit(&scene, CommandBody::ApproveDraft).await;
|
||||
submit(&scene, CommandBody::ActivateWorld).await;
|
||||
let _ = receipt;
|
||||
scene
|
||||
}
|
||||
|
||||
async fn attack(scene: &Scenario, victim: &str, display: &str) -> Result<(), ghostlight::MailboxError> {
|
||||
let now = snapshot(scene).await;
|
||||
let (korr, victim) = (who(&now, "Korr"), who(&now, victim));
|
||||
let arguments = json!({"target": text(victim), "display": display}).to_string();
|
||||
let (opportunity, invocation) = decode_actor_call(&now, korr, "", "attack", &arguments).expect("the player may attack");
|
||||
scene
|
||||
.world
|
||||
.submit_principal(
|
||||
PrincipalCommandIntent {
|
||||
id: CommandId::new(),
|
||||
world_id: now.world_id,
|
||||
expected_revision: now.revision,
|
||||
body: CommandBody::ExerciseDecision { opportunity, invocation },
|
||||
},
|
||||
&scene.principal,
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
const DEED: &str = "Korr buries his axe in Dorra.";
|
||||
|
||||
fn open_grievances(view: &str) -> String {
|
||||
view.split("Open grievances").nth(1).unwrap().split("\n Persona material").next().unwrap().to_owned()
|
||||
}
|
||||
|
||||
fn between<'a>(text: &'a str, from: &str, to: &str) -> &'a str {
|
||||
let start = text.find(from).unwrap_or_else(|| panic!("`{from}` not in view")) + from.len();
|
||||
let end = start + text[start..].find(to).unwrap_or(text.len() - start);
|
||||
&text[start..end]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nothing_forbids_the_sword_and_the_room_sees_it() {
|
||||
let scene = consequence_world().await;
|
||||
// Dorra is the player's friend, and the attack is admitted all the same.
|
||||
attack(&scene, "Dorra Ironkettle", DEED).await.expect("an attack on a friend is admitted");
|
||||
let view = table_view(&snapshot(&scene).await);
|
||||
let grievances = open_grievances(&view);
|
||||
let seen = between(&grievances, "acts seen by:", "forums covering");
|
||||
for witness in ["Grix Sparkfinger", "Brannoch Deepvein", "Dorra Ironkettle"] {
|
||||
assert!(seen.contains(witness), "{witness} stands in the room and saw it: {seen}");
|
||||
}
|
||||
assert!(!seen.contains("Hilda"), "the gate is out of earshot and out of sight: {seen}");
|
||||
assert!(grievances.contains("Korr"), "{grievances}");
|
||||
assert!(grievances.contains("nothing has answered it yet"), "{grievances}");
|
||||
let subjects = between(&view, "Subjects:", "
|
||||
Affordances");
|
||||
let watch = between(subjects, "The Deepgate Watch [", "holdings");
|
||||
assert!(watch.contains("institution") && !watch.contains("attack"), "an institution is granted no sword: {watch}");
|
||||
let player = between(subjects, "Korr [", "holdings");
|
||||
for verb in VERBS {
|
||||
assert!(player.contains(verb), "the player holds {verb}: {player}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unseen_world_has_no_open_grievance() {
|
||||
let scene = consequence_world().await;
|
||||
assert!(open_grievances(&table_view(&snapshot(&scene).await)).trim().ends_with("none"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn word_spreads_law_presses_and_kin_swear() {
|
||||
let scene = consequence_world().await;
|
||||
attack(&scene, "Dorra Ironkettle", DEED).await.unwrap();
|
||||
let now = snapshot(&scene).await;
|
||||
let view = table_view(&now);
|
||||
let (korr, grix, hilda, brann) =
|
||||
(who(&now, "Korr"), who(&now, "Grix Sparkfinger"), who(&now, "Hilda Gatewright"), who(&now, "Brannoch Deepvein"));
|
||||
let quoted = format!("\"{DEED}\" [");
|
||||
let deed = between(&view, "ed, "]").to_owned();
|
||||
let road = between(&view, "The Road [", "]").to_owned();
|
||||
assert!(!between(&view, &format!("\"{DEED}\" [{deed}]: "), "\n").contains("Hilda"), "the guard has not heard");
|
||||
|
||||
// The witness walks to the gate and tells the guard.
|
||||
rule(&scene, &[("relocate", json!({"subject": existing(grix), "via": existing(road)}))]).await;
|
||||
rule(&scene, &[("communicate", json!({"speaker": existing(grix), "fact": existing(&deed), "to": "colocated"}))]).await;
|
||||
let view = table_view(&snapshot(&scene).await);
|
||||
assert!(between(&view, &format!("\"{DEED}\" [{deed}]: "), "\n").contains("Hilda"), "the guard was told");
|
||||
|
||||
// Believing it, the guard regards the killer worse than a stranger.
|
||||
rule(
|
||||
&scene,
|
||||
&[(
|
||||
"declare_attitude",
|
||||
json!({"holder": existing(hilda), "toward": {"toward": "subject", "of": existing(korr)}, "delta": -60, "basis": {"basis": "rumour", "fact": existing(&deed)}, "decay": null}),
|
||||
)],
|
||||
)
|
||||
.await;
|
||||
let view = table_view(&snapshot(&scene).await);
|
||||
assert!(between(&view, "Regard (", "Persona material").contains("Hilda Gatewright ["), "{view}");
|
||||
|
||||
// The law leans on the player, and the grievance is no longer unanswered.
|
||||
assert!(open_grievances(&view).contains("nothing has answered it yet"));
|
||||
rule(&scene, &[("advance_pressure", json!({"source": {"from": "subject", "of": existing(hilda)}, "target": existing(korr), "by": 30}))]).await;
|
||||
let pressed = open_grievances(&table_view(&snapshot(&scene).await));
|
||||
assert!(between(&pressed, "pressed by:", "reckonings").contains("Hilda Gatewright"), "{pressed}");
|
||||
assert!(!pressed.contains("nothing has answered it yet"), "{pressed}");
|
||||
|
||||
// The victim's kin swear a reckoning with the player as counterparty.
|
||||
rule(
|
||||
&scene,
|
||||
&[(
|
||||
"create_commitment",
|
||||
json!({"subject": existing(brann), "counterparty": existing(korr), "kind": "obligation", "due": 600, "period": null, "checks": [], "statement": "Make Korr answer for Dorra."}),
|
||||
)],
|
||||
)
|
||||
.await;
|
||||
let sworn = open_grievances(&table_view(&snapshot(&scene).await));
|
||||
assert!(between(&sworn, "reckonings sworn against them:", "answered").contains("Brannoch Deepvein"), "{sworn}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_verb_text_refuses_violence() {
|
||||
let lower = serde_json::to_string(&declarations()).unwrap().to_lowercase();
|
||||
assert!(!lower.contains("not allowed to attack"));
|
||||
assert!(lower.find("refuse").is_none_or(|at| !lower[at..].contains("violence")));
|
||||
assert_eq!(declarations().len(), VERBS.len());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -54,19 +54,6 @@ pub struct ProjectorPrompt<'a> {
|
|||
pub word_budget: usize,
|
||||
}
|
||||
|
||||
/// What the storyteller is given to narrate a human player's own view. The
|
||||
/// player is not a Persona: nothing here is lived from inside them.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct NarratorPrompt<'a> {
|
||||
pub player: &'a str,
|
||||
pub typed_context: &'a str,
|
||||
/// What the player wrote this turn: the player's own act, which is not in their own knowledge.
|
||||
pub player_turn: &'a str,
|
||||
pub visible_stimulus: &'a str,
|
||||
pub domain_guidance: &'a str,
|
||||
pub word_budget: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PersonaPrompt<'a> {
|
||||
pub identity: &'a str,
|
||||
|
|
@ -106,43 +93,6 @@ pub fn build_projector_prompt(input: &ProjectorPrompt<'_>) -> String {
|
|||
)
|
||||
}
|
||||
|
||||
/// The storyteller's contract: it tells the player, in second person, what just
|
||||
/// happened and where they now stand, and is never the player or anyone else in
|
||||
/// the story. It is handed facts and told to tell a story from them: the
|
||||
/// context and stimulus are material, not a form to be read down.
|
||||
pub fn build_narrator_prompt(input: &NarratorPrompt<'_>) -> String {
|
||||
format!(
|
||||
"<!-- membrane:{MEMBRANE_SCHEMA}:narrator -->
|
||||
You are the storyteller of a long-running tale, telling the player what has just happened and where they now stand. The player's character is {player}. Speak to the player in the second person, present tense (\"You turn to Mira...\"); never in the first person, and never as {player} or any other character.
|
||||
|
||||
Tell it the way a storyteller at a table would, in a few short paragraphs of plain prose:
|
||||
- Begin with what the player just did, in their own words where they spoke, as theirs (\"You ask...\"), then give what came of it. When people answered or acted, let them: render each reply in that person's own voice, quoting their words exactly as the visible stimulus gives them, with a gesture or a beat of stage business around it, never summarised. Do not invent replies; if no one has answered, say who is looking at you, waiting, or turning away.
|
||||
- Then settle the scene: who is here and what they are doing, the feel of the place, and the ways out worked in naturally (\"the passage toward the Ironmarket\"), the way a person standing there would notice them.
|
||||
- Tell only what the facts below establish. Name only the people, places and routes they name; invent none, and do not say what lies beyond an exit. What the facts leave out is simply not told: never remark that something is unknown, absent, empty or missing, never list what the player has, holds, lacks or has not promised, and never give a number, a count or a cost.
|
||||
- Do not recite. Do not list what the player could do next or close on a menu of options; do not choose actions for the player, expose field names, or claim effects in the world.
|
||||
|
||||
Domain guidance:
|
||||
{guidance}
|
||||
|
||||
Facts about where the player stands:
|
||||
{context}
|
||||
|
||||
What the player did this turn, in their own words:
|
||||
{player_turn}
|
||||
|
||||
What the player has seen and heard (rows marked new are the most recent):
|
||||
{stimulus}
|
||||
|
||||
Use at most {word_budget} words; fewer is better. Return only the telling.",
|
||||
player = input.player,
|
||||
guidance = input.domain_guidance,
|
||||
context = input.typed_context,
|
||||
player_turn = input.player_turn,
|
||||
stimulus = input.visible_stimulus,
|
||||
word_budget = input.word_budget,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn build_persona_prompt(input: &PersonaPrompt<'_>) -> String {
|
||||
format!(
|
||||
"Everything below is prose from inside one person's life. Be that person and respond only from what the moment establishes. Treat asserted perceptions and memories as known. Let anything beyond them appear only as suspicion, conjecture, or deliberate invention by the character, and name it as such. Do not give yourself a temperament, a history, a mood, a relationship, or a turn of phrase the moment did not give you; if the moment gives you little, say little, or nothing. You may speak, remain silent, wonder, decide, or attempt something. Do not announce an outside consequence as already accomplished.\n\nVoice and setting guidance:\n{guidance}\n\nWho you are:\n{identity}\n\nWhat this moment is like for you:\n{stream}\n\nUse at most {word_budget} words; fewer is better. Return only the character's natural response in prose.",
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
@ -1,407 +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,
|
||||
GestaltKnobs, HostedBinding, LaneTokens, 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};
|
||||
|
||||
/// The default knobs' cover: what a manual run spends per tick on cognition
|
||||
/// cells inside one node. The operator's lever on cost is the token cap; the
|
||||
/// partition covers every voice of a due node.
|
||||
const COVER: CoverBudget = CoverBudget {
|
||||
cells: 8,
|
||||
constituent_cap: 8,
|
||||
urgency_slots: 2,
|
||||
};
|
||||
/// Default depth: only the root is open, so every faction speaks as a voice
|
||||
/// of one node at the tick's own rate, the shape of the flat cover.
|
||||
const DEPTH: u8 = 1;
|
||||
/// Default node-turn bound per tick: far above the world's node count.
|
||||
const MAX_NODE_TURNS: u16 = 256;
|
||||
|
||||
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; 9] = [
|
||||
"state",
|
||||
"ticks",
|
||||
"token-cap",
|
||||
"tick-span-minutes",
|
||||
"model",
|
||||
"base-url",
|
||||
"key-file",
|
||||
"depth",
|
||||
"band",
|
||||
];
|
||||
/// Flags a command may omit.
|
||||
const OPTIONAL: [&str; 3] = ["key-file", "depth", "band"];
|
||||
/// Flags that may be given more than once.
|
||||
const REPEATABLE: [&str; 1] = ["band"];
|
||||
|
||||
/// `--name value` pairs from the command's own list, each named once unless it
|
||||
/// is repeatable, in which case its values keep the order given.
|
||||
struct Flags(BTreeMap<&'static str, Vec<String>>);
|
||||
|
||||
impl Flags {
|
||||
fn parse(arguments: &[String], allowed: &[&'static str]) -> Result<Self> {
|
||||
let mut seen: BTreeMap<&'static str, Vec<String>> = 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");
|
||||
};
|
||||
let values = seen.entry(known).or_default();
|
||||
if !values.is_empty() && !REPEATABLE.contains(&known) {
|
||||
bail!("--{known} was given twice");
|
||||
}
|
||||
values.push(value.clone());
|
||||
}
|
||||
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).and_then(|values| values.first()).map_or("", String::as_str)
|
||||
}
|
||||
|
||||
fn all(&self, name: &str) -> &[String] {
|
||||
self.0.get(name).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The run's knobs: the flags over the defaults. With no `--band` the one band
|
||||
/// is the tick span; `--band DIST=MINUTES` gives the period of the nodes
|
||||
/// DIST hops from the focus (the last band is the rest, and a verse tick has no
|
||||
/// focus, so only that one governs). Bands must be given for distances 0, 1, 2
|
||||
/// and so on, with no gap.
|
||||
fn knobs(flags: &Flags, tick_span: TickMinutes) -> Result<GestaltKnobs> {
|
||||
let depth = if flags.0.contains_key("depth") {
|
||||
flags.number::<u8>("depth")?
|
||||
} else {
|
||||
DEPTH
|
||||
};
|
||||
let mut given: BTreeMap<usize, TickMinutes> = BTreeMap::new();
|
||||
for band in flags.all("band") {
|
||||
let parsed = band.split_once('=').and_then(|(distance, minutes)| {
|
||||
Some((distance.parse::<usize>().ok()?, TickMinutes::new(minutes.parse().ok()?)?))
|
||||
});
|
||||
let Some((distance, minutes)) = parsed else {
|
||||
bail!("--band is not DIST=MINUTES with a minutes value inside the clock's span");
|
||||
};
|
||||
if given.insert(distance, minutes).is_some() {
|
||||
bail!("--band names one distance twice");
|
||||
}
|
||||
}
|
||||
let bands = if given.is_empty() {
|
||||
vec![tick_span]
|
||||
} else if given.keys().copied().eq(0..given.len()) {
|
||||
given.into_values().collect()
|
||||
} else {
|
||||
bail!("--band must name distances 0, 1, 2 and so on without a gap");
|
||||
};
|
||||
Ok(GestaltKnobs {
|
||||
bands,
|
||||
depth,
|
||||
max_node_turns: MAX_NODE_TURNS,
|
||||
cover: COVER,
|
||||
})
|
||||
}
|
||||
|
||||
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")?;
|
||||
let knobs = knobs(&flags, tick_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,
|
||||
knobs,
|
||||
};
|
||||
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,
|
||||
// The run's token cap is the wave lane's allowance; the verse runs no
|
||||
// elaborator, so that lane has none.
|
||||
LaneTokens {
|
||||
wave: cap,
|
||||
elaboration: 0,
|
||||
},
|
||||
&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").and_then(|values| values.first()) 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, 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::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::EmptyModelPrefix { .. } => "an inference lane's model prefix is empty",
|
||||
}
|
||||
}
|
||||
|
|
@ -1,490 +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 {
|
||||
run_with(state, responder, ticks, cap, &[])
|
||||
}
|
||||
|
||||
fn run_with(state: &Path, responder: &Responder, ticks: &str, cap: &str, extra: &[&str]) -> Output {
|
||||
let url = responder.url();
|
||||
let mut arguments = vec![
|
||||
"run",
|
||||
"--state",
|
||||
state.to_str().unwrap(),
|
||||
"--ticks",
|
||||
ticks,
|
||||
"--token-cap",
|
||||
cap,
|
||||
"--tick-span-minutes",
|
||||
"60",
|
||||
"--model",
|
||||
"local/scripted",
|
||||
"--base-url",
|
||||
&url,
|
||||
];
|
||||
arguments.extend_from_slice(extra);
|
||||
verse(&arguments)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_run_takes_depth_and_band_flags_and_reports_by_node() {
|
||||
let state = tempfile::tempdir().unwrap();
|
||||
assert!(genesis(state.path()).status.success());
|
||||
let responder = Responder::start();
|
||||
let output = run_with(
|
||||
state.path(),
|
||||
&responder,
|
||||
"1",
|
||||
"1000000",
|
||||
&["--depth", "8", "--band", "0=60", "--band", "1=240"],
|
||||
);
|
||||
assert!(output.status.success(), "{}", stderr(&output));
|
||||
let text = stdout(&output);
|
||||
// Opened to every institution, each faction is its own node; with no focus
|
||||
// each sits at the last band's index.
|
||||
for faction in ["Adrasteia", "Brannoch"] {
|
||||
assert!(text.contains(&format!(" node {faction} (distance 1): ")), "{text}");
|
||||
}
|
||||
assert!(text.contains("tick 0 closed: 2 cells, 2 acts, 0 refused\n"), "{text}");
|
||||
}
|
||||
|
||||
#[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); 11] = [
|
||||
(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",
|
||||
),
|
||||
(
|
||||
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", "--band", "1=60",
|
||||
],
|
||||
"--band must name distances 0, 1, 2",
|
||||
),
|
||||
(
|
||||
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", "--depth", "0",
|
||||
],
|
||||
"--depth is not a positive integer",
|
||||
),
|
||||
];
|
||||
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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -7,12 +7,11 @@ license.workspace = true
|
|||
[dependencies]
|
||||
async-trait.workspace = true
|
||||
chrono.workspace = true
|
||||
model-connector.workspace = true
|
||||
codex-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
|
||||
|
|
@ -20,15 +19,8 @@ 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"
|
||||
|
|
|
|||
|
|
@ -928,14 +928,6 @@ fn lower(
|
|||
source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)),
|
||||
target: subject(0)?,
|
||||
},
|
||||
// The regarded subject is the actor, so a proposer cannot aim one
|
||||
// person's grudge at a third party; the delta is the entry's.
|
||||
ComponentOpKind::AdjustAttitude { delta, decay } => patch::ComponentOp::AdjustAttitude {
|
||||
holder: subject(0)?,
|
||||
toward: patch::Ref::Existing(actor),
|
||||
delta: *delta,
|
||||
decay: *decay,
|
||||
},
|
||||
ComponentOpKind::Relocate => patch::ComponentOp::Relocate {
|
||||
subject: subject(0)?,
|
||||
via: edge(1)?,
|
||||
|
|
@ -2842,8 +2834,7 @@ mod tests {
|
|||
| ComponentOpKind::CreateCommitment { .. }
|
||||
| ComponentOpKind::AdvancePressure { .. }
|
||||
| ComponentOpKind::ReducePressure { .. }
|
||||
| ComponentOpKind::ResolvePressure
|
||||
| ComponentOpKind::AdjustAttitude { .. } => false,
|
||||
| ComponentOpKind::ResolvePressure => false,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
@ -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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,313 +0,0 @@
|
|||
//! Attitude: how one subject regards another, as typed kernel state.
|
||||
//!
|
||||
//! The kernel stores *modifiers*, never an opinion. Each is a sourced, bounded,
|
||||
//! possibly fading term (the Crusader Kings shape); `opinion` derives the sum on
|
||||
//! demand and nothing stores it. A modifier points at one subject, or at a
|
||||
//! *trait* (species, faction, a look, a rumour about a person) and a trait
|
||||
//! modifier is prejudice: it applies to a subject only while the holder knows,
|
||||
//! at `Believed` or better, a fact the world declared as evidence that the
|
||||
//! subject carries that trait. A prejudice against outlanders does nothing to a
|
||||
//! stranger the holder has never learned is one.
|
||||
//!
|
||||
//! The reducer is the only writer: `ResolvedOp::AdjustAttitude` and
|
||||
//! `ResolvedOp::DeclareTrait` land here, through patches and affordance
|
||||
//! effects. Persona prose, the narrator, and host code write nothing.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::clock::{FictionalMinutes, TickMinutes};
|
||||
use super::patch::{Confidence, Ref};
|
||||
use super::{CommandId, EntityId, SubjectId, WorldState};
|
||||
|
||||
/// The bound on one stored modifier and on a derived opinion: a grudge or a
|
||||
/// fondness saturates here, so no run of insults reaches an unrecoverable
|
||||
/// number and the model-facing schema can say the range.
|
||||
pub(crate) const MAX_ATTITUDE: i16 = 100;
|
||||
|
||||
/// How many of an opinion's causes a view names. The rest are summed in.
|
||||
pub(crate) const OPINION_CAUSES_SHOWN: usize = 3;
|
||||
|
||||
/// World-declared canonical text, kernel-opaque, `[a-z][a-z0-9_]{0,47}`: the
|
||||
/// same shape as an authority kind, because it is the same kind of word.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(transparent)]
|
||||
pub(crate) struct TraitName(pub(crate) String);
|
||||
|
||||
/// What a modifier regards.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(tag = "toward", content = "of", rename_all = "snake_case")]
|
||||
pub(crate) enum AttitudeToward {
|
||||
Subject(SubjectId),
|
||||
Trait(TraitName),
|
||||
}
|
||||
|
||||
/// Why a modifier exists. `Grievance` and `Favor` name the command that did the
|
||||
/// deed, so one act is one row and two acts are two. `Rumour` is a belief the
|
||||
/// holder acted on, and holds only while the holder still knows its fact.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(tag = "cause", rename_all = "snake_case")]
|
||||
pub(crate) enum AttitudeCause {
|
||||
Prejudice,
|
||||
Grievance { command: CommandId },
|
||||
Favor { command: CommandId },
|
||||
Rumour { fact: EntityId },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct AttitudeKey {
|
||||
pub(crate) toward: AttitudeToward,
|
||||
pub(crate) cause: AttitudeCause,
|
||||
}
|
||||
|
||||
/// Nonzero and within `MAX_ATTITUDE` by construction of every writer. `since`
|
||||
/// is the world clock at the last write; with `decay` it sets how the term
|
||||
/// fades, and with none the term is permanent.
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct AttitudeModifier {
|
||||
pub(crate) delta: i16,
|
||||
pub(crate) since: FictionalMinutes,
|
||||
pub(crate) decay: Option<TickMinutes>,
|
||||
}
|
||||
|
||||
/// The proposal-time twin of [`AttitudeToward`].
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(tag = "toward", content = "of", rename_all = "snake_case")]
|
||||
pub(crate) enum AttitudeTowardRef {
|
||||
Subject(Ref<SubjectId>),
|
||||
Trait(TraitName),
|
||||
}
|
||||
|
||||
/// What an authored declaration rests on. A deed is not one of these: a deed
|
||||
/// is `AdjustAttitude`, whose cause the kernel derives from the command.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[serde(tag = "basis", rename_all = "snake_case")]
|
||||
pub(crate) enum AttitudeBasisRef {
|
||||
Prejudice,
|
||||
Rumour { fact: Ref<EntityId> },
|
||||
}
|
||||
|
||||
/// One cause of a derived opinion, with the delta it contributes right now.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct OpinionCause {
|
||||
pub(crate) toward: AttitudeToward,
|
||||
pub(crate) cause: AttitudeCause,
|
||||
pub(crate) delta: i32,
|
||||
}
|
||||
|
||||
/// Holder's regard for one subject: the clamped sum and its causes, strongest
|
||||
/// first. Derived, never stored.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Opinion {
|
||||
pub(crate) total: i32,
|
||||
pub(crate) causes: Vec<OpinionCause>,
|
||||
}
|
||||
|
||||
/// A modifier's contribution at `now`: a decaying term fades linearly to zero
|
||||
/// across its period, truncating toward zero.
|
||||
fn effective(modifier: &AttitudeModifier, now: FictionalMinutes) -> i32 {
|
||||
let delta = i64::from(modifier.delta);
|
||||
match modifier.decay {
|
||||
None => delta as i32,
|
||||
Some(period) => {
|
||||
let span = i64::from(period.minutes());
|
||||
let elapsed = i64::try_from(now.since(modifier.since)).unwrap_or(i64::MAX);
|
||||
if elapsed >= span {
|
||||
0
|
||||
} else {
|
||||
(delta * (span - elapsed) / span) as i32
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `holder` holds `fact` at `Believed` or better. A doubted rumour
|
||||
/// moves nobody.
|
||||
fn believes(state: &WorldState, holder: SubjectId, fact: EntityId) -> bool {
|
||||
state
|
||||
.knowledge
|
||||
.get(&holder)
|
||||
.and_then(|held| held.get(&fact))
|
||||
.is_some_and(|entry| entry.confidence >= Confidence::Believed)
|
||||
}
|
||||
|
||||
/// Whether the modifier at `key` applies to `subject` for `holder` right now.
|
||||
fn applies(state: &WorldState, holder: SubjectId, key: &AttitudeKey, subject: SubjectId) -> bool {
|
||||
let reaches = match &key.toward {
|
||||
AttitudeToward::Subject(target) => *target == subject,
|
||||
AttitudeToward::Trait(name) => state
|
||||
.traits
|
||||
.get(&subject)
|
||||
.and_then(|carried| carried.get(name))
|
||||
.is_some_and(|evidence| evidence.iter().any(|fact| believes(state, holder, *fact))),
|
||||
};
|
||||
reaches
|
||||
&& match &key.cause {
|
||||
AttitudeCause::Rumour { fact } => believes(state, holder, *fact),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// `holder`'s opinion of `subject`: every applicable modifier, summed and
|
||||
/// clamped. Causes with no remaining weight are dropped; ordered by strength,
|
||||
/// then by key, so the answer is deterministic.
|
||||
pub(crate) fn opinion(state: &WorldState, holder: SubjectId, subject: SubjectId) -> Opinion {
|
||||
let mut causes: Vec<(&AttitudeKey, OpinionCause)> = state
|
||||
.attitudes
|
||||
.get(&holder)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|(key, _)| applies(state, holder, key, subject))
|
||||
.map(|(key, modifier)| {
|
||||
(
|
||||
key,
|
||||
OpinionCause {
|
||||
toward: key.toward.clone(),
|
||||
cause: key.cause.clone(),
|
||||
delta: effective(modifier, state.now),
|
||||
},
|
||||
)
|
||||
})
|
||||
.filter(|(_, cause)| cause.delta != 0)
|
||||
.collect();
|
||||
causes.sort_by(|(left_key, left), (right_key, right)| {
|
||||
right
|
||||
.delta
|
||||
.abs()
|
||||
.cmp(&left.delta.abs())
|
||||
.then_with(|| left_key.cmp(right_key))
|
||||
});
|
||||
let total = causes
|
||||
.iter()
|
||||
.map(|(_, cause)| cause.delta)
|
||||
.sum::<i32>()
|
||||
.clamp(-i32::from(MAX_ATTITUDE), i32::from(MAX_ATTITUDE));
|
||||
Opinion {
|
||||
total,
|
||||
causes: causes.into_iter().map(|(_, cause)| cause).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every subject `holder` has a nonzero opinion of, in subject order. The
|
||||
/// candidates come from the holder's own rows, so the cost follows what the
|
||||
/// holder feels, never the size of the world.
|
||||
pub(crate) fn opinions_held(state: &WorldState, holder: SubjectId) -> BTreeMap<SubjectId, Opinion> {
|
||||
let Some(rows) = state.attitudes.get(&holder) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let mut candidates: BTreeSet<SubjectId> = BTreeSet::new();
|
||||
for key in rows.keys() {
|
||||
match &key.toward {
|
||||
AttitudeToward::Subject(target) => {
|
||||
candidates.insert(*target);
|
||||
}
|
||||
AttitudeToward::Trait(name) => candidates.extend(
|
||||
state
|
||||
.traits
|
||||
.iter()
|
||||
.filter(|(_, carried)| carried.contains_key(name))
|
||||
.map(|(subject, _)| *subject),
|
||||
),
|
||||
}
|
||||
}
|
||||
candidates
|
||||
.into_iter()
|
||||
.map(|subject| (subject, opinion(state, holder, subject)))
|
||||
.filter(|(_, held)| !held.causes.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The write: add `delta` to the modifier at `key`, saturating at
|
||||
/// `MAX_ATTITUDE`, and restamp it. A modifier summed to zero is removed, so
|
||||
/// absence is the only zero. Saturation at the bound is a legal write that
|
||||
/// renews the term, which is what a grudge piling on a grudge is.
|
||||
pub(crate) fn adjust(
|
||||
state: &mut WorldState,
|
||||
holder: SubjectId,
|
||||
key: AttitudeKey,
|
||||
delta: i16,
|
||||
decay: Option<TickMinutes>,
|
||||
) {
|
||||
let held = state.attitudes.entry(holder).or_default();
|
||||
let current = held.get(&key).map_or(0, |modifier| i32::from(modifier.delta));
|
||||
let next = (current + i32::from(delta))
|
||||
.clamp(-i32::from(MAX_ATTITUDE), i32::from(MAX_ATTITUDE)) as i16;
|
||||
if next == 0 {
|
||||
held.remove(&key);
|
||||
if held.is_empty() {
|
||||
state.attitudes.remove(&holder);
|
||||
}
|
||||
} else {
|
||||
held.insert(
|
||||
key,
|
||||
AttitudeModifier {
|
||||
delta: next,
|
||||
since: state.now,
|
||||
decay,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The deed's cause: a fall in regard is a grievance and a rise is a favor,
|
||||
/// both named for the command that did it.
|
||||
pub(crate) fn deed_cause(delta: i16, command: CommandId) -> AttitudeCause {
|
||||
if delta < 0 {
|
||||
AttitudeCause::Grievance { command }
|
||||
} else {
|
||||
AttitudeCause::Favor { command }
|
||||
}
|
||||
}
|
||||
|
||||
/// A delta an author or a world may write: nonzero, within the bound.
|
||||
pub(crate) fn is_valid_delta(delta: i16) -> bool {
|
||||
delta != 0 && delta.unsigned_abs() <= MAX_ATTITUDE.unsigned_abs()
|
||||
}
|
||||
|
||||
/// A fade the clock can carry: one minute to a year, the span bound every
|
||||
/// other period in the kernel obeys. `TickMinutes` is transparent in serde, so
|
||||
/// a decoded zero is possible and refused here.
|
||||
pub(crate) fn is_valid_decay(decay: Option<TickMinutes>) -> bool {
|
||||
decay.is_none_or(|span| TickMinutes::new(span.minutes()).is_some())
|
||||
}
|
||||
|
||||
/// The one wording of a derived opinion's size, so the Dungeon Master's table,
|
||||
/// a Persona's own view, and the narrator name the same feeling for the same
|
||||
/// number. Reads after "regards them with".
|
||||
pub(crate) fn regard_word(total: i32) -> &'static str {
|
||||
match total {
|
||||
..=-70 => "hatred",
|
||||
-69..=-35 => "hostility",
|
||||
-34..=-10 => "resentment",
|
||||
-9..=9 => "indifference",
|
||||
10..=34 => "liking",
|
||||
35..=69 => "warmth",
|
||||
_ => "devotion",
|
||||
}
|
||||
}
|
||||
|
||||
/// One cause as a clause a reader can act on. The statement of a rumour is the
|
||||
/// fact the holder believes, resolved by the caller from its own view.
|
||||
pub(crate) fn describe_cause(
|
||||
cause: &OpinionCause,
|
||||
fact_statement: impl Fn(EntityId) -> Option<String>,
|
||||
) -> String {
|
||||
let weight = format!("{:+}", cause.delta);
|
||||
match (&cause.cause, &cause.toward) {
|
||||
(AttitudeCause::Prejudice, AttitudeToward::Trait(name)) => {
|
||||
format!("prejudice toward the {} ({weight})", name.0)
|
||||
}
|
||||
(AttitudeCause::Prejudice, AttitudeToward::Subject(_)) => {
|
||||
format!("a feeling it cannot account for ({weight})")
|
||||
}
|
||||
(AttitudeCause::Grievance { .. }, _) => format!("a grievance ({weight})"),
|
||||
(AttitudeCause::Favor { .. }, _) => format!("a favor owed ({weight})"),
|
||||
(AttitudeCause::Rumour { fact }, _) => match fact_statement(*fact) {
|
||||
Some(statement) => format!("a rumour it believes, \"{statement}\" ({weight})"),
|
||||
None => format!("a rumour it believes ({weight})"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -1,670 +0,0 @@
|
|||
//! Attitude is kernel state: sourced modifiers, a derived opinion, prejudice
|
||||
//! gated on what the holder knows. Every test here goes through the reducer's
|
||||
//! own doors (a patch or an affordance) and reads the derived opinion back.
|
||||
|
||||
use super::*;
|
||||
use crate::attitude::{self, AttitudeCause, AttitudeToward};
|
||||
use crate::attitude::{AttitudeBasisRef, AttitudeTowardRef, TraitName};
|
||||
|
||||
const OUTLANDER: &str = "The farmer came over the pass from the outland.";
|
||||
|
||||
fn play_patch(
|
||||
kernel: &mut WorldKernel,
|
||||
patch: WorldPatch,
|
||||
) -> Result<SubmitReceipt, KernelError> {
|
||||
submit_as(
|
||||
kernel,
|
||||
play_caller(),
|
||||
CommandBody::AdmitPatch {
|
||||
answers: None,
|
||||
patch,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn fact_with(kernel: &WorldKernel, statement: &str) -> EntityId {
|
||||
*kernel
|
||||
.state
|
||||
.facts
|
||||
.iter()
|
||||
.find(|(_, record)| record.statement.as_str() == statement)
|
||||
.expect("the declared fact")
|
||||
.0
|
||||
}
|
||||
|
||||
fn ruled_fact(handle: &str, statement: &str) -> Declaration {
|
||||
Declaration::Fact(FactDeclaration {
|
||||
handle: DraftHandle::new(handle),
|
||||
label: "A ruling".into(),
|
||||
statement: Statement::new(statement).unwrap(),
|
||||
standing: FactStandingRef::Ruled,
|
||||
})
|
||||
}
|
||||
|
||||
fn learn(
|
||||
kernel: &mut WorldKernel,
|
||||
subject: SubjectId,
|
||||
fact: EntityId,
|
||||
confidence: Confidence,
|
||||
) -> Result<SubmitReceipt, KernelError> {
|
||||
play_patch(
|
||||
kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![ComponentOp::AcquireKnowledge {
|
||||
subject: Ref::Existing(subject),
|
||||
fact: Ref::Existing(fact),
|
||||
source: AuthoredSource::Witnessed,
|
||||
confidence,
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn regard(kernel: &WorldKernel, holder: SubjectId, subject: SubjectId) -> attitude::Opinion {
|
||||
attitude::opinion(&kernel.state, holder, subject)
|
||||
}
|
||||
|
||||
/// A reeve who is prejudiced against outlanders, and a farmer who is one.
|
||||
fn outlander_world(path: &Path) -> (WorldKernel, Clockwork, EntityId) {
|
||||
let (mut kernel, clockwork, _) = clock_kernel(path, "Outlanders");
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: vec![ruled_fact("outland", OUTLANDER)],
|
||||
operations: vec![
|
||||
ComponentOp::DeclareTrait {
|
||||
subject: Ref::Existing(clockwork.farmer),
|
||||
name: TraitName("outlander".into()),
|
||||
fact: Ref::Draft(DraftHandle::new("outland")),
|
||||
},
|
||||
ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
|
||||
delta: -40,
|
||||
basis: AttitudeBasisRef::Prejudice,
|
||||
decay: None,
|
||||
},
|
||||
],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("the play authority declares the trait and the prejudice");
|
||||
let fact = fact_with(&kernel, OUTLANDER);
|
||||
(kernel, clockwork, fact)
|
||||
}
|
||||
|
||||
/// A world-authored `insult`: the target comes to regard the actor 30 lower.
|
||||
fn grant_insult(kernel: &mut WorldKernel, to: SubjectId, delta: i16, decay: Option<TickMinutes>) {
|
||||
play_patch(
|
||||
kernel,
|
||||
WorldPatch {
|
||||
declarations: vec![Declaration::Affordance(AffordanceDeclaration {
|
||||
handle: DraftHandle::new("insult"),
|
||||
kind: AffordanceKindName("insult".into()),
|
||||
roles: vec![RoleSpec {
|
||||
role: Role("target".into()),
|
||||
kind: RefKind::Subject(None),
|
||||
}],
|
||||
preconditions: Vec::new(),
|
||||
effect_slots: vec![EffectSlot {
|
||||
op_kind: ComponentOpKind::AdjustAttitude { delta, decay },
|
||||
roles: vec![Role("target".into())],
|
||||
bounds: Bounds::None,
|
||||
}],
|
||||
outcome_bands: vec![OutcomeBand {
|
||||
weight: 1,
|
||||
effects: vec![0],
|
||||
}],
|
||||
carries_speech: false,
|
||||
})],
|
||||
operations: vec![ComponentOp::GrantAffordance {
|
||||
subject: Ref::Existing(to),
|
||||
affordance: Ref::Draft(DraftHandle::new("insult")),
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("the world authors and grants the verb");
|
||||
}
|
||||
|
||||
fn insult_id(kernel: &WorldKernel) -> AffordanceId {
|
||||
*kernel
|
||||
.state
|
||||
.affordance_catalog
|
||||
.iter()
|
||||
.find(|(_, entry)| entry.kind.0 == "insult")
|
||||
.expect("the insult entry")
|
||||
.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prejudice_needs_belief() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
|
||||
|
||||
// The holder has not heard the farmer is an outlander: no opinion at all.
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
assert!(kernel.snapshot().unwrap().subjects.iter().all(|s| s.opinions.is_empty()));
|
||||
|
||||
// Somebody else knowing it does not move the reeve.
|
||||
learn(&mut kernel, clockwork.treasury, fact, Confidence::Certain).unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
|
||||
// A doubted telling does not either.
|
||||
learn(&mut kernel, clockwork.reeve, fact, Confidence::Doubted).unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
|
||||
// Believed, it does, for the farmer and for nobody who is not one.
|
||||
learn(&mut kernel, clockwork.reeve, fact, Confidence::Believed).unwrap();
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -40);
|
||||
assert_eq!(held.causes[0].cause, AttitudeCause::Prejudice);
|
||||
assert_eq!(
|
||||
held.causes[0].toward,
|
||||
AttitudeToward::Trait(TraitName("outlander".into()))
|
||||
);
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.treasury).total, 0);
|
||||
assert_eq!(
|
||||
regard(&kernel, clockwork.farmer, clockwork.reeve).total,
|
||||
0,
|
||||
"regard does not run backward"
|
||||
);
|
||||
|
||||
// Forgetting it lifts the prejudice: the opinion is derived, not stored.
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![ComponentOp::Forget {
|
||||
subject: Ref::Existing(clockwork.reeve),
|
||||
fact: Ref::Existing(fact),
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grievance_from_an_act() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Grievance");
|
||||
grant_insult(&mut kernel, clockwork.farmer, -30, None);
|
||||
let insult = insult_id(&kernel);
|
||||
|
||||
exercise(
|
||||
&mut kernel,
|
||||
clockwork.farmer,
|
||||
insult,
|
||||
vec![binding("target", Target::Subject(clockwork.reeve))],
|
||||
)
|
||||
.expect("the insult commits");
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -30);
|
||||
assert!(matches!(
|
||||
held.causes[0].cause,
|
||||
AttitudeCause::Grievance { .. }
|
||||
));
|
||||
assert_eq!(
|
||||
regard(&kernel, clockwork.farmer, clockwork.reeve).total,
|
||||
0,
|
||||
"the insulter does not come to resent the insulted"
|
||||
);
|
||||
|
||||
// A second insult is a second act with its own cause; they add.
|
||||
exercise(
|
||||
&mut kernel,
|
||||
clockwork.farmer,
|
||||
insult,
|
||||
vec![binding("target", Target::Subject(clockwork.reeve))],
|
||||
)
|
||||
.unwrap();
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -60);
|
||||
assert_eq!(held.causes.len(), 2);
|
||||
assert_ne!(held.causes[0].cause, held.causes[1].cause);
|
||||
|
||||
// A favor is the same write with the other sign.
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: Ref::Existing(clockwork.farmer),
|
||||
delta: 20,
|
||||
decay: None,
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -40);
|
||||
assert!(
|
||||
held.causes
|
||||
.iter()
|
||||
.any(|cause| matches!(cause.cause, AttitudeCause::Favor { .. }) && cause.delta == 20)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regard_saturates_at_the_bound_and_a_clamped_write_is_not_an_error() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Saturation");
|
||||
let wrong = |delta| ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: Ref::Existing(clockwork.farmer),
|
||||
delta,
|
||||
decay: None,
|
||||
};
|
||||
// Three deeds in one command are one row of the same cause, clamped.
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![wrong(-60), wrong(-60), wrong(-60)],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("a saturated write still commits");
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -100);
|
||||
assert_eq!(held.causes.len(), 1);
|
||||
|
||||
// Separate commands pile past one row, and the opinion still clamps.
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![wrong(-60)],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_decaying_term_fades_and_a_grudge_does_not() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Decay");
|
||||
let write = |delta, decay| ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: Ref::Existing(clockwork.farmer),
|
||||
delta,
|
||||
decay,
|
||||
};
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![write(-40, Some(minutes(100)))],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![write(20, None)],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -20);
|
||||
tick(&mut kernel, 50).unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
tick(&mut kernel, 50).unwrap();
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, 20, "the faded grievance is gone, the favor stays");
|
||||
assert_eq!(held.causes.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rumour_moves_only_a_holder_who_believes_it() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Rumour");
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: vec![ruled_fact("tale", "They say the farmer poisoned a well.")],
|
||||
operations: vec![ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: AttitudeTowardRef::Subject(Ref::Existing(clockwork.farmer)),
|
||||
delta: -25,
|
||||
basis: AttitudeBasisRef::Rumour {
|
||||
fact: Ref::Draft(DraftHandle::new("tale")),
|
||||
},
|
||||
decay: None,
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let tale = fact_with(&kernel, "They say the farmer poisoned a well.");
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||
learn(&mut kernel, clockwork.reeve, tale, Confidence::Believed).unwrap();
|
||||
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||
assert_eq!(held.total, -25);
|
||||
assert_eq!(held.causes[0].cause, AttitudeCause::Rumour { fact: tale });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attitude_writes_with_no_meaning_are_refused_whole() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
|
||||
let before = kernel.state.clone();
|
||||
let adjust = |delta, holder, toward| ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(holder),
|
||||
toward: Ref::Existing(toward),
|
||||
delta,
|
||||
decay: None,
|
||||
};
|
||||
let refused: Vec<(&str, ComponentOp)> = vec![
|
||||
("zero delta", adjust(0, clockwork.reeve, clockwork.farmer)),
|
||||
("past the bound", adjust(101, clockwork.reeve, clockwork.farmer)),
|
||||
("regarding oneself", adjust(-5, clockwork.reeve, clockwork.reeve)),
|
||||
(
|
||||
"a zero decay",
|
||||
ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: Ref::Existing(clockwork.farmer),
|
||||
delta: -5,
|
||||
decay: serde_json::from_value(serde_json::json!(0)).unwrap(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"a rumour of a trait",
|
||||
ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
|
||||
delta: -5,
|
||||
basis: AttitudeBasisRef::Rumour {
|
||||
fact: Ref::Existing(fact),
|
||||
},
|
||||
decay: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
"a trait that is not a name",
|
||||
ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: AttitudeTowardRef::Trait(TraitName("Not A Name".into())),
|
||||
delta: -5,
|
||||
basis: AttitudeBasisRef::Prejudice,
|
||||
decay: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
"a trait declared with a bad name",
|
||||
ComponentOp::DeclareTrait {
|
||||
subject: Ref::Existing(clockwork.farmer),
|
||||
name: TraitName("".into()),
|
||||
fact: Ref::Existing(fact),
|
||||
},
|
||||
),
|
||||
];
|
||||
for (name, operation) in refused {
|
||||
let error = play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![operation],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect_err(name);
|
||||
assert!(
|
||||
format!("{error:?}").contains("InvalidAttitude"),
|
||||
"{name}: {error:?}"
|
||||
);
|
||||
}
|
||||
// An affordance whose delta is nothing is refused at declaration.
|
||||
let error = play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: vec![Declaration::Affordance(AffordanceDeclaration {
|
||||
handle: DraftHandle::new("nothing"),
|
||||
kind: AffordanceKindName("nothing".into()),
|
||||
roles: vec![RoleSpec {
|
||||
role: Role("target".into()),
|
||||
kind: RefKind::Subject(None),
|
||||
}],
|
||||
preconditions: Vec::new(),
|
||||
effect_slots: vec![EffectSlot {
|
||||
op_kind: ComponentOpKind::AdjustAttitude {
|
||||
delta: 0,
|
||||
decay: None,
|
||||
},
|
||||
roles: vec![Role("target".into())],
|
||||
bounds: Bounds::None,
|
||||
}],
|
||||
outcome_bands: vec![OutcomeBand {
|
||||
weight: 1,
|
||||
effects: vec![0],
|
||||
}],
|
||||
carries_speech: false,
|
||||
})],
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect_err("an entry that changes no regard");
|
||||
assert!(format!("{error:?}").contains("InvalidAttitude"), "{error:?}");
|
||||
assert_eq!(kernel.state, before, "a refused write leaves no trace");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_derived_opinion_and_its_causes_reach_the_tables_view() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
|
||||
grant_insult(&mut kernel, clockwork.farmer, -30, None);
|
||||
let insult = insult_id(&kernel);
|
||||
learn(&mut kernel, clockwork.reeve, fact, Confidence::Believed).unwrap();
|
||||
exercise(
|
||||
&mut kernel,
|
||||
clockwork.farmer,
|
||||
insult,
|
||||
vec![binding("target", Target::Subject(clockwork.reeve))],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let snapshot = kernel.snapshot().unwrap();
|
||||
let reeve = snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|subject| subject.id == clockwork.reeve)
|
||||
.unwrap();
|
||||
assert_eq!(reeve.opinions.len(), 1);
|
||||
assert_eq!(reeve.opinions[0].toward, clockwork.farmer);
|
||||
assert_eq!(reeve.opinions[0].total, -70);
|
||||
assert_eq!(reeve.opinions[0].causes.len(), 2);
|
||||
|
||||
let view = crate::table_view(&snapshot);
|
||||
let line = view
|
||||
.split("Regard")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split("Persona material").next())
|
||||
.expect("the table has a regard section");
|
||||
assert!(line.contains("The Yard Reeve"), "{line}");
|
||||
assert!(line.contains("regards The Yard Farmer"), "{line}");
|
||||
assert!(line.contains("with hatred (-70)"), "{line}");
|
||||
assert!(line.contains("(-70)"), "{line}");
|
||||
assert!(line.contains("a grievance (-30)"), "{line}");
|
||||
assert!(line.contains("prejudice toward the outlander (-40)"), "{line}");
|
||||
}
|
||||
|
||||
/// An act the room saw: the same invocation as `exercise`, with the actor's own
|
||||
/// words for what everyone present watched.
|
||||
fn exercise_displaying(
|
||||
kernel: &mut WorldKernel,
|
||||
actor: SubjectId,
|
||||
affordance: AffordanceId,
|
||||
bindings: Vec<RoleBinding>,
|
||||
display: &str,
|
||||
) -> Result<SubmitReceipt, KernelError> {
|
||||
let snapshot = kernel.snapshot().unwrap();
|
||||
let opportunity = opportunity_for(&snapshot, actor);
|
||||
let caller = CallerId::Controller(opportunity.controller_id);
|
||||
kernel.submit(
|
||||
command(
|
||||
&snapshot,
|
||||
CommandId::new(),
|
||||
caller.clone(),
|
||||
CommandBody::ExerciseDecision {
|
||||
opportunity,
|
||||
invocation: DecisionInvocation {
|
||||
affordance,
|
||||
bindings,
|
||||
proposed: vec![ProposedEffect {
|
||||
slot: 0,
|
||||
magnitude: Magnitude::None,
|
||||
}],
|
||||
speech: None,
|
||||
display: Some(Statement::new(display).unwrap()),
|
||||
},
|
||||
},
|
||||
),
|
||||
&AuthenticatedCaller::fixture(caller),
|
||||
)
|
||||
}
|
||||
|
||||
use crate::clock::FictionalMinutes;
|
||||
use crate::patch::{CommitmentKind, PressureMagnitude};
|
||||
|
||||
const BLOW: &str = "The farmer strikes the reeve.";
|
||||
|
||||
/// The view's Open grievances block, alone.
|
||||
fn open_grievances(kernel: &WorldKernel) -> String {
|
||||
let view = crate::table_view(&kernel.snapshot().unwrap());
|
||||
view.split("Open grievances")
|
||||
.nth(1)
|
||||
.expect("the view always carries the block")
|
||||
.split("\n Persona material")
|
||||
.next()
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
fn segment<'a>(text: &'a str, from: &str, to: &str) -> &'a str {
|
||||
let start = text.find(from).unwrap_or_else(|| panic!("`{from}` missing in {text}")) + from.len();
|
||||
let end = start + text[start..].find(to).unwrap_or(text.len() - start);
|
||||
&text[start..end]
|
||||
}
|
||||
|
||||
fn strike(kernel: &mut WorldKernel, clockwork: &Clockwork, delta: i16) {
|
||||
grant_insult(kernel, clockwork.farmer, delta, None);
|
||||
let insult = insult_id(kernel);
|
||||
exercise_displaying(
|
||||
kernel,
|
||||
clockwork.farmer,
|
||||
insult,
|
||||
vec![binding("target", Target::Subject(clockwork.reeve))],
|
||||
BLOW,
|
||||
)
|
||||
.expect("the blow commits");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deed_the_room_saw_is_an_open_grievance_until_something_answers_it() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Open grievances");
|
||||
assert!(open_grievances(&kernel).trim().ends_with("none"));
|
||||
|
||||
strike(&mut kernel, &clockwork, -30);
|
||||
let block = open_grievances(&kernel);
|
||||
assert_eq!(block.matches("; acts seen by:").count(), 1, "one doer, no other: {block}");
|
||||
assert!(block.contains("The Yard Farmer"), "{block}");
|
||||
assert!(segment(&block, "wronged", ";").contains("The Yard Reeve"), "{block}");
|
||||
let seen = segment(&block, "acts seen by:", "forums covering");
|
||||
assert!(seen.contains("The Yard Reeve") && seen.contains(BLOW), "{seen}");
|
||||
assert!(!seen.contains("The Yard Farmer"), "the doer is not their own witness: {seen}");
|
||||
assert!(segment(&block, "forums covering them:", ";").contains("none"), "{block}");
|
||||
assert!(segment(&block, "pressed by:", ";").contains("no one"), "{block}");
|
||||
assert!(segment(&block, "reckonings sworn against them:", ";").contains("none"), "{block}");
|
||||
assert!(block.contains("nothing has answered it yet"), "{block}");
|
||||
|
||||
// Someone leans on the doer: answered, and the pressure is named with its weight.
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![ComponentOp::AdvancePressure {
|
||||
source: PressureSourceRef::Subject(Ref::Existing(clockwork.reeve)),
|
||||
target: Ref::Existing(clockwork.farmer),
|
||||
by: PressureMagnitude(30),
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let block = open_grievances(&kernel);
|
||||
let pressed = segment(&block, "pressed by:", ";");
|
||||
assert!(pressed.contains("The Yard Reeve") && pressed.contains("(30)"), "{pressed}");
|
||||
assert!(block.contains("answered so far") && !block.contains("nothing has answered"), "{block}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sworn_reckoning_answers_a_grievance_and_a_favour_opens_none() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Reckoning");
|
||||
strike(&mut kernel, &clockwork, -30);
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![ComponentOp::CreateCommitment {
|
||||
subject: Ref::Existing(clockwork.reeve),
|
||||
counterparty: Some(Ref::Existing(clockwork.farmer)),
|
||||
kind: CommitmentKind::Obligation,
|
||||
due: FictionalMinutes(600),
|
||||
period: None,
|
||||
checks: Vec::new(),
|
||||
statement: Statement::new("Make the farmer answer for the blow.").unwrap(),
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let block = open_grievances(&kernel);
|
||||
let sworn = segment(&block, "reckonings sworn against them:", "answered");
|
||||
assert!(sworn.contains("The Yard Reeve") && sworn.contains("Make the farmer answer"), "{sworn}");
|
||||
assert!(segment(&block, "pressed by:", ";").contains("no one"), "{block}");
|
||||
assert!(block.contains("answered so far"), "{block}");
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kindly, clockwork, _) = clock_kernel(directory.path(), "Favour");
|
||||
strike(&mut kindly, &clockwork, 20);
|
||||
assert!(open_grievances(&kindly).trim().ends_with("none"), "a favour is no grievance");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dislike_nobody_earned_is_no_open_grievance() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Prejudice");
|
||||
play_patch(
|
||||
&mut kernel,
|
||||
WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(clockwork.reeve),
|
||||
toward: AttitudeTowardRef::Subject(Ref::Existing(clockwork.farmer)),
|
||||
delta: -40,
|
||||
basis: AttitudeBasisRef::Prejudice,
|
||||
decay: None,
|
||||
}],
|
||||
evidence: Vec::new(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -40);
|
||||
assert!(
|
||||
open_grievances(&kernel).trim().ends_with("none"),
|
||||
"a feeling no deed explains wrongs no one"
|
||||
);
|
||||
}
|
||||
|
|
@ -469,7 +469,7 @@ mod tests {
|
|||
AuthorityTargetRef, CallerId, CausalBoundary, CommandBody, CommandEnvelope, CommitmentKind,
|
||||
ComponentOp, CoverBudget, DecisionOpportunity, DecisionScope, Declaration, DraftHandle,
|
||||
EntityDeclaration, EntityId, EntityKind, EvidenceRef, FactDeclaration, FactStandingRef,
|
||||
FictionalMinutes, JurisdictionKey, NewController, PatchGround, Quantity, Ref, TickIndex,
|
||||
FictionalMinutes, JurisdictionKey, NewController, PatchGround, Quantity, Ref,
|
||||
RouteDeclaration, Statement, SubjectDeclaration, SubjectId, SubjectKind, SystemCapability,
|
||||
WorldEffect, WorldId, WorldKernel, WorldMailbox, WorldScaleIntentRef, agency_graph,
|
||||
commit_digest, derive_boundaries, derive_cover, derive_opportunities,
|
||||
|
|
@ -518,7 +518,6 @@ mod tests {
|
|||
},
|
||||
controller,
|
||||
position: Some(Ref::Existing(commons)),
|
||||
import_key: None,
|
||||
})
|
||||
};
|
||||
WorldPatch {
|
||||
|
|
@ -736,7 +735,8 @@ mod tests {
|
|||
assert!(!graph.subjects.contains(&mirror.first));
|
||||
let cover = derive_cover(
|
||||
snapshot.world_id,
|
||||
TickIndex(0),
|
||||
snapshot.now,
|
||||
30,
|
||||
&opportunities,
|
||||
&graph,
|
||||
CoverBudget {
|
||||
|
|
@ -1195,7 +1195,6 @@ mod tests {
|
|||
controller: NewController::External { consumer },
|
||||
affordances: BTreeSet::new(),
|
||||
position: Some(Ref::Existing(commons)),
|
||||
import_key: None,
|
||||
})])
|
||||
};
|
||||
// A binding to another consumer is outside its ground.
|
||||
|
|
@ -1574,7 +1573,6 @@ mod tests {
|
|||
controller,
|
||||
affordances,
|
||||
position: Some(Ref::Existing(mirror.commons)),
|
||||
import_key: None,
|
||||
})])
|
||||
};
|
||||
let pairing = |result: Result<SubmitReceipt, KernelError>| {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -11,6 +11,7 @@
|
|||
//! The cover is a partition, never a filter: every active subject is in exactly
|
||||
//! one cell every tick. The budget decides at what resolution, not whether.
|
||||
|
||||
use super::clock::FictionalMinutes;
|
||||
use super::{ControllerMode, DecisionOpportunity, SubjectId, WorldId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
|
@ -28,18 +29,25 @@ pub(crate) const AGENCY_STAR_THRESHOLD: usize = 16;
|
|||
/// the name, not by a second namespace.
|
||||
const COVER_NAMESPACE: &str = "ghostlight.cover.v1";
|
||||
|
||||
/// A tick's ordinal: the number of clock advances the world had committed when
|
||||
/// the tick opened. The driver reads it from the world and freezes it in the
|
||||
/// tick document; it is never derived from `now`, so it does not depend on the
|
||||
/// span. It is threaded into every derived command id, so a resumed tick
|
||||
/// re-submits the same ids and the kernel's idempotency ledger answers with the
|
||||
/// original receipts instead of double-committing.
|
||||
/// Monotone tick index. Derived from the world clock, never stored. It is
|
||||
/// threaded into every derived command id, so a resumed tick over the same
|
||||
/// snapshot re-derives the same ids and the kernel's idempotency ledger answers
|
||||
/// with the original receipts instead of double-committing.
|
||||
#[derive(
|
||||
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
|
||||
)]
|
||||
#[serde(transparent)]
|
||||
pub struct TickIndex(pub u64);
|
||||
|
||||
impl TickIndex {
|
||||
/// Floor division by the span one `AdvanceTime` carries. The driver submits
|
||||
/// the clock *after* the cells run, so every cell in one tick sees the same
|
||||
/// `now` and therefore the same index.
|
||||
pub(crate) fn of(now: FictionalMinutes, tick_minutes: u32) -> Self {
|
||||
Self(now.0 / u64::from(tick_minutes.max(1)))
|
||||
}
|
||||
}
|
||||
|
||||
/// How a subject was represented this tick. Derived from the cell, carried
|
||||
/// nowhere in world state: representation is a compute budget, not world truth.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -62,12 +70,9 @@ impl std::fmt::Display for CellId {
|
|||
}
|
||||
}
|
||||
|
||||
/// sha256 over a fixed namespace and a name, first sixteen bytes: the one id
|
||||
/// recipe the scheduler's derived ids share (cells here, hierarchy nodes in
|
||||
/// `hierarchy.rs`), so the two cannot drift apart.
|
||||
pub(crate) fn derive_uuid(namespace: &str, name: &str) -> Uuid {
|
||||
fn derive_uuid(name: &str) -> Uuid {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(namespace.as_bytes());
|
||||
hasher.update(COVER_NAMESPACE.as_bytes());
|
||||
hasher.update([0u8]);
|
||||
hasher.update(name.as_bytes());
|
||||
let bytes: [u8; 16] = hasher.finalize()[..16]
|
||||
|
|
@ -84,7 +89,7 @@ fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId {
|
|||
.first()
|
||||
.copied()
|
||||
.expect("a cell always has at least one member");
|
||||
CellId(derive_uuid(COVER_NAMESPACE, &format!(
|
||||
CellId(derive_uuid(&format!(
|
||||
"cell|{world:?}|{}|{}|{lowest:?}",
|
||||
tick.0,
|
||||
members.len()
|
||||
|
|
@ -93,7 +98,7 @@ fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId {
|
|||
|
||||
/// The stable, derived identity a cell's controller-work row is keyed by.
|
||||
pub(crate) fn cell_work_uuid(world: WorldId, cell: CellId, tick: TickIndex) -> Uuid {
|
||||
derive_uuid(COVER_NAMESPACE, &format!("cell-work|{world:?}|{cell}|{}", tick.0))
|
||||
derive_uuid(&format!("cell-work|{world:?}|{cell}|{}", tick.0))
|
||||
}
|
||||
|
||||
/// One constituent's submission id. Deterministic, so a resumed cell re-submits
|
||||
|
|
@ -104,7 +109,7 @@ pub(crate) fn cell_constituent_uuid(
|
|||
subject: SubjectId,
|
||||
tick: TickIndex,
|
||||
) -> Uuid {
|
||||
derive_uuid(COVER_NAMESPACE, &format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0))
|
||||
derive_uuid(&format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
|
|
@ -236,27 +241,6 @@ impl AgencyGraph {
|
|||
}
|
||||
}
|
||||
|
||||
/// The adjacency among `members` alone: one node's voices partition over
|
||||
/// the edges that run between them. A star's centre outside `members`
|
||||
/// leaves its rays unlinked, which is honest: they were adjacent through
|
||||
/// somebody who is not at this table.
|
||||
pub(crate) fn restricted(&self, members: &BTreeSet<SubjectId>) -> Self {
|
||||
Self {
|
||||
subjects: self
|
||||
.subjects
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|subject| members.contains(subject))
|
||||
.collect(),
|
||||
edges: self
|
||||
.edges
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|(one, other)| members.contains(one) && members.contains(other))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn link(&mut self, one: SubjectId, other: SubjectId) {
|
||||
if one == other {
|
||||
return;
|
||||
|
|
@ -270,7 +254,7 @@ impl AgencyGraph {
|
|||
}
|
||||
}
|
||||
|
||||
/// The partition. Pure over `(world, tick, opportunities, graph, budget)`.
|
||||
/// The partition. Pure over `(world, now, opportunities, graph, budget)`.
|
||||
///
|
||||
/// `opportunities` arrives in the kernel's one attention order (pressure, then
|
||||
/// attention debt, then id) and is never re-sorted and never filtered here: a
|
||||
|
|
@ -278,11 +262,13 @@ impl AgencyGraph {
|
|||
/// is a fact about cognition rather than a scheduling preference.
|
||||
pub fn derive_cover(
|
||||
world: WorldId,
|
||||
tick: TickIndex,
|
||||
now: FictionalMinutes,
|
||||
tick_minutes: u32,
|
||||
opportunities: &[DecisionOpportunity],
|
||||
graph: &AgencyGraph,
|
||||
budget: CoverBudget,
|
||||
) -> Cover {
|
||||
let tick = TickIndex::of(now, tick_minutes);
|
||||
let active: Vec<&DecisionOpportunity> = opportunities
|
||||
.iter()
|
||||
.filter(|opportunity| opportunity.controller_mode != ControllerMode::Human)
|
||||
|
|
@ -615,28 +601,14 @@ mod tests {
|
|||
) -> Cover {
|
||||
derive_cover(
|
||||
WorldId::nil_for_test(),
|
||||
TickIndex(tick),
|
||||
FictionalMinutes(tick * 60),
|
||||
60,
|
||||
opportunities,
|
||||
graph,
|
||||
budget,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restriction_keeps_only_the_edges_between_the_members() {
|
||||
let mut graph = AgencyGraph {
|
||||
subjects: vec![subject(1), subject(2), subject(3), subject(4)],
|
||||
edges: BTreeSet::new(),
|
||||
};
|
||||
graph.link(subject(1), subject(2));
|
||||
graph.link(subject(2), subject(3));
|
||||
graph.link(subject(3), subject(4));
|
||||
let members = BTreeSet::from([subject(1), subject(2), subject(4)]);
|
||||
let kept = graph.restricted(&members);
|
||||
assert_eq!(kept.subjects, vec![subject(1), subject(2), subject(4)]);
|
||||
assert_eq!(kept.edges, BTreeSet::from([(subject(1), subject(2))]));
|
||||
}
|
||||
|
||||
/// Verification 21, at the design profile: 2,400 subjects, 240 cells, a cap
|
||||
/// of 24, 36 urgency slots. Every subject exactly once, the budget held, and
|
||||
/// the head of the attention order attended in detail.
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -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;
|
||||
|
|
@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,765 +0,0 @@
|
|||
//! The gestalt hierarchy: who hangs from whom, derived from world state on
|
||||
//! every read.
|
||||
//!
|
||||
//! This organ owns the tree and nothing else. [`derive_hierarchy`] is pure over
|
||||
//! a `&WorldState`: no clock, no entropy, no mailbox, no filesystem. Nothing it
|
||||
//! returns is stored, cached or admitted; a node, a [`NodeId`] and a home
|
||||
//! parent change only because the world changed through an ordinary command
|
||||
//! (an office granted, an authority granted, a subject moved).
|
||||
//!
|
||||
//! Like the agency graph it is wider than any subject view, so it is reachable
|
||||
//! from `WorldMailbox` and from neither `ControllerPort` nor `ElaborationPort`.
|
||||
//! The agency graph stays the adjacency inside one node.
|
||||
//!
|
||||
//! Home-parent rule, the first that exists: the institution in which the
|
||||
//! subject holds an office (several: fewest live members, then lowest id); the
|
||||
//! institution holding an authority grant over the subject (several: lowest
|
||||
//! id); the innermost institution holding a grant over a place subtree that
|
||||
//! contains its position (several over one place: lowest id); the place node
|
||||
//! of its own position; the root. A subject never hangs from itself. Two
|
||||
//! institutions that would hang from each other are a cycle, broken at its
|
||||
//! lowest id, which hangs from the root. Other ties stay context, not a second
|
||||
//! parent: one home per subject.
|
||||
|
||||
use super::{
|
||||
ControllerMode, EntityId, EntityKind, FictionalMinutes, SubjectId, SubjectKind, WorldId,
|
||||
WorldState, cover::derive_uuid, patch::AuthorityTarget,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Fixed, never regenerated: two worlds in one process are separated by the
|
||||
/// world id inside the name, as cover ids are.
|
||||
const NODE_NAMESPACE: &str = "ghostlight.gestalt.node.v1";
|
||||
|
||||
/// Derived from `(world, anchor)`, so the same anchor in the same world is the
|
||||
/// same node on every read and across every unrelated commit.
|
||||
#[derive(
|
||||
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
|
||||
)]
|
||||
#[serde(transparent)]
|
||||
pub struct NodeId(Uuid);
|
||||
|
||||
impl NodeId {
|
||||
pub(crate) fn of(world: WorldId, anchor: &NodeAnchor) -> Self {
|
||||
Self(derive_uuid(
|
||||
NODE_NAMESPACE,
|
||||
&format!("node|{world:?}|{anchor:?}"),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// What a node stands on. `Subject` names a leaf: a derived hierarchy lists
|
||||
/// leaves as a node's `loose` subjects and mints no node for them, so the
|
||||
/// variant exists to give a leaf one stable id when a planner needs it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(tag = "anchor", content = "id", rename_all = "snake_case")]
|
||||
pub enum NodeAnchor {
|
||||
World,
|
||||
Institution(SubjectId),
|
||||
Place(EntityId),
|
||||
Subject(SubjectId),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Node {
|
||||
pub id: NodeId,
|
||||
pub anchor: NodeAnchor,
|
||||
/// `None` for the root alone.
|
||||
pub parent: Option<NodeId>,
|
||||
/// Ascending by id.
|
||||
pub children: Vec<NodeId>,
|
||||
/// The institution subject that speaks for its own node, when it has a
|
||||
/// non-Human controller. `None` for the root and for place nodes.
|
||||
pub voice: Option<SubjectId>,
|
||||
/// Subjects that hang directly from this node and are not nodes
|
||||
/// themselves. Ascending. Never the Human subject.
|
||||
pub loose: Vec<SubjectId>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Hierarchy {
|
||||
root: NodeId,
|
||||
pub nodes: BTreeMap<NodeId, Node>,
|
||||
/// Every placed subject's one parent node, the Human subject included:
|
||||
/// the player is placed, never a voice.
|
||||
pub home: BTreeMap<SubjectId, NodeId>,
|
||||
/// When each voice last consumed a decision opportunity; absent means
|
||||
/// never. Read from the kernel's `last_opportunity_at`.
|
||||
pub last_attended: BTreeMap<SubjectId, FictionalMinutes>,
|
||||
/// The voices that are populations. A closed place node still speaks for
|
||||
/// its populations; its persons are silent.
|
||||
pub populations: BTreeSet<SubjectId>,
|
||||
/// For every place, the node that governs it: its own place node if one
|
||||
/// exists, else its innermost governing institution, else the nearest
|
||||
/// enclosing place node, else the root.
|
||||
governing: BTreeMap<EntityId, NodeId>,
|
||||
}
|
||||
|
||||
impl Hierarchy {
|
||||
pub fn root(&self) -> NodeId {
|
||||
self.root
|
||||
}
|
||||
|
||||
/// The chain of nodes that govern `place`, innermost first and ending at
|
||||
/// the root. A place the world does not hold is governed by the root
|
||||
/// alone.
|
||||
pub fn focus_path(&self, place: EntityId) -> Vec<NodeId> {
|
||||
let mut path = Vec::new();
|
||||
let mut current = Some(self.governing.get(&place).copied().unwrap_or(self.root));
|
||||
while let Some(id) = current {
|
||||
path.push(id);
|
||||
current = self.nodes.get(&id).and_then(|node| node.parent);
|
||||
}
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Home {
|
||||
Institution(SubjectId),
|
||||
Place(EntityId),
|
||||
Root,
|
||||
}
|
||||
|
||||
/// The place and its containers, innermost first. Bounded by the entity count,
|
||||
/// so a corrupt containment loop cannot spin.
|
||||
fn place_chain(state: &WorldState, place: EntityId) -> Vec<EntityId> {
|
||||
let mut chain = Vec::new();
|
||||
let mut current = Some(place);
|
||||
for _ in 0..=state.entities.len() {
|
||||
let Some(node) = current else { break };
|
||||
chain.push(node);
|
||||
current = state
|
||||
.entities
|
||||
.get(&node)
|
||||
.and_then(|record| record.container);
|
||||
}
|
||||
chain
|
||||
}
|
||||
|
||||
pub(super) fn derive_hierarchy(state: &WorldState) -> Hierarchy {
|
||||
// Who exists to the hierarchy: every subject with a controller. Voices are
|
||||
// the ones that are not Human.
|
||||
let mut placed: BTreeSet<SubjectId> = BTreeSet::new();
|
||||
let mut voices: BTreeSet<SubjectId> = BTreeSet::new();
|
||||
for (scope, controller) in &state.controller_assignments {
|
||||
match controller.mode() {
|
||||
Some(ControllerMode::Human) => {
|
||||
placed.insert(scope.subject_id);
|
||||
}
|
||||
Some(_) => {
|
||||
placed.insert(scope.subject_id);
|
||||
voices.insert(scope.subject_id);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
let institutions: BTreeSet<SubjectId> = voices
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|subject| {
|
||||
state
|
||||
.subjects
|
||||
.get(subject)
|
||||
.is_some_and(|record| record.kind == SubjectKind::Institution)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Office incumbency: subject -> (institution, its live member count).
|
||||
let members = |institution: SubjectId| -> usize {
|
||||
state
|
||||
.selection
|
||||
.get(&institution)
|
||||
.map(|offices| {
|
||||
offices
|
||||
.values()
|
||||
.filter_map(|office| office.incumbent)
|
||||
.filter(|incumbent| placed.contains(incumbent))
|
||||
.collect::<BTreeSet<_>>()
|
||||
.len()
|
||||
})
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let mut offices_held: BTreeMap<SubjectId, Vec<SubjectId>> = BTreeMap::new();
|
||||
for institution in &institutions {
|
||||
for office in state.selection.get(institution).into_iter().flat_map(|o| o.values()) {
|
||||
if let Some(incumbent) = office.incumbent
|
||||
&& placed.contains(&incumbent)
|
||||
{
|
||||
let held = offices_held.entry(incumbent).or_default();
|
||||
if !held.contains(institution) {
|
||||
held.push(*institution);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Authority grants held by an institution, by what they cover.
|
||||
let mut over_subject: BTreeMap<SubjectId, BTreeSet<SubjectId>> = BTreeMap::new();
|
||||
let mut over_place: BTreeMap<EntityId, BTreeSet<SubjectId>> = BTreeMap::new();
|
||||
for (holder, grants) in &state.authority {
|
||||
if !institutions.contains(holder) {
|
||||
continue;
|
||||
}
|
||||
for grant in grants {
|
||||
match grant.over {
|
||||
AuthorityTarget::Subject(subject) => {
|
||||
over_subject.entry(subject).or_default().insert(*holder);
|
||||
}
|
||||
AuthorityTarget::PlaceSubtree(place) => {
|
||||
over_place.entry(place).or_default().insert(*holder);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut home_of: BTreeMap<SubjectId, Home> = BTreeMap::new();
|
||||
for subject in &placed {
|
||||
let own = *subject;
|
||||
let by_office = offices_held.get(&own).and_then(|held| {
|
||||
held.iter()
|
||||
.copied()
|
||||
.filter(|institution| *institution != own)
|
||||
.min_by_key(|institution| (members(*institution), *institution))
|
||||
});
|
||||
let by_grant = || {
|
||||
over_subject
|
||||
.get(&own)
|
||||
.and_then(|holders| holders.iter().copied().find(|holder| *holder != own))
|
||||
};
|
||||
let by_place = || {
|
||||
let position = state.positions.get(&own)?;
|
||||
place_chain(state, position.place).into_iter().find_map(|place| {
|
||||
over_place
|
||||
.get(&place)
|
||||
.and_then(|holders| holders.iter().copied().find(|holder| *holder != own))
|
||||
})
|
||||
};
|
||||
let home = by_office
|
||||
.or_else(by_grant)
|
||||
.or_else(by_place)
|
||||
.map(Home::Institution)
|
||||
.or_else(|| state.positions.get(&own).map(|position| Home::Place(position.place)))
|
||||
.unwrap_or(Home::Root);
|
||||
home_of.insert(own, home);
|
||||
}
|
||||
|
||||
// A cycle can only run through institutions. Break each at its lowest id.
|
||||
let mut settled: BTreeSet<SubjectId> = BTreeSet::new();
|
||||
for start in &institutions {
|
||||
let mut path: Vec<SubjectId> = Vec::new();
|
||||
let mut current = *start;
|
||||
loop {
|
||||
if settled.contains(¤t) {
|
||||
break;
|
||||
}
|
||||
if let Some(at) = path.iter().position(|seen| *seen == current) {
|
||||
let lowest = path[at..].iter().copied().min().expect("a cycle is non-empty");
|
||||
home_of.insert(lowest, Home::Root);
|
||||
break;
|
||||
}
|
||||
path.push(current);
|
||||
match home_of.get(¤t) {
|
||||
Some(Home::Institution(parent)) => current = *parent,
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
settled.extend(path);
|
||||
}
|
||||
|
||||
// Place nodes exist only where some subject hangs from one.
|
||||
let place_nodes: BTreeSet<EntityId> = home_of
|
||||
.values()
|
||||
.filter_map(|home| match home {
|
||||
Home::Place(place) => Some(*place),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let world = state.world_id;
|
||||
let root = NodeId::of(world, &NodeAnchor::World);
|
||||
let institution_node = |institution: SubjectId| NodeId::of(world, &NodeAnchor::Institution(institution));
|
||||
let place_node = |place: EntityId| NodeId::of(world, &NodeAnchor::Place(place));
|
||||
let node_of_home = |home: &Home| match home {
|
||||
Home::Institution(institution) => institution_node(*institution),
|
||||
Home::Place(place) => place_node(*place),
|
||||
Home::Root => root,
|
||||
};
|
||||
|
||||
let mut nodes: BTreeMap<NodeId, Node> = BTreeMap::new();
|
||||
nodes.insert(
|
||||
root,
|
||||
Node {
|
||||
id: root,
|
||||
anchor: NodeAnchor::World,
|
||||
parent: None,
|
||||
children: Vec::new(),
|
||||
voice: None,
|
||||
loose: Vec::new(),
|
||||
},
|
||||
);
|
||||
for institution in &institutions {
|
||||
let id = institution_node(*institution);
|
||||
nodes.insert(
|
||||
id,
|
||||
Node {
|
||||
id,
|
||||
anchor: NodeAnchor::Institution(*institution),
|
||||
parent: Some(node_of_home(&home_of[institution])),
|
||||
children: Vec::new(),
|
||||
voice: Some(*institution),
|
||||
loose: Vec::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
for place in &place_nodes {
|
||||
let id = place_node(*place);
|
||||
let parent = place_chain(state, *place)
|
||||
.into_iter()
|
||||
.skip(1)
|
||||
.find(|ancestor| place_nodes.contains(ancestor))
|
||||
.map(place_node)
|
||||
.unwrap_or(root);
|
||||
nodes.insert(
|
||||
id,
|
||||
Node {
|
||||
id,
|
||||
anchor: NodeAnchor::Place(*place),
|
||||
parent: Some(parent),
|
||||
children: Vec::new(),
|
||||
voice: None,
|
||||
loose: Vec::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let mut home: BTreeMap<SubjectId, NodeId> = BTreeMap::new();
|
||||
for (subject, subject_home) in &home_of {
|
||||
let parent = node_of_home(subject_home);
|
||||
home.insert(*subject, parent);
|
||||
if voices.contains(subject) && !institutions.contains(subject) {
|
||||
nodes
|
||||
.get_mut(&parent)
|
||||
.expect("a home names a node that was just minted")
|
||||
.loose
|
||||
.push(*subject);
|
||||
}
|
||||
}
|
||||
let links: Vec<(NodeId, NodeId)> = nodes
|
||||
.values()
|
||||
.filter_map(|node| node.parent.map(|parent| (parent, node.id)))
|
||||
.collect();
|
||||
for (parent, child) in links {
|
||||
nodes
|
||||
.get_mut(&parent)
|
||||
.expect("a parent is a minted node")
|
||||
.children
|
||||
.push(child);
|
||||
}
|
||||
// `home_of` iterates ascending, so `loose` is already ascending; children
|
||||
// arrive in node-id order from `nodes`.
|
||||
|
||||
let mut governing: BTreeMap<EntityId, NodeId> = BTreeMap::new();
|
||||
for (place, record) in &state.entities {
|
||||
if record.kind != EntityKind::Place {
|
||||
continue;
|
||||
}
|
||||
let chain = place_chain(state, *place);
|
||||
let node = if place_nodes.contains(place) {
|
||||
place_node(*place)
|
||||
} else if let Some(holder) = chain
|
||||
.iter()
|
||||
.find_map(|link| over_place.get(link).and_then(|holders| holders.first()))
|
||||
{
|
||||
institution_node(*holder)
|
||||
} else {
|
||||
chain
|
||||
.iter()
|
||||
.find(|link| place_nodes.contains(link))
|
||||
.map(|link| place_node(*link))
|
||||
.unwrap_or(root)
|
||||
};
|
||||
governing.insert(*place, node);
|
||||
}
|
||||
|
||||
let last_attended = voices
|
||||
.iter()
|
||||
.filter_map(|voice| {
|
||||
state
|
||||
.last_opportunity_at
|
||||
.get(voice)
|
||||
.map(|at| (*voice, *at))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let populations = voices
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|voice| {
|
||||
state
|
||||
.subjects
|
||||
.get(voice)
|
||||
.is_some_and(|record| record.kind == SubjectKind::Population)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Hierarchy {
|
||||
root,
|
||||
nodes,
|
||||
home,
|
||||
last_attended,
|
||||
populations,
|
||||
governing,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use crate::patch::{
|
||||
AuthorityGrant, AuthorityKindName, EntityRecord, Office, OfficeName, Position,
|
||||
};
|
||||
use crate::{
|
||||
ControllerAssignment, ControllerId, DecisionScope, PrincipalId, SubjectState,
|
||||
};
|
||||
|
||||
pub(crate) struct Fixture {
|
||||
pub(crate) state: WorldState,
|
||||
next: u128,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
state: WorldState::empty(
|
||||
WorldId(Uuid::from_u128(0xfeed)),
|
||||
PrincipalId::new("owner"),
|
||||
"Hierarchy".into(),
|
||||
None,
|
||||
),
|
||||
next: 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn uuid(&mut self) -> Uuid {
|
||||
self.next += 1;
|
||||
Uuid::from_u128(self.next)
|
||||
}
|
||||
|
||||
pub(crate) fn place(&mut self, label: &str, container: Option<EntityId>) -> EntityId {
|
||||
let id = EntityId(self.uuid());
|
||||
self.state.entities.insert(
|
||||
id,
|
||||
EntityRecord {
|
||||
label: label.into(),
|
||||
kind: EntityKind::Place,
|
||||
container,
|
||||
},
|
||||
);
|
||||
id
|
||||
}
|
||||
|
||||
pub(crate) fn subject(&mut self, label: &str, kind: SubjectKind, at: Option<EntityId>) -> SubjectId {
|
||||
let id = SubjectId(self.uuid());
|
||||
let controller_id = ControllerId(self.uuid());
|
||||
self.state.subjects.insert(
|
||||
id,
|
||||
SubjectState {
|
||||
label: label.into(),
|
||||
kind,
|
||||
import_key: None,
|
||||
},
|
||||
);
|
||||
self.state.controller_assignments.insert(
|
||||
DecisionScope { subject_id: id },
|
||||
ControllerAssignment::NarrativePersona { controller_id },
|
||||
);
|
||||
if let Some(place) = at {
|
||||
self.state.positions.insert(id, Position { place });
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
pub(crate) fn player(&mut self, at: EntityId) -> SubjectId {
|
||||
let id = self.subject("Player", SubjectKind::Person, Some(at));
|
||||
let controller_id = ControllerId(self.uuid());
|
||||
self.state.controller_assignments.insert(
|
||||
DecisionScope { subject_id: id },
|
||||
ControllerAssignment::Human {
|
||||
controller_id,
|
||||
principal: PrincipalId::new("player"),
|
||||
},
|
||||
);
|
||||
id
|
||||
}
|
||||
|
||||
pub(crate) fn office(&mut self, institution: SubjectId, name: &str, incumbent: SubjectId) {
|
||||
self.state.selection.entry(institution).or_default().insert(
|
||||
OfficeName(name.into()),
|
||||
Office {
|
||||
incumbent: Some(incumbent),
|
||||
delegated: [AuthorityKindName("rule".into())].into(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn grant(&mut self, holder: SubjectId, over: AuthorityTarget) {
|
||||
self.state.authority.entry(holder).or_default().insert(AuthorityGrant {
|
||||
kind: AuthorityKindName("rule".into()),
|
||||
over,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn parent_of(hierarchy: &Hierarchy, node: NodeId) -> Option<NodeId> {
|
||||
hierarchy.nodes[&node].parent
|
||||
}
|
||||
|
||||
fn inst(hierarchy: &Hierarchy, world: &WorldState, subject: SubjectId) -> NodeId {
|
||||
let id = NodeId::of(world.world_id, &NodeAnchor::Institution(subject));
|
||||
assert!(hierarchy.nodes.contains_key(&id), "no institution node");
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hierarchy_is_deterministic_and_ids_survive_an_unrelated_commit() {
|
||||
let mut f = Fixture::new();
|
||||
let town = f.place("Town", None);
|
||||
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||
let alice = f.subject("Alice", SubjectKind::Person, Some(town));
|
||||
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||
f.office(council, "mayor", alice);
|
||||
let first = derive_hierarchy(&f.state);
|
||||
assert_eq!(first, derive_hierarchy(&f.state));
|
||||
assert_eq!(
|
||||
serde_json::to_vec(&first).unwrap(),
|
||||
serde_json::to_vec(&derive_hierarchy(&f.state)).unwrap()
|
||||
);
|
||||
// Time passes and an unrelated subject acts: no node changes identity.
|
||||
f.state.now = FictionalMinutes(500);
|
||||
f.state.revision += 7;
|
||||
f.state.last_opportunity_at.insert(alice, FictionalMinutes(40));
|
||||
let later = derive_hierarchy(&f.state);
|
||||
assert_eq!(
|
||||
first.nodes.keys().collect::<Vec<_>>(),
|
||||
later.nodes.keys().collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(first.home, later.home);
|
||||
assert_eq!(later.last_attended.get(&alice), Some(&FictionalMinutes(40)));
|
||||
assert!(first.last_attended.is_empty());
|
||||
// The same anchor in another world is another node.
|
||||
let other = NodeId::of(WorldId(Uuid::from_u128(0xbeef)), &NodeAnchor::World);
|
||||
assert_ne!(other, first.root());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_voice_has_exactly_one_home_and_a_chain_to_the_root() {
|
||||
let mut f = Fixture::new();
|
||||
let region = f.place("Region", None);
|
||||
let town = f.place("Town", Some(region));
|
||||
let tavern = f.place("Tavern", Some(town));
|
||||
let empire = f.subject("Empire", SubjectKind::Institution, None);
|
||||
let council = f.subject("Council", SubjectKind::Institution, Some(town));
|
||||
let guild = f.subject("Guild", SubjectKind::Institution, Some(tavern));
|
||||
let folk = f.subject("Townsfolk", SubjectKind::Population, Some(town));
|
||||
let alice = f.subject("Alice", SubjectKind::Person, Some(tavern));
|
||||
let bob = f.subject("Bob", SubjectKind::Person, Some(region));
|
||||
let nowhere = f.subject("Drifter", SubjectKind::Person, None);
|
||||
let player = f.player(tavern);
|
||||
f.grant(empire, AuthorityTarget::Subject(council));
|
||||
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||
f.office(guild, "master", alice);
|
||||
let hierarchy = derive_hierarchy(&f.state);
|
||||
|
||||
let voices = [empire, council, guild, folk, alice, bob, nowhere];
|
||||
for voice in voices {
|
||||
let mut at = hierarchy.home[&voice];
|
||||
let mut seen = BTreeSet::new();
|
||||
loop {
|
||||
assert!(seen.insert(at), "a chain revisited a node");
|
||||
match parent_of(&hierarchy, at) {
|
||||
Some(up) => at = up,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
assert_eq!(at, hierarchy.root(), "a chain ended off the root");
|
||||
// Exactly one place holds it: as a child node or as a loose subject.
|
||||
let holders = hierarchy
|
||||
.nodes
|
||||
.values()
|
||||
.filter(|node| node.loose.contains(&voice) || {
|
||||
node.anchor == NodeAnchor::Institution(voice)
|
||||
})
|
||||
.count();
|
||||
assert_eq!(holders, 1, "a voice is held by {holders} nodes");
|
||||
}
|
||||
assert_eq!(hierarchy.home.len(), voices.len() + 1, "the player is placed too");
|
||||
assert!(hierarchy.home.contains_key(&player));
|
||||
// A population is a single loose voice, hung by the same rule.
|
||||
assert_eq!(hierarchy.home[&folk], inst(&hierarchy, &f.state, council));
|
||||
assert_eq!(hierarchy.home[&nowhere], hierarchy.root());
|
||||
// Children and parents agree.
|
||||
for node in hierarchy.nodes.values() {
|
||||
for child in &node.children {
|
||||
assert_eq!(hierarchy.nodes[child].parent, Some(node.id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn institutions_come_before_places() {
|
||||
let mut f = Fixture::new();
|
||||
let town = f.place("Town", None);
|
||||
let tap_room = f.place("Tap-room", Some(town));
|
||||
let field = f.place("Field", None);
|
||||
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||
let guild = f.subject("Guild", SubjectKind::Institution, None);
|
||||
let in_guild = f.subject("Guildsman", SubjectKind::Person, Some(tap_room));
|
||||
let plain = f.subject("Drinker", SubjectKind::Person, Some(tap_room));
|
||||
let farmer = f.subject("Farmer", SubjectKind::Person, Some(field));
|
||||
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||
f.office(guild, "member", in_guild);
|
||||
let hierarchy = derive_hierarchy(&f.state);
|
||||
assert_eq!(hierarchy.home[&in_guild], inst(&hierarchy, &f.state, guild));
|
||||
assert_eq!(hierarchy.home[&plain], inst(&hierarchy, &f.state, council));
|
||||
let field_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(field));
|
||||
assert_eq!(hierarchy.home[&farmer], field_node);
|
||||
assert_eq!(parent_of(&hierarchy, field_node), Some(hierarchy.root()));
|
||||
// A place node exists only where somebody hangs from it.
|
||||
assert_eq!(
|
||||
hierarchy
|
||||
.nodes
|
||||
.values()
|
||||
.filter(|node| matches!(node.anchor, NodeAnchor::Place(_)))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_authority_grant_over_the_subject_beats_a_place_grant() {
|
||||
let mut f = Fixture::new();
|
||||
let town = f.place("Town", None);
|
||||
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||
let temple = f.subject("Temple", SubjectKind::Institution, None);
|
||||
let priest = f.subject("Priest", SubjectKind::Person, Some(town));
|
||||
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||
f.grant(temple, AuthorityTarget::Subject(priest));
|
||||
let hierarchy = derive_hierarchy(&f.state);
|
||||
assert_eq!(hierarchy.home[&priest], inst(&hierarchy, &f.state, temple));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_innermost_place_grant_governs_and_several_offices_pick_the_smaller_body() {
|
||||
let mut f = Fixture::new();
|
||||
let region = f.place("Region", None);
|
||||
let town = f.place("Town", Some(region));
|
||||
let crown = f.subject("Crown", SubjectKind::Institution, None);
|
||||
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||
let big = f.subject("Big", SubjectKind::Institution, None);
|
||||
let small = f.subject("Small", SubjectKind::Institution, None);
|
||||
let walker = f.subject("Walker", SubjectKind::Person, Some(town));
|
||||
let other_a = f.subject("A", SubjectKind::Person, None);
|
||||
let other_b = f.subject("B", SubjectKind::Person, None);
|
||||
let sitter = f.subject("Sitter", SubjectKind::Person, Some(town));
|
||||
f.grant(crown, AuthorityTarget::PlaceSubtree(region));
|
||||
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||
f.office(big, "a", other_a);
|
||||
f.office(big, "b", other_b);
|
||||
f.office(big, "c", sitter);
|
||||
f.office(small, "a", sitter);
|
||||
let hierarchy = derive_hierarchy(&f.state);
|
||||
assert_eq!(hierarchy.home[&walker], inst(&hierarchy, &f.state, council));
|
||||
assert_eq!(hierarchy.home[&sitter], inst(&hierarchy, &f.state, small));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cycle_is_broken_at_its_lowest_id() {
|
||||
let mut f = Fixture::new();
|
||||
let one = f.subject("One", SubjectKind::Institution, None);
|
||||
let two = f.subject("Two", SubjectKind::Institution, None);
|
||||
f.grant(one, AuthorityTarget::Subject(two));
|
||||
f.grant(two, AuthorityTarget::Subject(one));
|
||||
let (low, high) = if one < two { (one, two) } else { (two, one) };
|
||||
let hierarchy = derive_hierarchy(&f.state);
|
||||
assert_eq!(hierarchy.home[&low], hierarchy.root());
|
||||
assert_eq!(hierarchy.home[&high], inst(&hierarchy, &f.state, low));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tail_leading_into_a_cycle_keeps_its_parent_when_the_cycle_breaks() {
|
||||
let mut f = Fixture::new();
|
||||
let tail = f.subject("Tail", SubjectKind::Institution, None);
|
||||
let one = f.subject("One", SubjectKind::Institution, None);
|
||||
let two = f.subject("Two", SubjectKind::Institution, None);
|
||||
f.grant(one, AuthorityTarget::Subject(tail));
|
||||
f.grant(one, AuthorityTarget::Subject(two));
|
||||
f.grant(two, AuthorityTarget::Subject(one));
|
||||
let hierarchy = derive_hierarchy(&f.state);
|
||||
assert_eq!(hierarchy.home[&tail], inst(&hierarchy, &f.state, one));
|
||||
assert_eq!(hierarchy.home[&one], hierarchy.root());
|
||||
assert_eq!(hierarchy.home[&two], inst(&hierarchy, &f.state, one));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_player_is_placed_and_never_a_voice() {
|
||||
let mut f = Fixture::new();
|
||||
let town = f.place("Town", None);
|
||||
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||
let player = f.player(town);
|
||||
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||
f.office(council, "seat", player);
|
||||
let hierarchy = derive_hierarchy(&f.state);
|
||||
assert_eq!(hierarchy.home[&player], inst(&hierarchy, &f.state, council));
|
||||
assert!(
|
||||
hierarchy
|
||||
.nodes
|
||||
.values()
|
||||
.all(|node| node.voice != Some(player) && !node.loose.contains(&player))
|
||||
);
|
||||
assert!(!hierarchy.last_attended.contains_key(&player));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_focus_path_follows_governance() {
|
||||
let mut f = Fixture::new();
|
||||
let town = f.place("Town", None);
|
||||
let tap_room = f.place("Tap-room", Some(town));
|
||||
let heath = f.place("Heath", None);
|
||||
let empire = f.subject("Empire", SubjectKind::Institution, None);
|
||||
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||
f.subject("Drinker", SubjectKind::Person, Some(tap_room));
|
||||
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||
f.grant(empire, AuthorityTarget::Subject(council));
|
||||
let hierarchy = derive_hierarchy(&f.state);
|
||||
assert_eq!(
|
||||
hierarchy.focus_path(tap_room),
|
||||
vec![
|
||||
inst(&hierarchy, &f.state, council),
|
||||
inst(&hierarchy, &f.state, empire),
|
||||
hierarchy.root(),
|
||||
]
|
||||
);
|
||||
// An ungoverned place is governed by the root alone.
|
||||
assert_eq!(hierarchy.focus_path(heath), vec![hierarchy.root()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_place_node_hangs_from_the_nearest_enclosing_place_node() {
|
||||
let mut f = Fixture::new();
|
||||
let region = f.place("Region", None);
|
||||
let hamlet = f.place("Hamlet", Some(region));
|
||||
let barn = f.place("Barn", Some(hamlet));
|
||||
f.subject("Reeve", SubjectKind::Person, Some(region));
|
||||
f.subject("Hand", SubjectKind::Person, Some(barn));
|
||||
let hierarchy = derive_hierarchy(&f.state);
|
||||
let region_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(region));
|
||||
let barn_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(barn));
|
||||
assert_eq!(parent_of(&hierarchy, barn_node), Some(region_node));
|
||||
assert_eq!(
|
||||
hierarchy.focus_path(hamlet),
|
||||
vec![region_node, hierarchy.root()]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -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"
|
||||
);
|
||||
}
|
||||
|
|
@ -181,11 +181,6 @@ impl WorldJournal {
|
|||
self.commits.get(&command_id)
|
||||
}
|
||||
|
||||
/// Every commit the journal holds, in no particular order.
|
||||
pub(super) fn commits(&self) -> impl Iterator<Item = &WorldCommit> {
|
||||
self.commits.values()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn commit_count(&self) -> usize {
|
||||
self.commits.len()
|
||||
|
|
@ -733,55 +728,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
|
|||
));
|
||||
}
|
||||
}
|
||||
// Attitude: a holder and its target are canonical subjects, a delta is
|
||||
// nonzero and bounded, a stamp is not from the future, and a rumour rests
|
||||
// on a fact that exists. A trait row names a canonical subject, a civic
|
||||
// trait name, and at least one real fact.
|
||||
for (holder, held) in &state.attitudes {
|
||||
let modifier_is_canonical = |key: &super::AttitudeKey, modifier: &super::AttitudeModifier| {
|
||||
let toward_is_canonical = match &key.toward {
|
||||
super::AttitudeToward::Subject(target) => {
|
||||
state.subjects.contains_key(target) && target != holder
|
||||
}
|
||||
super::AttitudeToward::Trait(name) => super::patch::is_civic_name(&name.0),
|
||||
};
|
||||
let cause_is_canonical = match &key.cause {
|
||||
super::AttitudeCause::Rumour { fact } => {
|
||||
state.facts.contains_key(fact)
|
||||
&& matches!(key.toward, super::AttitudeToward::Subject(_))
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
toward_is_canonical
|
||||
&& cause_is_canonical
|
||||
&& crate::attitude::is_valid_delta(modifier.delta)
|
||||
&& crate::attitude::is_valid_decay(modifier.decay)
|
||||
&& modifier.since <= state.now
|
||||
};
|
||||
if !state.subjects.contains_key(holder)
|
||||
|| held.is_empty()
|
||||
|| !held.iter().all(|(key, modifier)| modifier_is_canonical(key, modifier))
|
||||
{
|
||||
return Err(JournalError::Corrupt(
|
||||
"an attitude row does not name a canonical holder, target, cause, and bounded delta"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
for (subject_id, carried) in &state.traits {
|
||||
if !state.subjects.contains_key(subject_id)
|
||||
|| carried.is_empty()
|
||||
|| carried.iter().any(|(name, evidence)| {
|
||||
!super::patch::is_civic_name(&name.0)
|
||||
|| evidence.is_empty()
|
||||
|| !evidence.iter().all(|fact| state.facts.contains_key(fact))
|
||||
})
|
||||
{
|
||||
return Err(JournalError::Corrupt(
|
||||
"a trait row does not name a canonical subject, trait, and fact".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
if state
|
||||
.last_opportunity_at
|
||||
.iter()
|
||||
|
|
@ -880,17 +826,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
|
|||
"one subject holds two overlapping jurisdictions of one kind".into(),
|
||||
));
|
||||
}
|
||||
let mut declared_keys = BTreeSet::new();
|
||||
let no_held = BTreeSet::new();
|
||||
for subject in state.subjects.values() {
|
||||
if let Some(key) = &subject.import_key
|
||||
&& super::patch::import_key_fault(key, &no_held, &mut declared_keys).is_some()
|
||||
{
|
||||
return Err(JournalError::Corrupt(
|
||||
"subject import key is malformed or held by two subjects".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut controller_ids = BTreeSet::new();
|
||||
for (subject_id, subject) in &state.subjects {
|
||||
if !super::patch::is_canonical_text(&subject.label) {
|
||||
|
|
@ -1172,11 +1107,8 @@ mod tests {
|
|||
},
|
||||
affordances: kernel_speak_grant(),
|
||||
position: None,
|
||||
import_key: None,
|
||||
}),
|
||||
scale_intent: WorldScaleIntentRef::default(),
|
||||
grammar: None,
|
||||
era: None,
|
||||
};
|
||||
let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
||||
let snapshot = kernel.snapshot().unwrap();
|
||||
|
|
@ -1258,11 +1190,8 @@ mod tests {
|
|||
},
|
||||
affordances: kernel_speak_grant(),
|
||||
position: None,
|
||||
import_key: None,
|
||||
}),
|
||||
scale_intent: WorldScaleIntentRef::default(),
|
||||
grammar: None,
|
||||
era: None,
|
||||
};
|
||||
let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
||||
let snapshot = kernel.snapshot().unwrap();
|
||||
|
|
@ -1291,7 +1220,6 @@ mod tests {
|
|||
controller: NewController::OperationalAgent,
|
||||
affordances: BTreeSet::from([speak_entry(&kernel)]),
|
||||
position: Some(Ref::Draft(DraftHandle::new("rhythm-road"))),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
operations: Vec::new(),
|
||||
|
|
@ -1827,11 +1755,8 @@ mod tests {
|
|||
controller: NewController::Human { principal: owner },
|
||||
affordances: kernel_speak_grant(),
|
||||
position: None,
|
||||
import_key: None,
|
||||
}),
|
||||
scale_intent: WorldScaleIntentRef::default(),
|
||||
grammar: None,
|
||||
era: None,
|
||||
};
|
||||
let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
||||
let mut forged_head = kernel.state.clone();
|
||||
|
|
@ -3039,118 +2964,4 @@ mod custody_tests {
|
|||
"the chain digest answered for the authority check: {detail}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Attitude replays exactly: a restart rebuilds the same modifiers, traits
|
||||
/// and digest from the commits, and a row nobody's command wrote, whether
|
||||
/// edited, planted, or re-sealed under a digest that agrees with it, stops
|
||||
/// the history from recovering.
|
||||
#[test]
|
||||
fn attitude_replays_exactly_and_a_forged_row_fails_replay() {
|
||||
use crate::attitude::{AttitudeBasisRef, AttitudeCause, AttitudeKey, AttitudeToward, AttitudeTowardRef, TraitName};
|
||||
use crate::tests::{auth_principal, creation, operations, owner, speech_world, submit_owner};
|
||||
use crate::{ComponentOp, Ref};
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("world.cc");
|
||||
let (mut kernel, _) =
|
||||
WorldKernel::create(&path, creation(CommandId::new(), "Attitude"), &auth_principal(owner()))
|
||||
.unwrap();
|
||||
let (speech, _) = speech_world(&mut kernel);
|
||||
let before = kernel.snapshot().unwrap();
|
||||
submit_owner(
|
||||
&mut kernel,
|
||||
&before,
|
||||
operations(vec![
|
||||
ComponentOp::AdjustAttitude {
|
||||
holder: Ref::Existing(speech.listener),
|
||||
toward: Ref::Existing(speech.speaker),
|
||||
delta: -30,
|
||||
decay: None,
|
||||
},
|
||||
ComponentOp::DeclareTrait {
|
||||
subject: Ref::Existing(speech.speaker),
|
||||
name: TraitName("outlander".into()),
|
||||
fact: Ref::Existing(speech.flood),
|
||||
},
|
||||
ComponentOp::DeclareAttitude {
|
||||
holder: Ref::Existing(speech.listener),
|
||||
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
|
||||
delta: -10,
|
||||
basis: AttitudeBasisRef::Prejudice,
|
||||
decay: None,
|
||||
},
|
||||
]),
|
||||
);
|
||||
assert!(!kernel.state.attitudes.is_empty() && !kernel.state.traits.is_empty());
|
||||
|
||||
let rows = |state: &WorldState| -> Vec<CultCacheEnvelope> {
|
||||
let mut rows: Vec<CultCacheEnvelope> = kernel
|
||||
.journal
|
||||
.commits
|
||||
.values()
|
||||
.map(|commit| {
|
||||
envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap()
|
||||
})
|
||||
.collect();
|
||||
rows.push(envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state).unwrap());
|
||||
rows
|
||||
};
|
||||
let (_, recovered, _) = recover(rows(&kernel.state), None).expect("the honest history recovers");
|
||||
assert_eq!(recovered, kernel.state);
|
||||
assert_eq!(recovered.state_digest, kernel.state.state_digest);
|
||||
|
||||
let planted = AttitudeKey {
|
||||
toward: AttitudeToward::Subject(speech.listener),
|
||||
cause: AttitudeCause::Prejudice,
|
||||
};
|
||||
let forgeries: Vec<(&str, Box<dyn Fn(&mut WorldState)>)> = vec![
|
||||
(
|
||||
"a grievance edited",
|
||||
Box::new(|state| {
|
||||
let held = state.attitudes.get_mut(&speech.listener).unwrap();
|
||||
held.values_mut().next().unwrap().delta = -90;
|
||||
}),
|
||||
),
|
||||
(
|
||||
"an attitude planted",
|
||||
Box::new(move |state| {
|
||||
state.attitudes.entry(speech.speaker).or_default().insert(
|
||||
planted.clone(),
|
||||
crate::AttitudeModifier {
|
||||
delta: -50,
|
||||
since: state.now,
|
||||
decay: None,
|
||||
},
|
||||
);
|
||||
}),
|
||||
),
|
||||
(
|
||||
"a grievance erased",
|
||||
Box::new(|state| {
|
||||
state.attitudes.clear();
|
||||
}),
|
||||
),
|
||||
(
|
||||
"a trait erased",
|
||||
Box::new(|state| {
|
||||
state.traits.clear();
|
||||
}),
|
||||
),
|
||||
];
|
||||
for (name, forge) in forgeries {
|
||||
let mut forged = kernel.state.clone();
|
||||
forge(&mut forged);
|
||||
assert!(
|
||||
matches!(recover(rows(&forged), None), Err(JournalError::Corrupt(_))),
|
||||
"{name}: a forged attitude row replayed"
|
||||
);
|
||||
// Re-sealed under a digest that agrees with the forgery.
|
||||
forged.state_digest = crate::state_digest(&forged).unwrap();
|
||||
assert!(
|
||||
matches!(recover(rows(&forged), None), Err(JournalError::Corrupt(_))),
|
||||
"{name}: a re-sealed forged attitude row replayed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ impl Lens {
|
|||
}
|
||||
|
||||
/// What kind of structure the lens reaches for.
|
||||
pub fn reaches_for(self) -> &'static str {
|
||||
pub(crate) fn reaches_for(self) -> &'static str {
|
||||
match self {
|
||||
Lens::Patina => "ordinary objects, customs, nicknames, local jokes",
|
||||
Lens::Charter => "government, law, offices, selection, succession, redress",
|
||||
|
|
|
|||
|
|
@ -54,41 +54,24 @@
|
|||
//! ```compile_fail,E0425
|
||||
//! let _ = ghostlight::fixture_inference_output("prose", "receipt");
|
||||
//! ```
|
||||
//!
|
||||
//! ```compile_fail,E0599
|
||||
//! fn no_lane_reads_it(port: &ghostlight::ControllerPort) {
|
||||
//! let _ = port.hierarchy();
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
mod action;
|
||||
mod aetheria;
|
||||
mod attitude;
|
||||
mod clock;
|
||||
mod consumer;
|
||||
mod controllers;
|
||||
mod cover;
|
||||
mod elaboration;
|
||||
mod grammar;
|
||||
mod hierarchy;
|
||||
#[cfg(test)]
|
||||
mod import_key_tests;
|
||||
mod journal;
|
||||
mod lens;
|
||||
mod local_inference;
|
||||
mod mailbox;
|
||||
mod patch;
|
||||
mod routed_inference;
|
||||
mod sdk_inference;
|
||||
mod table;
|
||||
mod tool_schema;
|
||||
mod vault;
|
||||
mod verse;
|
||||
mod wave;
|
||||
|
||||
pub(crate) use action::ActionMismatch;
|
||||
pub(crate) use attitude::{
|
||||
AttitudeCause, AttitudeKey, AttitudeModifier, AttitudeToward, TraitName,
|
||||
};
|
||||
pub(crate) use clock::Motion;
|
||||
pub use clock::{FictionalMinutes, TickMinutes};
|
||||
pub use consumer::{
|
||||
|
|
@ -97,39 +80,23 @@ pub use consumer::{
|
|||
};
|
||||
pub use controllers::{
|
||||
CONTROLLER_WORK_SCHEMA, CellRun, ConnectorBinding, ControllerError, ControllerModels,
|
||||
ControllerOpenError,
|
||||
ControllerNeed, ControllerPendingReason, ControllerRunner, ControllerWork,
|
||||
ControllerWorkCustody, ControllerWorkLookup, ControllerWorkStore, ControllerWorkStoreError,
|
||||
ControllerWorkWrite,
|
||||
GroupedCheckpoint, InferenceEvent, InferenceFault, InferenceFaultClass, InferenceFaultDisposition, InferenceOutput,
|
||||
GroupedCheckpoint, InferenceEvent, InferenceFault, InferenceFaultDisposition, InferenceOutput,
|
||||
InferencePort,
|
||||
InferencePurpose, InferenceRequest, NarrativeCheckpoint, NarrativeRun, OperationalCheckpoint,
|
||||
OperationalRun, PersonaLane, PreparedInference, SubmissionDisposition, TokenUsage,
|
||||
OperationalRun, PersonaLane, PreparedInference, SubmissionDisposition, ToolResultOracle,
|
||||
TracingInferencePort, open_controller_work, open_inference,
|
||||
};
|
||||
pub(crate) use cover::{CellId, Constituent, Resolution};
|
||||
pub use aetheria::{
|
||||
AetheriaCatalog, AetheriaFaction, CatalogReadError, VerbRule, read_aetheria_catalog,
|
||||
};
|
||||
pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover};
|
||||
pub use hierarchy::{Hierarchy, Node, NodeAnchor, NodeId};
|
||||
pub use wave::{
|
||||
Deferral, DeferredNode, Focus, FrozenCell, GestaltKnobs, GestaltKnobsError, NodeOutcome, NodeReport,
|
||||
NodeTurn, Refusal, RefusalReason, UnattributedCall, Wave, WaveClock, WaveOutcome, WaveStop,
|
||||
act_line, acts_since, deferred_nodes, node_label, node_reports, plan_wave, run_frozen_cells,
|
||||
};
|
||||
pub use elaboration::{
|
||||
ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, SweepReport, EvidenceError, EvidenceQuery,
|
||||
EvidenceReceipt, EvidenceSource, NullEvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row,
|
||||
};
|
||||
pub use grammar::{
|
||||
GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb,
|
||||
RenderPath,
|
||||
ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, EvidenceError, EvidenceQuery,
|
||||
EvidenceReceipt, EvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row,
|
||||
};
|
||||
pub use lens::{Lens, LensWeights};
|
||||
pub use local_inference::{DEFAULT_HOSTED_MODEL_PREFIX, DEFAULT_LOCAL_MODEL_PREFIX, HostedBinding, LocalBinding};
|
||||
#[cfg(feature = "test-support")]
|
||||
pub use local_inference::open_local_port_with_timeout;
|
||||
pub use local_inference::{DEFAULT_LOCAL_MODEL_PREFIX, LocalBinding};
|
||||
pub(crate) use mailbox::ElaborationPort;
|
||||
pub use mailbox::{ConsumerPort, ControllerPort, MailboxError, PlayPort, SeedPort, WorldMailbox};
|
||||
pub use patch::{
|
||||
|
|
@ -144,7 +111,6 @@ pub(crate) use patch::{
|
|||
PersonaMaterial, Position, PressureMagnitude, PressureSource, Quantity, Reach,
|
||||
SubjectDeclaration, WorldScaleIntent, WorldScaleIntentRef,
|
||||
};
|
||||
pub use patch::ImportKey;
|
||||
#[cfg(test)]
|
||||
use patch::{
|
||||
AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp,
|
||||
|
|
@ -155,23 +121,13 @@ pub(crate) use patch::{
|
|||
AffordanceKindName, AuthorityGrantRef, AuthorityKindName, AuthorityTargetRef, ComponentOpKind,
|
||||
EffectSlot, OutcomeBand, Precondition, RoleSpec,
|
||||
};
|
||||
pub use sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, SdkBinding};
|
||||
pub use table::{
|
||||
DecodedBatch, PatchSite, TableError, actor_tools, authoring_tools, decode_actor_call,
|
||||
decode_authoring_call, decode_authoring_calls, describe_refusal, describe_refusal_to_actor,
|
||||
handle_for, id_text, id_text_matches, table_view,
|
||||
};
|
||||
pub use vault::{
|
||||
ImportOutcome, SnapshotId, VAULT_PROFILE_SCHEMA, VAULT_SNAPSHOT_SCHEMA, VaultError,
|
||||
VaultEra, VaultEvidenceSource, VaultProfile, VaultSnapshot, production_eras, production_profile, production_vault_names,
|
||||
};
|
||||
pub use verse::{
|
||||
CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, Lane, LaneTokens,
|
||||
NodeSpend, ProviderCallRecord, WaveSpend,
|
||||
RUN_RECORD_SCHEMA, RecordedKnobs, RecordingInferencePort, RunClaim,
|
||||
ReplayInferencePort, RunField, RunId, RunOutcome, RunStart, RunStatus, TickCheckpoint,
|
||||
TickReport, VerseGenesisError, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore,
|
||||
call_run_id, run_manual,
|
||||
id_text, id_text_matches, table_view,
|
||||
};
|
||||
pub use vault::{VaultError, VaultEvidenceSource};
|
||||
use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
|
|
@ -467,24 +423,6 @@ struct CreateWorld {
|
|||
/// The world's flavor as genesis writes it. `SetLensWeights` may replace
|
||||
/// it later; this command carries what the world began with.
|
||||
lens_weights: LensWeights,
|
||||
/// The grammar the world is bound to for its whole life, or none for an
|
||||
/// open-catalog world. Authored here and nowhere else: genesis installs it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
grammar: Option<GrammarBinding>,
|
||||
/// The era the world is pinned to, authored here and nowhere else: no
|
||||
/// `CommandBody` carries a `WorldEra`, so it is write-once by command
|
||||
/// shape, as `scale_intent` is.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
era: Option<WorldEra>,
|
||||
}
|
||||
|
||||
/// The period of its lore a world is set in. Authored at genesis by the
|
||||
/// consumer that knows what periods its lore has, and never replaced.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct WorldEra {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
/// Unattributed creation intent. World ingress derives ownership, controller
|
||||
|
|
@ -509,9 +447,6 @@ pub struct CreateWorldIntent {
|
|||
/// Required. The library holds no default weights; a consumer states the
|
||||
/// world's flavor or is refused.
|
||||
pub lens_weights: LensWeights,
|
||||
/// The era the world is set in, or none. Pinned at genesis and never
|
||||
/// replaced.
|
||||
pub era: Option<WorldEra>,
|
||||
}
|
||||
|
||||
/// One jurisdiction root as ingress states it. The handle is a string here and
|
||||
|
|
@ -772,10 +707,6 @@ pub enum CommandBody {
|
|||
struct SubjectState {
|
||||
label: String,
|
||||
kind: SubjectKind,
|
||||
/// Written only when a subject declaration is resolved; absent from a
|
||||
/// subject nobody imported, so its digests are unchanged.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
import_key: Option<ImportKey>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
|
|
@ -895,15 +826,6 @@ struct WorldState {
|
|||
/// Authored at creation and never mutated; the one prose the world says
|
||||
/// about itself, projected as guidance to every lane.
|
||||
brief: String,
|
||||
/// Bound by genesis and never written again; absent from a world with no
|
||||
/// grammar, so such a world's state and digests are what they were before
|
||||
/// grammars existed.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
grammar: Option<GrammarBinding>,
|
||||
/// Pinned by genesis and never written again; absent from a world with no
|
||||
/// era, whose state and digests are what they were before eras existed.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
era: Option<WorldEra>,
|
||||
draft_approvals: BTreeSet<PrincipalId>,
|
||||
subjects: BTreeMap<SubjectId, SubjectState>,
|
||||
entities: BTreeMap<EntityId, EntityRecord>,
|
||||
|
|
@ -949,19 +871,6 @@ struct WorldState {
|
|||
/// Pressure *on* each subject, keyed target-major then source. Never empty
|
||||
/// for a present key; no stored zero magnitude.
|
||||
pressures: BTreeMap<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>,
|
||||
/// How each subject regards others: sourced modifiers, never a stored
|
||||
/// opinion (`attitude::opinion` derives it). Never empty for a present key;
|
||||
/// no stored zero delta. Outside every scope digest: attitude constrains no
|
||||
/// precondition. Absent from a world that has none, so such a world's state
|
||||
/// and digests are what they were before attitude existed.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
attitudes: BTreeMap<SubjectId, BTreeMap<AttitudeKey, AttitudeModifier>>,
|
||||
/// The facts the world declares as evidence that a subject carries a trait:
|
||||
/// what a prejudice reads, since a trait modifier applies to a subject only
|
||||
/// while its holder knows one of these. Never empty for a present key.
|
||||
/// Absent when empty, for the same reason as `attitudes`.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
traits: BTreeMap<SubjectId, BTreeMap<TraitName, BTreeSet<EntityId>>>,
|
||||
/// When each subject was last given a decision opportunity it consumed.
|
||||
/// Absence means never. The debt term of the attention order and nothing
|
||||
/// else.
|
||||
|
|
@ -1082,8 +991,6 @@ pub struct SubjectSnapshot {
|
|||
pub id: SubjectId,
|
||||
pub label: String,
|
||||
pub kind: SubjectKind,
|
||||
/// The Aetheria record this subject was imported from, if it was.
|
||||
pub import_key: Option<ImportKey>,
|
||||
/// Absent for an externally controlled mirror, which has no controller and
|
||||
/// no turn. Every reader fails closed on `None`; none gets a default.
|
||||
pub(crate) controller_id: Option<ControllerId>,
|
||||
|
|
@ -1125,11 +1032,6 @@ pub struct SubjectSnapshot {
|
|||
/// subject's state, and the actor already sees the commitment that produced
|
||||
/// it.
|
||||
pub(crate) pressures: Vec<PressureSnapshot>,
|
||||
/// How this subject regards each subject it has an opinion of, derived by
|
||||
/// `attitude::opinion` at snapshot time: never stored, so there is one
|
||||
/// answer for the Dungeon Master's table, a Persona's own view, and the
|
||||
/// narrator. View-only, covered by no digest of its own.
|
||||
pub(crate) opinions: Vec<OpinionSnapshot>,
|
||||
/// This subject's own dependencies, lowered from `components.dependencies`
|
||||
/// (private to this module) so the play table's omniscient view can print
|
||||
/// what a `release` may name without reaching into `ScopeComponents`
|
||||
|
|
@ -1169,17 +1071,6 @@ pub(crate) struct PressureSnapshot {
|
|||
pub(crate) magnitude: PressureMagnitude,
|
||||
}
|
||||
|
||||
/// One subject's derived regard for another, with its strongest causes. A trait
|
||||
/// prejudice appears only once the holder knows the subject carries the trait.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct OpinionSnapshot {
|
||||
pub(crate) toward: SubjectId,
|
||||
/// Clamped to `-MAX_ATTITUDE..=MAX_ATTITUDE`.
|
||||
pub(crate) total: i32,
|
||||
/// At most `OPINION_CAUSES_SHOWN`, strongest first.
|
||||
pub(crate) causes: Vec<attitude::OpinionCause>,
|
||||
}
|
||||
|
||||
/// What a subject knows of one fact. `standing` carries no `EvidenceRef`: a
|
||||
/// receipt is non-fictional provenance and never enters a subject-facing
|
||||
/// surface, so a subject learns *that* a fact is canonical and never which
|
||||
|
|
@ -1242,9 +1133,6 @@ pub(crate) struct ForumSnapshot {
|
|||
pub struct AffordanceSnapshot {
|
||||
pub id: AffordanceId,
|
||||
pub entry: Affordance,
|
||||
/// Derived from the world's grammar by this entry's kind; none when the
|
||||
/// world has no grammar.
|
||||
pub render_path: Option<RenderPath>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
|
|
@ -1307,10 +1195,6 @@ pub struct WorldSnapshot {
|
|||
pub owner: PrincipalId,
|
||||
pub title: String,
|
||||
pub brief: String,
|
||||
/// The era the world was pinned to at genesis; none for a world with no era.
|
||||
pub era: Option<WorldEra>,
|
||||
/// The bound grammar's identity; none for a world with an open catalog.
|
||||
pub grammar: Option<GrammarIdentity>,
|
||||
pub draft_approvals: BTreeSet<PrincipalId>,
|
||||
pub required_approvers: BTreeSet<PrincipalId>,
|
||||
pub subjects: Vec<SubjectSnapshot>,
|
||||
|
|
@ -1342,63 +1226,6 @@ pub struct WorldSnapshot {
|
|||
pub last_commit_digest: Option<String>,
|
||||
}
|
||||
|
||||
impl WorldSnapshot {
|
||||
/// The place a subject stands in, for the owner's own surfaces; no
|
||||
/// subject-facing lane reads this.
|
||||
pub fn place_of(&self, subject: SubjectId) -> Option<EntityId> {
|
||||
self.subjects.iter().find(|candidate| candidate.id == subject)?.position
|
||||
}
|
||||
|
||||
/// The label of the place a subject stands in, for the owner's own
|
||||
/// surfaces and tests; no subject-facing lane reads this.
|
||||
pub fn standing_place(&self, subject: SubjectId) -> Option<&str> {
|
||||
let position = self.place_of(subject)?;
|
||||
self.places.iter().find(|place| place.id == position).map(|place| place.label.as_str())
|
||||
}
|
||||
|
||||
/// The live subjects with a controller other than a human's that stand in
|
||||
/// the same place as `subject`, ascending by id; `subject` itself is never
|
||||
/// among them. For the owner's own surfaces (the Dungeon's room-level
|
||||
/// reaction derives its audience here): no controller lane reads it, since
|
||||
/// one subject must not learn who else stands beside it from a list the
|
||||
/// kernel built for the table.
|
||||
pub fn co_located(&self, subject: SubjectId) -> Vec<SubjectId> {
|
||||
let Some(position) = self
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|candidate| candidate.id == subject)
|
||||
.and_then(|candidate| candidate.position)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut present: Vec<SubjectId> = self
|
||||
.subjects
|
||||
.iter()
|
||||
.filter(|other| {
|
||||
other.id != subject
|
||||
&& !other.retired
|
||||
&& other.position == Some(position)
|
||||
&& matches!(other.controller_mode, Some(mode) if mode != ControllerMode::Human)
|
||||
})
|
||||
.map(|other| other.id)
|
||||
.collect();
|
||||
present.sort();
|
||||
present
|
||||
}
|
||||
|
||||
/// What every lane reads as the world's guidance: the era line, then the
|
||||
/// owner's brief verbatim, either omitted when empty. Derived on every
|
||||
/// read; no prompt reads `brief` directly.
|
||||
pub fn guidance(&self) -> String {
|
||||
let era = self
|
||||
.era
|
||||
.as_ref()
|
||||
.map(|era| format!("Era: {}. {}", era.label, era.description));
|
||||
let brief = (!self.brief.is_empty()).then(|| self.brief.clone());
|
||||
[era, brief].into_iter().flatten().collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
/// One committed act as the human operator's story feed reads it. It is the
|
||||
/// operator surface, not a perception surface: no subject-facing lane receives
|
||||
/// it, and `SelectedDecision` never sees an event log at all.
|
||||
|
|
@ -1409,21 +1236,6 @@ pub struct OperatorEvent {
|
|||
pub speaker_label: String,
|
||||
pub speech: Option<Statement>,
|
||||
pub display: Option<Statement>,
|
||||
/// The affordance kind the act exercised.
|
||||
pub verb: String,
|
||||
/// How the world's grammar renders that verb; none in a world with no
|
||||
/// grammar.
|
||||
pub render_path: Option<RenderPath>,
|
||||
/// What the act bound each of the verb's roles to, in the invocation's
|
||||
/// order.
|
||||
pub roles: Vec<BoundRole>,
|
||||
}
|
||||
|
||||
/// One role an act bound, with the label of what it was bound to.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BoundRole {
|
||||
pub role: String,
|
||||
pub target: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
|
|
@ -1607,23 +1419,11 @@ fn prepare_creation(
|
|||
}
|
||||
let title = normalize_title(&input.title)?;
|
||||
let brief = input.brief.trim().to_owned();
|
||||
if input
|
||||
.era
|
||||
.as_ref()
|
||||
.is_some_and(|era| [&era.id, &era.label, &era.description].iter().any(|text| text.trim().is_empty()))
|
||||
{
|
||||
return Err(KernelError::Invariant("a world era states an id, a label and a description".into()));
|
||||
}
|
||||
// The world's own identity is not world structure, and it feeds every
|
||||
// derived ID, so it is minted before resolution rather than by it.
|
||||
let world_id = WorldId::issue();
|
||||
let resolved = patch::resolve_patch(
|
||||
&WorldState::empty(
|
||||
world_id,
|
||||
input.owner.clone(),
|
||||
title.clone(),
|
||||
input.grammar.clone(),
|
||||
),
|
||||
&WorldState::empty(world_id, input.owner.clone(), title.clone()),
|
||||
input.id,
|
||||
&input.patch,
|
||||
Some(&input.scale_intent),
|
||||
|
|
@ -1721,43 +1521,7 @@ impl WorldKernel {
|
|||
/// no consumer may read in full would be a loaded gun with a comment on it.
|
||||
fn operator_log(&self) -> Result<Vec<OperatorEvent>, KernelError> {
|
||||
self.journal.ensure_healthy()?;
|
||||
// An event records what the world did; the invocation, which names the
|
||||
// bound roles, lives on the commit that produced it.
|
||||
let invocations: BTreeMap<EventId, &DecisionInvocation> = self
|
||||
.journal
|
||||
.commits()
|
||||
.filter_map(|commit| match &commit.effect {
|
||||
WorldEffect::DecisionExercised {
|
||||
invocation, event, ..
|
||||
} => Some((event.id, invocation)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
operator_log(&self.state, &invocations)
|
||||
}
|
||||
|
||||
/// The tick driver's opportunity list, in the same order a snapshot
|
||||
/// carries it. Separate from `snapshot` for the reason `agency_graph` is:
|
||||
/// only the tick driver reads it.
|
||||
fn opportunities(&self) -> Result<Vec<DecisionOpportunity>, KernelError> {
|
||||
self.journal.ensure_healthy()?;
|
||||
Ok(order_opportunities(
|
||||
&self.state,
|
||||
derive_opportunities(&self.state)?,
|
||||
))
|
||||
}
|
||||
|
||||
/// How many clock advances the world has committed: the next tick's
|
||||
/// ordinal, held by the world and read from its journal. Separate from
|
||||
/// `snapshot` for the reason `opportunities` is: only the tick driver
|
||||
/// reads it.
|
||||
fn clock_advances(&self) -> Result<u64, KernelError> {
|
||||
self.journal.ensure_healthy()?;
|
||||
Ok(self
|
||||
.journal
|
||||
.commits()
|
||||
.filter(|commit| matches!(commit.effect, WorldEffect::TimeAdvanced { .. }))
|
||||
.count() as u64)
|
||||
operator_log(&self.state)
|
||||
}
|
||||
|
||||
/// The scheduler's adjacency projection. Separate from `snapshot` for the
|
||||
|
|
@ -1769,14 +1533,6 @@ impl WorldKernel {
|
|||
Ok(agency_graph(&self.state))
|
||||
}
|
||||
|
||||
/// The gestalt hierarchy. Separate from `snapshot` for the reason
|
||||
/// `agency_graph` is: it is wider than any subject view, so a field on
|
||||
/// `WorldSnapshot` would be reachable from every prompt builder.
|
||||
fn hierarchy(&self) -> Result<Hierarchy, KernelError> {
|
||||
self.journal.ensure_healthy()?;
|
||||
Ok(hierarchy::derive_hierarchy(&self.state))
|
||||
}
|
||||
|
||||
fn submit(
|
||||
&mut self,
|
||||
command: CommandEnvelope,
|
||||
|
|
@ -2138,12 +1894,7 @@ impl WorldState {
|
|||
/// The world before any structure. Genesis resolves its own patch against
|
||||
/// this value, so the genesis lane and `AdmitPatch` share one resolver
|
||||
/// signature instead of hand-passing empty partitions.
|
||||
fn empty(
|
||||
world_id: WorldId,
|
||||
owner: PrincipalId,
|
||||
title: String,
|
||||
grammar: Option<GrammarBinding>,
|
||||
) -> Self {
|
||||
fn empty(world_id: WorldId, owner: PrincipalId, title: String) -> Self {
|
||||
Self {
|
||||
schema: STATE_SCHEMA.into(),
|
||||
world_id,
|
||||
|
|
@ -2152,8 +1903,6 @@ impl WorldState {
|
|||
owner,
|
||||
title,
|
||||
brief: String::new(),
|
||||
grammar,
|
||||
era: None,
|
||||
draft_approvals: BTreeSet::new(),
|
||||
subjects: BTreeMap::new(),
|
||||
entities: BTreeMap::new(),
|
||||
|
|
@ -2170,8 +1919,6 @@ impl WorldState {
|
|||
commitments: BTreeMap::new(),
|
||||
persona_material: BTreeMap::new(),
|
||||
pressures: BTreeMap::new(),
|
||||
attitudes: BTreeMap::new(),
|
||||
traits: BTreeMap::new(),
|
||||
last_opportunity_at: BTreeMap::new(),
|
||||
now: FictionalMinutes::default(),
|
||||
scale_intent: WorldScaleIntent::default(),
|
||||
|
|
@ -2213,9 +1960,8 @@ impl WorldState {
|
|||
// The same re-derive-and-compare that `apply_committed_command` runs for
|
||||
// every other command. Deterministic allocation is what lets one
|
||||
// equality replace a field-by-field binding zip.
|
||||
let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone());
|
||||
let mut state = Self::empty(world_id, owner.clone(), title.clone());
|
||||
state.brief = brief.clone();
|
||||
state.era = command.era.clone();
|
||||
let expected = patch::resolve_patch(
|
||||
&state,
|
||||
command.id,
|
||||
|
|
@ -2323,18 +2069,6 @@ fn admit_resolved(
|
|||
.filter_map(ControllerAssignment::id)
|
||||
.collect();
|
||||
for entry in &resolved.affordances {
|
||||
// The catalog's only writer holds the same grammar check the resolver
|
||||
// runs, so an effect resolved elsewhere cannot install an entry the
|
||||
// bound grammar refuses.
|
||||
if state.grammar.as_ref().is_some_and(|grammar| {
|
||||
grammar
|
||||
.refusal(&entry.affordance.kind, &entry.affordance.roles)
|
||||
.is_some()
|
||||
}) {
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted affordance is outside the bound grammar".into(),
|
||||
));
|
||||
}
|
||||
if state
|
||||
.affordance_catalog
|
||||
.insert(entry.affordance_id, entry.affordance.clone())
|
||||
|
|
@ -2345,21 +2079,6 @@ fn admit_resolved(
|
|||
));
|
||||
}
|
||||
}
|
||||
// The subjects map's only writer holds the same injectivity the resolver
|
||||
// checks, decided by the same function.
|
||||
{
|
||||
let held = patch::held_import_keys(state.subjects.values());
|
||||
let mut declared = BTreeSet::new();
|
||||
for subject in &resolved.subjects {
|
||||
if let Some(key) = &subject.subject.import_key
|
||||
&& patch::import_key_fault(key, &held, &mut declared).is_some()
|
||||
{
|
||||
return Err(KernelError::Invariant(
|
||||
"admitted subject's import key is malformed, held or repeated".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
for subject in &resolved.subjects {
|
||||
let scope = DecisionScope {
|
||||
subject_id: subject.subject_id,
|
||||
|
|
@ -3370,50 +3089,6 @@ fn apply_operation(
|
|||
}
|
||||
set_pressure(state, *target, *source, 0);
|
||||
}
|
||||
ResolvedOp::AdjustAttitude {
|
||||
holder,
|
||||
key,
|
||||
delta,
|
||||
decay,
|
||||
} => {
|
||||
let regards_live = match &key.toward {
|
||||
AttitudeToward::Subject(target) => state.subjects.contains_key(target),
|
||||
AttitudeToward::Trait(name) => patch::is_civic_name(&name.0),
|
||||
};
|
||||
let rests_on_known = match &key.cause {
|
||||
AttitudeCause::Rumour { fact } => state.facts.contains_key(fact),
|
||||
_ => true,
|
||||
};
|
||||
if !state.subjects.contains_key(holder)
|
||||
|| !regards_live
|
||||
|| !rests_on_known
|
||||
|| !attitude::is_valid_delta(*delta)
|
||||
|| !attitude::is_valid_decay(*decay)
|
||||
|| key.toward == AttitudeToward::Subject(*holder)
|
||||
{
|
||||
return Err(unknown());
|
||||
}
|
||||
attitude::adjust(state, *holder, key.clone(), *delta, *decay);
|
||||
}
|
||||
ResolvedOp::DeclareTrait {
|
||||
subject,
|
||||
name,
|
||||
fact,
|
||||
} => {
|
||||
if !state.subjects.contains_key(subject)
|
||||
|| !state.facts.contains_key(fact)
|
||||
|| !patch::is_civic_name(&name.0)
|
||||
{
|
||||
return Err(unknown());
|
||||
}
|
||||
state
|
||||
.traits
|
||||
.entry(*subject)
|
||||
.or_default()
|
||||
.entry(name.clone())
|
||||
.or_default()
|
||||
.insert(*fact);
|
||||
}
|
||||
ResolvedOp::Retire { subject } => {
|
||||
let scope = DecisionScope {
|
||||
subject_id: *subject,
|
||||
|
|
@ -3988,10 +3663,7 @@ fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponent
|
|||
/// The human operator's story feed, derived from the causal record. The events
|
||||
/// log is not a perception surface: `knowledge` is the sole answer to what a
|
||||
/// subject may act on and what its projection may contain.
|
||||
fn operator_log(
|
||||
state: &WorldState,
|
||||
invocations: &BTreeMap<EventId, &DecisionInvocation>,
|
||||
) -> Result<Vec<OperatorEvent>, KernelError> {
|
||||
fn operator_log(state: &WorldState) -> Result<Vec<OperatorEvent>, KernelError> {
|
||||
state
|
||||
.events
|
||||
.iter()
|
||||
|
|
@ -4000,30 +3672,6 @@ fn operator_log(
|
|||
.subjects
|
||||
.get(&event.scope.subject_id)
|
||||
.ok_or_else(|| KernelError::Invariant("event names no live subject".into()))?;
|
||||
let invocation = invocations.get(&event.id).ok_or_else(|| {
|
||||
KernelError::Invariant("event has no committed invocation".into())
|
||||
})?;
|
||||
let entry = state
|
||||
.affordance_catalog
|
||||
.get(&event.affordance)
|
||||
.ok_or_else(|| KernelError::Invariant("event names no catalog entry".into()))?;
|
||||
let roles = invocation
|
||||
.bindings
|
||||
.iter()
|
||||
.map(|binding| {
|
||||
let label = match binding.target {
|
||||
Target::Subject(id) => state.subjects.get(&id).map(|s| s.label.clone()),
|
||||
Target::Entity(id) => state.entities.get(&id).map(|e| e.label.clone()),
|
||||
Target::Edge(id) => state.edges.contains_key(&id).then(|| "edge".to_owned()),
|
||||
};
|
||||
label
|
||||
.map(|target| BoundRole {
|
||||
role: binding.role.0.clone(),
|
||||
target,
|
||||
})
|
||||
.ok_or_else(|| KernelError::Invariant("event binds no live referent".into()))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(OperatorEvent {
|
||||
revision: event.revision,
|
||||
speaker: event.scope.subject_id,
|
||||
|
|
@ -4036,13 +3684,6 @@ fn operator_log(
|
|||
.display
|
||||
.and_then(|fact| state.facts.get(&fact))
|
||||
.map(|record| record.statement.clone()),
|
||||
verb: entry.kind.0.clone(),
|
||||
render_path: state
|
||||
.grammar
|
||||
.as_ref()
|
||||
.and_then(|grammar| grammar.verb(&entry.kind.0))
|
||||
.map(|verb| verb.render_path),
|
||||
roles,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
|
|
@ -4321,7 +3962,6 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
|
|||
id: *subject_id,
|
||||
label: subject.label.clone(),
|
||||
kind: subject.kind,
|
||||
import_key: subject.import_key.clone(),
|
||||
controller_id: controller.id(),
|
||||
controller_mode: controller.mode(),
|
||||
human_controller: controller.human_principal().cloned(),
|
||||
|
|
@ -4358,17 +3998,6 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
|
|||
magnitude: *magnitude,
|
||||
})
|
||||
.collect(),
|
||||
opinions: attitude::opinions_held(state, *subject_id)
|
||||
.into_iter()
|
||||
.map(|(toward, mut held)| {
|
||||
held.causes.truncate(attitude::OPINION_CAUSES_SHOWN);
|
||||
OpinionSnapshot {
|
||||
toward,
|
||||
total: held.total,
|
||||
causes: held.causes,
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
qualified: qualifies(state, *subject_id),
|
||||
last_acted_at: last_acted_at.get(subject_id).copied(),
|
||||
})
|
||||
|
|
@ -4448,8 +4077,6 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
|
|||
owner: state.owner.clone(),
|
||||
title: state.title.clone(),
|
||||
brief: state.brief.clone(),
|
||||
era: state.era.clone(),
|
||||
grammar: state.grammar.as_ref().map(GrammarBinding::identity),
|
||||
draft_approvals: state.draft_approvals.clone(),
|
||||
required_approvers: required_approvers(state),
|
||||
subjects,
|
||||
|
|
@ -4459,11 +4086,6 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
|
|||
.map(|(affordance_id, entry)| AffordanceSnapshot {
|
||||
id: *affordance_id,
|
||||
entry: entry.clone(),
|
||||
render_path: state
|
||||
.grammar
|
||||
.as_ref()
|
||||
.and_then(|grammar| grammar.verb(&entry.kind.0))
|
||||
.map(|verb| verb.render_path),
|
||||
})
|
||||
.collect(),
|
||||
places,
|
||||
|
|
@ -5472,16 +5094,6 @@ fn operation_ground(
|
|||
}
|
||||
(subjects, places(named), routes)
|
||||
}
|
||||
// An attitude is the holder's own state about another subject, so both
|
||||
// are ground; a trait names none.
|
||||
ResolvedOp::AdjustAttitude { holder, key, .. } => {
|
||||
let mut subjects = vec![*holder];
|
||||
if let AttitudeToward::Subject(target) = &key.toward {
|
||||
subjects.push(*target);
|
||||
}
|
||||
(subjects, Vec::new(), Vec::new())
|
||||
}
|
||||
ResolvedOp::DeclareTrait { subject, .. } => (vec![*subject], Vec::new(), Vec::new()),
|
||||
// Confinement never reaches these through the ordinary ground check:
|
||||
// `confine_to_ground` refuses `Retire`, `GrantAffordance`, and
|
||||
// `RevokeAffordance` unconditionally for every confined author before
|
||||
|
|
@ -5824,7 +5436,6 @@ mod tests {
|
|||
// The fixture world is one room. Co-located speech needs a place to
|
||||
// fill, so every fixture subject stands in the commons.
|
||||
position: Some(Ref::Draft(DraftHandle::new(COMMONS))),
|
||||
import_key: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -5927,14 +5538,11 @@ mod tests {
|
|||
.chain(std::iter::once(Ref::Draft(DraftHandle::new("convene"))))
|
||||
.collect(),
|
||||
position: Some(Ref::Draft(DraftHandle::new(COMMONS))),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
},
|
||||
scale_intent: WorldScaleIntentRef::default(),
|
||||
lens_weights: stock_weights(),
|
||||
grammar: None,
|
||||
era: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -6079,7 +5687,6 @@ mod tests {
|
|||
controller: NewController::OperationalAgent,
|
||||
affordances: BTreeSet::from([speak]),
|
||||
position: Some(Ref::Draft(DraftHandle::new("yard"))),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
// A route that should start closed is declared and closed in one
|
||||
|
|
@ -6185,7 +5792,6 @@ mod tests {
|
|||
}))
|
||||
.collect(),
|
||||
position: Some(Ref::Existing(place)),
|
||||
import_key: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -6706,7 +6312,6 @@ mod tests {
|
|||
controller: NewController::OperationalAgent,
|
||||
affordances: civic_grants(handles, &speak),
|
||||
position: Some(place),
|
||||
import_key: None,
|
||||
})
|
||||
};
|
||||
let declarations = civic_affordances()
|
||||
|
|
@ -6763,7 +6368,6 @@ mod tests {
|
|||
&speak,
|
||||
),
|
||||
position: Some(Ref::Draft(DraftHandle::new("hall"))),
|
||||
import_key: None,
|
||||
}),
|
||||
Declaration::Subject(SubjectDeclaration {
|
||||
handle: DraftHandle::new("reeve"),
|
||||
|
|
@ -6775,7 +6379,6 @@ mod tests {
|
|||
&speak,
|
||||
),
|
||||
position: Some(Ref::Draft(DraftHandle::new("chamber"))),
|
||||
import_key: None,
|
||||
}),
|
||||
person(
|
||||
"farmer",
|
||||
|
|
@ -6799,7 +6402,6 @@ mod tests {
|
|||
controller: NewController::NarrativePersona,
|
||||
affordances: civic_grants(&["levy", "petition"], &speak),
|
||||
position: None,
|
||||
import_key: None,
|
||||
}),
|
||||
])
|
||||
.collect();
|
||||
|
|
@ -6963,7 +6565,6 @@ mod tests {
|
|||
Ref::Draft(DraftHandle::new("recant")),
|
||||
]),
|
||||
position: place.map(|place| Ref::Draft(DraftHandle::new(place))),
|
||||
import_key: None,
|
||||
})
|
||||
};
|
||||
submit_owner(
|
||||
|
|
@ -8232,7 +7833,6 @@ mod tests {
|
|||
controller: NewController::OperationalAgent,
|
||||
affordances: BTreeSet::from([speak.clone()]),
|
||||
position: Some(Ref::Existing(topology.road)),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
operations: Vec::new(),
|
||||
|
|
@ -9251,7 +8851,6 @@ mod custody_tests {
|
|||
controller: NewController::OperationalAgent,
|
||||
affordances: BTreeSet::from([speak.clone()]),
|
||||
position: Some(Ref::Existing(topology.yard)),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
operations: vec![ComponentOp::Admit {
|
||||
|
|
@ -9911,7 +9510,6 @@ mod custody_tests {
|
|||
controller: NewController::OperationalAgent,
|
||||
affordances: BTreeSet::from([speak.clone()]),
|
||||
position: Some(Ref::Existing(topology.yard)),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
operations: vec![admit(u64::MAX), admit(1)],
|
||||
|
|
@ -11838,7 +11436,7 @@ mod soul_knowledge_tests {
|
|||
// Nobody holds it.
|
||||
assert!(kernel.state.knowledge.is_empty());
|
||||
// The operator reads it anyway, with the speaker resolved by label.
|
||||
let log = kernel.operator_log().unwrap();
|
||||
let log = operator_log(&kernel.state).unwrap();
|
||||
assert_eq!(
|
||||
log,
|
||||
vec![OperatorEvent {
|
||||
|
|
@ -11847,9 +11445,6 @@ mod soul_knowledge_tests {
|
|||
speaker_label: "The Yard Bystander".into(),
|
||||
speech: Some(Statement::new(text).unwrap()),
|
||||
display: None,
|
||||
verb: "speak".into(),
|
||||
render_path: None,
|
||||
roles: Vec::new(),
|
||||
}]
|
||||
);
|
||||
// And no subject snapshot carries it.
|
||||
|
|
@ -11907,7 +11502,6 @@ mod witness_tests {
|
|||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([speak.clone(), Ref::Draft(DraftHandle::new("beacon"))]),
|
||||
position: Some(Ref::Draft(DraftHandle::new(place))),
|
||||
import_key: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -13021,7 +12615,6 @@ mod witness_tests {
|
|||
// Every non-mirror subject must hold one.
|
||||
affordances: BTreeSet::from([Ref::Existing(beacon)]),
|
||||
position: position.map(Ref::Existing),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
operations: vec![witness(
|
||||
|
|
@ -13335,8 +12928,6 @@ mod clock_tests {
|
|||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
mod attitude_tests;
|
||||
|
||||
/// The canonical IDs of the clock fixture: a hall containing a yard, a
|
||||
/// dead end reached by exactly one route, three subjects, a resource, and
|
||||
/// one commitment of each kind.
|
||||
|
|
@ -13388,7 +12979,6 @@ mod clock_tests {
|
|||
Ref::Draft(DraftHandle::new("threaten")),
|
||||
]),
|
||||
position: Some(Ref::Draft(DraftHandle::new(place))),
|
||||
import_key: None,
|
||||
})
|
||||
};
|
||||
let subject = |handle: &str| Ref::Draft(DraftHandle::new(handle));
|
||||
|
|
@ -15465,53 +15055,6 @@ mod clock_tests {
|
|||
assert_eq!(replayed.state.state_digest, created.state_digest);
|
||||
}
|
||||
|
||||
fn late_sol() -> WorldEra {
|
||||
WorldEra { id: "late-sol".into(), label: "Late Sol".into(), description: "The old order fails.".into() }
|
||||
}
|
||||
|
||||
/// Genesis pins the era, replay restores it, and the only command that
|
||||
/// can touch a world's flavor afterward leaves it alone: no `CommandBody`
|
||||
/// carries a `WorldEra`.
|
||||
#[test]
|
||||
fn genesis_pins_the_era_and_nothing_replaces_it() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("world.cc");
|
||||
let mut input = creation(CommandId::new(), "Pinned");
|
||||
input.era = Some(late_sol());
|
||||
let (kernel, _) = WorldKernel::create(&path, input, &auth_principal(owner())).unwrap();
|
||||
let created = kernel.snapshot().unwrap();
|
||||
assert_eq!(created.era, Some(late_sol()));
|
||||
let world_id = created.world_id;
|
||||
drop(kernel);
|
||||
let replayed = WorldKernel::open(&path, world_id).unwrap();
|
||||
assert_eq!(replayed.snapshot().unwrap().era, Some(late_sol()));
|
||||
assert_eq!(replayed.state.state_digest, created.state_digest);
|
||||
|
||||
let mut blank = creation(CommandId::new(), "Blank Era");
|
||||
blank.era = Some(WorldEra { description: " ".into(), ..late_sol() });
|
||||
let refused = WorldKernel::create(&directory.path().join("blank.cc"), blank, &auth_principal(owner()));
|
||||
assert!(matches!(refused, Err(KernelError::Invariant(_))));
|
||||
}
|
||||
|
||||
/// Every lane reads this string: era first, then the brief verbatim,
|
||||
/// either omitted when empty; nothing at all when both are.
|
||||
#[test]
|
||||
fn guidance_is_the_era_then_the_brief_and_empty_when_neither() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut snapshots = Vec::new();
|
||||
for (name, era, brief) in [("a", Some(late_sol()), "Speak plainly."), ("b", Some(late_sol()), ""), ("c", None, "Speak plainly."), ("d", None, "")] {
|
||||
let mut input = creation(CommandId::new(), name);
|
||||
input.era = era;
|
||||
input.brief = brief.into();
|
||||
let (kernel, _) = WorldKernel::create(&directory.path().join(format!("{name}.cc")), input, &auth_principal(owner())).unwrap();
|
||||
snapshots.push(kernel.snapshot().unwrap().guidance());
|
||||
}
|
||||
assert_eq!(
|
||||
snapshots,
|
||||
["Era: Late Sol. The old order fails.\nSpeak plainly.", "Era: Late Sol. The old order fails.", "Speak plainly.", ""]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_genesis_lens_set_that_never_draws_is_refused() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
|
|
@ -15617,7 +15160,7 @@ mod clock_tests {
|
|||
}));
|
||||
let title = normalize_title(&input.title).unwrap();
|
||||
let resolved = patch::resolve_patch(
|
||||
&WorldState::empty(world_id, input.owner.clone(), title.clone(), None),
|
||||
&WorldState::empty(world_id, input.owner.clone(), title.clone()),
|
||||
input.id,
|
||||
&input.patch,
|
||||
Some(&input.scale_intent),
|
||||
|
|
@ -15646,7 +15189,7 @@ mod clock_tests {
|
|||
});
|
||||
let title = normalize_title(&input.title).unwrap();
|
||||
let resolved = patch::resolve_patch(
|
||||
&WorldState::empty(world_id, input.owner.clone(), title.clone(), None),
|
||||
&WorldState::empty(world_id, input.owner.clone(), title.clone()),
|
||||
input.id,
|
||||
&input.patch,
|
||||
Some(&input.scale_intent),
|
||||
|
|
@ -17489,7 +17032,6 @@ mod clock_tests {
|
|||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([speak]),
|
||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
operations: Vec::new(),
|
||||
|
|
@ -17556,7 +17098,6 @@ mod clock_tests {
|
|||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([speak]),
|
||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
operations: Vec::new(),
|
||||
|
|
@ -17634,7 +17175,6 @@ mod clock_tests {
|
|||
},
|
||||
affordances: BTreeSet::new(),
|
||||
position: Some(Ref::Existing(commons)),
|
||||
import_key: None,
|
||||
})],
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
|
|
@ -17728,7 +17268,6 @@ mod clock_tests {
|
|||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([speak]),
|
||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
operations: vec![ComponentOp::Mint {
|
||||
|
|
@ -17971,7 +17510,6 @@ mod clock_tests {
|
|||
// the boundary its own answer claims: an occupied
|
||||
// place is no longer unelaborated.
|
||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||
import_key: None,
|
||||
})],
|
||||
operations: Vec::new(),
|
||||
evidence: Vec::new(),
|
||||
|
|
@ -18150,7 +17688,6 @@ mod clock_tests {
|
|||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([speak]),
|
||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||
import_key: None,
|
||||
})],
|
||||
operations: vec![ComponentOp::Retire {
|
||||
subject: Ref::Draft(DraftHandle::new("stray")),
|
||||
|
|
@ -18260,7 +17797,6 @@ mod clock_tests {
|
|||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([speak]),
|
||||
position: Some(Ref::Existing(commons)),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
operations: vec![ComponentOp::GrantAffordance {
|
||||
|
|
@ -18475,7 +18011,6 @@ mod clock_tests {
|
|||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([speak]),
|
||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||
import_key: None,
|
||||
})],
|
||||
operations: vec![ComponentOp::GrantAffordance {
|
||||
subject: Ref::Draft(DraftHandle::new("stray")),
|
||||
|
|
@ -18894,7 +18429,6 @@ mod clock_tests {
|
|||
Ref::Existing(clockwork.threaten),
|
||||
]),
|
||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||
import_key: None,
|
||||
})],
|
||||
operations: vec![ComponentOp::RevokeAffordance {
|
||||
subject: Ref::Draft(DraftHandle::new("stray")),
|
||||
|
|
@ -19343,7 +18877,6 @@ mod clock_tests {
|
|||
controller: NewController::NarrativePersona,
|
||||
affordances: BTreeSet::from([speak.clone()]),
|
||||
position: None,
|
||||
import_key: None,
|
||||
}),
|
||||
Declaration::Channel(ChannelDeclaration {
|
||||
handle: DraftHandle::new("wire"),
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,15 +1,13 @@
|
|||
use super::{
|
||||
AgencyGraph, AuthenticatedCaller, Hierarchy, CallerId, CommandBody, CommandEnvelope, CommandId,
|
||||
AgencyGraph, AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId,
|
||||
ConsumerId, CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation,
|
||||
DecisionOpportunity, Declaration, DraftHandle, EntityDeclaration, EntityKind, JurisdictionKey,
|
||||
KernelError, NewController, OperatorEvent, PatchAnswer, PrincipalCommandIntent, PrincipalId,
|
||||
EntityId, Ref, SubjectDeclaration, SubjectKind, SubmitReceipt, SystemCapability, TickMinutes, WorldId,
|
||||
Ref, SubjectDeclaration, SubjectKind, SubmitReceipt, SystemCapability, TickMinutes, WorldId,
|
||||
WorldKernel, WorldPatch, WorldPhase, WorldScaleIntentRef, WorldSnapshot, journal,
|
||||
patch::kernel_speak_grant, prepare_creation,
|
||||
verse::{CreateVerseWorldIntent, VerseGenesisError},
|
||||
};
|
||||
use crate::patch::{AccessKind, ComponentOp, Cost, RouteDeclaration};
|
||||
use crate::{SubjectId, VerifiedPrincipalEvidence};
|
||||
use crate::VerifiedPrincipalEvidence;
|
||||
use chrono::Utc;
|
||||
use std::path::Path;
|
||||
use thiserror::Error;
|
||||
|
|
@ -20,21 +18,6 @@ use tokio::task::JoinHandle;
|
|||
/// other. A world that wants more declares them through the patch lane.
|
||||
const GENESIS_PLACE: &str = "commons";
|
||||
|
||||
/// The commons every genesis declares, the one room its first subjects share.
|
||||
pub(crate) fn commons_declaration() -> Declaration {
|
||||
Declaration::Entity(EntityDeclaration {
|
||||
handle: DraftHandle::new(GENESIS_PLACE),
|
||||
label: "The Commons".into(),
|
||||
kind: EntityKind::Place,
|
||||
container: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a genesis subject stands.
|
||||
pub(crate) fn commons_ref() -> Ref<EntityId> {
|
||||
Ref::Draft(DraftHandle::new(GENESIS_PLACE))
|
||||
}
|
||||
|
||||
const REQUEST_CAPACITY: usize = 32;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
|
@ -83,21 +66,6 @@ enum Request {
|
|||
AgencyGraph {
|
||||
reply: oneshot::Sender<Result<AgencyGraph, KernelError>>,
|
||||
},
|
||||
/// The gestalt hierarchy, derived from world state. Separate from
|
||||
/// `Snapshot` as `AgencyGraph` is: only the tick driver may hold it.
|
||||
Hierarchy {
|
||||
reply: oneshot::Sender<Result<Hierarchy, KernelError>>,
|
||||
},
|
||||
/// The tick driver's opportunity list. Separate from `Snapshot` so the
|
||||
/// list a cover is derived from has one door, held by the driver.
|
||||
Opportunities {
|
||||
reply: oneshot::Sender<Result<Vec<DecisionOpportunity>, KernelError>>,
|
||||
},
|
||||
/// The tick ordinal's one door: how many clock advances the world has
|
||||
/// committed. Held by the tick driver, as `Opportunities` is.
|
||||
ClockAdvances {
|
||||
reply: oneshot::Sender<Result<u64, KernelError>>,
|
||||
},
|
||||
ControllerReceipt {
|
||||
command_id: CommandId,
|
||||
opportunity: super::DecisionOpportunity,
|
||||
|
|
@ -152,8 +120,7 @@ impl WorldMailbox {
|
|||
kind,
|
||||
controller,
|
||||
affordances: kernel_speak_grant(),
|
||||
position: Some(commons_ref()),
|
||||
import_key: None,
|
||||
position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))),
|
||||
})
|
||||
};
|
||||
// Roots stand beside the commons, not inside it: a root contained by
|
||||
|
|
@ -162,7 +129,12 @@ impl WorldMailbox {
|
|||
// jurisdiction's population target. The owner subject lands in
|
||||
// `Uncovered`, visible and reducing nothing.
|
||||
let mut declarations = vec![
|
||||
commons_declaration(),
|
||||
Declaration::Entity(EntityDeclaration {
|
||||
handle: DraftHandle::new(GENESIS_PLACE),
|
||||
label: "The Commons".into(),
|
||||
kind: EntityKind::Place,
|
||||
container: None,
|
||||
}),
|
||||
declare(
|
||||
"first-person",
|
||||
input.human_subject_label,
|
||||
|
|
@ -217,8 +189,6 @@ impl WorldMailbox {
|
|||
},
|
||||
scale_intent,
|
||||
lens_weights: input.lens_weights,
|
||||
grammar: None,
|
||||
era: input.era,
|
||||
},
|
||||
AuthenticatedCaller::verified_principal(principal_id),
|
||||
)
|
||||
|
|
@ -247,20 +217,6 @@ impl WorldMailbox {
|
|||
.map_err(mailbox_outcome)
|
||||
}
|
||||
|
||||
/// Creates the canonical Aetheria verse world through the same
|
||||
/// authenticated creation `create` uses.
|
||||
pub async fn create_verse(
|
||||
&self,
|
||||
intent: CreateVerseWorldIntent,
|
||||
principal: &VerifiedPrincipalEvidence,
|
||||
) -> Result<CreationReceipt, VerseGenesisError> {
|
||||
let principal_id = PrincipalId::new(principal.account_subject_hash());
|
||||
let input = intent.lower(principal_id.clone())?;
|
||||
Ok(self
|
||||
.create_authenticated(input, AuthenticatedCaller::verified_principal(principal_id))
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// A wall-clock read at the boundary a request crosses into the mailbox is
|
||||
/// ingress, not reduce: the reducer stays deterministic over its journal,
|
||||
/// and this is the one place a caller's own claim of continued authority
|
||||
|
|
@ -503,54 +459,6 @@ impl WorldMailbox {
|
|||
.map_err(MailboxError::Kernel)
|
||||
}
|
||||
|
||||
/// The tick driver's projection of the gestalt hierarchy, derived afresh
|
||||
/// from the world on every call. It is on `WorldMailbox` and on neither
|
||||
/// `ControllerPort` nor `ElaborationPort`, as `agency_graph` is: the tree
|
||||
/// is wider than any subject view.
|
||||
pub async fn hierarchy(&self) -> Result<Hierarchy, MailboxError> {
|
||||
let (reply, response) = oneshot::channel();
|
||||
self.sender
|
||||
.send(Request::Hierarchy { reply })
|
||||
.await
|
||||
.map_err(|_| MailboxError::Unavailable)?;
|
||||
|
||||
response
|
||||
.await
|
||||
.map_err(|_| MailboxError::Unavailable)?
|
||||
.map_err(MailboxError::Kernel)
|
||||
}
|
||||
|
||||
/// The tick driver's opportunity list, in snapshot order. It is on
|
||||
/// `WorldMailbox` and on no controller port, as `agency_graph` is.
|
||||
pub async fn opportunities(&self) -> Result<Vec<DecisionOpportunity>, MailboxError> {
|
||||
let (reply, response) = oneshot::channel();
|
||||
self.sender
|
||||
.send(Request::Opportunities { reply })
|
||||
.await
|
||||
.map_err(|_| MailboxError::Unavailable)?;
|
||||
|
||||
response
|
||||
.await
|
||||
.map_err(|_| MailboxError::Unavailable)?
|
||||
.map_err(MailboxError::Kernel)
|
||||
}
|
||||
|
||||
/// The tick driver's ordinal: how many clock advances the world has
|
||||
/// committed. It is on `WorldMailbox` and on no controller port, as
|
||||
/// `opportunities` is.
|
||||
pub async fn clock_advances(&self) -> Result<u64, MailboxError> {
|
||||
let (reply, response) = oneshot::channel();
|
||||
self.sender
|
||||
.send(Request::ClockAdvances { reply })
|
||||
.await
|
||||
.map_err(|_| MailboxError::Unavailable)?;
|
||||
|
||||
response
|
||||
.await
|
||||
.map_err(|_| MailboxError::Unavailable)?
|
||||
.map_err(MailboxError::Kernel)
|
||||
}
|
||||
|
||||
pub async fn operator_log(&self) -> Result<Vec<OperatorEvent>, MailboxError> {
|
||||
let (reply, response) = oneshot::channel();
|
||||
self.sender
|
||||
|
|
@ -740,98 +648,6 @@ impl SeedPort {
|
|||
}
|
||||
}
|
||||
|
||||
impl SeedPort {
|
||||
/// Stands the world's first person among people. Genesis puts the human at
|
||||
/// the commons, which a seed never populates, so the first turn would open
|
||||
/// in an empty room. This moves the human to the most populated place the
|
||||
/// seed declared (ties to the lowest label, then id) through one declared
|
||||
/// route that the same patch closes behind them, and answers where they
|
||||
/// now stand, or `None` when there is nothing to change: no seeded place
|
||||
/// has anyone in it, or the human already stands in one. Draft only, like
|
||||
/// every seed submission.
|
||||
pub async fn stand_first_person_among_people(
|
||||
&self,
|
||||
command_id: CommandId,
|
||||
world_id: WorldId,
|
||||
) -> Result<Option<String>, MailboxError> {
|
||||
let snapshot = self.mailbox.snapshot().await?;
|
||||
let Some(spawn) = first_person_spawn(&snapshot) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let route = Ref::Draft(DraftHandle::new("spawn-route"));
|
||||
let patch = WorldPatch {
|
||||
declarations: vec![Declaration::Route(RouteDeclaration {
|
||||
handle: DraftHandle::new("spawn-route"),
|
||||
label: "the way in".into(),
|
||||
from: Ref::Existing(spawn.from),
|
||||
to: Ref::Existing(spawn.to),
|
||||
access: AccessKind::Public,
|
||||
cost: Cost(1),
|
||||
})],
|
||||
operations: vec![
|
||||
ComponentOp::Relocate {
|
||||
subject: Ref::Existing(spawn.subject),
|
||||
via: route.clone(),
|
||||
},
|
||||
ComponentOp::CloseRoute { route },
|
||||
],
|
||||
evidence: Vec::new(),
|
||||
};
|
||||
self.submit_seed(command_id, world_id, patch).await?;
|
||||
Ok(Some(spawn.label))
|
||||
}
|
||||
}
|
||||
|
||||
struct FirstPersonSpawn {
|
||||
subject: SubjectId,
|
||||
from: EntityId,
|
||||
to: EntityId,
|
||||
label: String,
|
||||
}
|
||||
|
||||
/// The human's move, read from the snapshot alone: to the seeded place (one
|
||||
/// with a container; the commons and the jurisdiction roots have none) holding
|
||||
/// the most other subjects.
|
||||
fn first_person_spawn(snapshot: &WorldSnapshot) -> Option<FirstPersonSpawn> {
|
||||
let human = snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|subject| subject.controller_mode == Some(crate::ControllerMode::Human) && !subject.retired)?;
|
||||
let from = human.position?;
|
||||
let seeded = |id: EntityId| {
|
||||
snapshot
|
||||
.places
|
||||
.iter()
|
||||
.any(|place| place.id == id && place.container.is_some())
|
||||
};
|
||||
if seeded(from) {
|
||||
return None;
|
||||
}
|
||||
let population = |place: &crate::PlaceSnapshot| {
|
||||
snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.filter(|other| other.id != human.id && !other.retired && other.position == Some(place.id))
|
||||
.count()
|
||||
};
|
||||
let (count, place) = snapshot
|
||||
.places
|
||||
.iter()
|
||||
.filter(|place| place.container.is_some())
|
||||
.map(|place| (population(place), place))
|
||||
.min_by(|(a, place_a), (b, place_b)| {
|
||||
b.cmp(a)
|
||||
.then_with(|| place_a.label.cmp(&place_b.label))
|
||||
.then_with(|| place_a.id.cmp(&place_b.id))
|
||||
})?;
|
||||
(count > 0).then(|| FirstPersonSpawn {
|
||||
subject: human.id,
|
||||
from,
|
||||
to: place.id,
|
||||
label: place.label.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The play table's one door. Minted only by Dungeon, which constructs one
|
||||
/// `PlayPort` in its `AppState`; exclusivity is that single construction site,
|
||||
/// pinned by a negative grep, exactly as every other system capability's is.
|
||||
|
|
@ -1112,45 +928,6 @@ async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver<Request>)
|
|||
return;
|
||||
}
|
||||
}
|
||||
Request::Hierarchy { reply } => {
|
||||
let result = match &owned {
|
||||
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
|
||||
OwnedWorld::Live(kernel) => kernel.hierarchy(),
|
||||
};
|
||||
let owner_must_stop = result
|
||||
.as_ref()
|
||||
.is_err_and(KernelError::requires_owner_restart);
|
||||
let _ = reply.send(result);
|
||||
if owner_must_stop {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Request::Opportunities { reply } => {
|
||||
let result = match &owned {
|
||||
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
|
||||
OwnedWorld::Live(kernel) => kernel.opportunities(),
|
||||
};
|
||||
let owner_must_stop = result
|
||||
.as_ref()
|
||||
.is_err_and(KernelError::requires_owner_restart);
|
||||
let _ = reply.send(result);
|
||||
if owner_must_stop {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Request::ClockAdvances { reply } => {
|
||||
let result = match &owned {
|
||||
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
|
||||
OwnedWorld::Live(kernel) => kernel.clock_advances(),
|
||||
};
|
||||
let owner_must_stop = result
|
||||
.as_ref()
|
||||
.is_err_and(KernelError::requires_owner_restart);
|
||||
let _ = reply.send(result);
|
||||
if owner_must_stop {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Request::ControllerReceipt {
|
||||
command_id,
|
||||
opportunity,
|
||||
|
|
@ -1211,8 +988,6 @@ mod tests {
|
|||
fn creation(id: CommandId, title: &str) -> CreateWorld {
|
||||
CreateWorld {
|
||||
lens_weights: crate::tests::stock_weights(),
|
||||
grammar: None,
|
||||
era: None,
|
||||
id,
|
||||
owner: PrincipalId::new("owner"),
|
||||
title: title.into(),
|
||||
|
|
@ -1234,7 +1009,6 @@ mod tests {
|
|||
},
|
||||
affordances: kernel_speak_grant(),
|
||||
position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))),
|
||||
import_key: None,
|
||||
}),
|
||||
],
|
||||
operations: Vec::new(),
|
||||
|
|
@ -1283,22 +1057,6 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hierarchy_is_derived_from_the_world_through_the_mailbox() {
|
||||
let (_directory, _path, mailbox, task, _authenticated, _input, _receipt) = fixture().await;
|
||||
let hierarchy = mailbox.hierarchy().await.unwrap();
|
||||
let snapshot = mailbox.snapshot().await.unwrap();
|
||||
// The fixture world holds one Human operator in one room: placed under
|
||||
// that room's node, no voice anywhere.
|
||||
assert_eq!(hierarchy.home.len(), 1);
|
||||
assert!(hierarchy.nodes.values().all(|node| node.voice.is_none() && node.loose.is_empty()));
|
||||
assert_eq!(hierarchy.nodes.len(), 2);
|
||||
assert_eq!(hierarchy, mailbox.hierarchy().await.unwrap());
|
||||
assert_eq!(snapshot.subjects.len(), 1);
|
||||
drop(mailbox);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn empty_owner_rejects_world_operations_then_accepts_creation() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
|
|
@ -1638,7 +1396,6 @@ mod tests {
|
|||
controller,
|
||||
affordances: kernel_speak_grant(),
|
||||
position: Some(Ref::Draft(DraftHandle::new(format!("room-{handle}")))),
|
||||
import_key: None,
|
||||
})
|
||||
};
|
||||
let room = |handle: &str| {
|
||||
|
|
@ -1668,8 +1425,6 @@ mod tests {
|
|||
evidence: Vec::new(),
|
||||
},
|
||||
scale_intent: WorldScaleIntentRef::default(),
|
||||
grammar: None,
|
||||
era: None,
|
||||
},
|
||||
&authenticated,
|
||||
)
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,296 +0,0 @@
|
|||
//! Prefix-based routing across the configured inference transports.
|
||||
//!
|
||||
//! `RoutedInferencePort` routes each model identifier to the longest matching
|
||||
//! claimed prefix (`local/`, `hosted/`, etc.) and falls back to the connector
|
||||
//! when no configured prefix claims the model.
|
||||
|
||||
use super::controllers::{
|
||||
InferenceFault, InferenceOutput, InferencePort, InferenceRequest, PreparedInference,
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Which port a lane uses is which model it is configured with. The config
|
||||
/// already gates cognition by model name and deliberately refuses a mode flag,
|
||||
/// so the transport is bound where the model is named and nowhere else.
|
||||
pub(super) struct RoutedInferencePort {
|
||||
connector: Option<Arc<dyn InferencePort>>,
|
||||
/// The OpenAI-compatible ports (the loopback one and the hosted one), each
|
||||
/// with its own claimed prefix carried beside it, so `route` can compare
|
||||
/// lengths without a parallel field per port to keep in sync.
|
||||
claims: Vec<(String, Arc<dyn InferencePort>)>,
|
||||
}
|
||||
|
||||
impl RoutedInferencePort {
|
||||
pub(super) fn new(
|
||||
connector: Option<Arc<dyn InferencePort>>,
|
||||
claims: Vec<(String, Arc<dyn InferencePort>)>,
|
||||
) -> Self {
|
||||
Self { connector, claims }
|
||||
}
|
||||
|
||||
/// The model name carries the transport. When more than one prefix matches,
|
||||
/// the longest claim wins. Any model no configured prefix claims falls to
|
||||
/// the connector, or routes nowhere when no connector is bound.
|
||||
pub(super) fn route(&self, model: &str) -> Option<&Arc<dyn InferencePort>> {
|
||||
if let Some((_, port)) = self
|
||||
.claims
|
||||
.iter()
|
||||
.filter(|(prefix, _)| model.starts_with(prefix.as_str()))
|
||||
.max_by_key(|(prefix, _)| prefix.len())
|
||||
{
|
||||
return Some(port);
|
||||
}
|
||||
self.connector.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl InferencePort for RoutedInferencePort {
|
||||
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
|
||||
let model = request.provider_model().to_owned();
|
||||
match self.route(&model) {
|
||||
Some(port) => port.prepare(request),
|
||||
None => Err(InferenceFault::integrity_violation(
|
||||
"no configured inference backend claims the requested model",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
|
||||
let model = request.invocation.request.model.clone();
|
||||
match self.route(&model) {
|
||||
Some(port) => port.infer(request).await,
|
||||
None => Err(InferenceFault::integrity_violation(
|
||||
"no configured inference backend claims the requested model",
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::CommandId;
|
||||
use crate::controllers::{
|
||||
ConnectorBinding, ControllerModels, ControllerOpenError, InferencePurpose, RequestShape,
|
||||
open_inference, tool_request, unix_ms,
|
||||
};
|
||||
use crate::local_inference::{
|
||||
DEFAULT_HOSTED_MODEL_PREFIX, DEFAULT_LOCAL_MODEL_PREFIX, HostedBinding, LocalBinding,
|
||||
};
|
||||
use model_connector::{InputItem, ToolDefinition};
|
||||
|
||||
const TEST_RUNTIME: &str = "ghostlight-routed-test";
|
||||
const TEST_MODEL: &str = "claude-opus-5-5";
|
||||
|
||||
struct StubPort;
|
||||
|
||||
#[async_trait]
|
||||
impl InferencePort for StubPort {
|
||||
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
|
||||
PreparedInference::prepare(TEST_RUNTIME, unix_ms()?.saturating_add(60_000), request)
|
||||
}
|
||||
|
||||
async fn infer(&self, _request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
|
||||
Err(InferenceFault::integrity_violation("stub port"))
|
||||
}
|
||||
}
|
||||
|
||||
fn prose_request(prompt: &str) -> InferenceRequest {
|
||||
tool_request(
|
||||
CommandId::new(),
|
||||
0,
|
||||
InferencePurpose::Persona,
|
||||
TEST_MODEL,
|
||||
"Respond only in natural prose.",
|
||||
vec![InputItem::UserText {
|
||||
text: prompt.into(),
|
||||
}],
|
||||
Vec::<ToolDefinition>::new(),
|
||||
RequestShape {
|
||||
max_output_tokens: 1_200,
|
||||
parallel_tool_calls: false,
|
||||
},
|
||||
)
|
||||
.expect("the prose request builds")
|
||||
}
|
||||
|
||||
fn models(model: &str) -> ControllerModels {
|
||||
ControllerModels {
|
||||
projector: model.into(),
|
||||
persona: model.into(),
|
||||
interpreter: model.into(),
|
||||
operational_agent: model.into(),
|
||||
elaborator: model.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_inference_routes_connector_local_hosted_only() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let connector_key = directory.path().join("connector.key");
|
||||
let hosted_key = directory.path().join("hosted.key");
|
||||
std::fs::write(&connector_key, "connector-test-key").unwrap();
|
||||
std::fs::write(&hosted_key, "hosted-test-key").unwrap();
|
||||
|
||||
let connector = ConnectorBinding {
|
||||
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||
key_path: connector_key,
|
||||
caller_runtime_id: TEST_RUNTIME.into(),
|
||||
};
|
||||
let local = LocalBinding {
|
||||
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||
model_prefix: DEFAULT_LOCAL_MODEL_PREFIX.into(),
|
||||
caller_runtime_id: TEST_RUNTIME.into(),
|
||||
};
|
||||
let hosted = HostedBinding {
|
||||
base_url: "https://api.example.test".into(),
|
||||
key_path: hosted_key.clone(),
|
||||
model_prefix: DEFAULT_HOSTED_MODEL_PREFIX.into(),
|
||||
caller_runtime_id: TEST_RUNTIME.into(),
|
||||
};
|
||||
|
||||
assert!(
|
||||
open_inference(
|
||||
Some(connector),
|
||||
Some(local),
|
||||
Some(hosted),
|
||||
&["claude-opus-5-5", "local/llama-8b", "hosted/deepseek-chat"],
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
|
||||
let connector_port = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||
let local_port = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||
let hosted_port = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||
let routed = RoutedInferencePort::new(
|
||||
Some(Arc::clone(&connector_port)),
|
||||
vec![
|
||||
(DEFAULT_LOCAL_MODEL_PREFIX.to_owned(), Arc::clone(&local_port)),
|
||||
(DEFAULT_HOSTED_MODEL_PREFIX.to_owned(), Arc::clone(&hosted_port)),
|
||||
],
|
||||
);
|
||||
assert!(Arc::ptr_eq(
|
||||
routed.route("claude-opus-5-5").unwrap(),
|
||||
&connector_port
|
||||
));
|
||||
assert!(Arc::ptr_eq(
|
||||
routed.route("local/llama-8b").unwrap(),
|
||||
&local_port
|
||||
));
|
||||
assert!(Arc::ptr_eq(
|
||||
routed.route("hosted/deepseek-chat").unwrap(),
|
||||
&hosted_port
|
||||
));
|
||||
|
||||
let clashing_local = LocalBinding {
|
||||
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||
model_prefix: "shared/".into(),
|
||||
caller_runtime_id: TEST_RUNTIME.into(),
|
||||
};
|
||||
let clashing_hosted = HostedBinding {
|
||||
base_url: "https://api.example.test".into(),
|
||||
key_path: hosted_key,
|
||||
model_prefix: "shared/".into(),
|
||||
caller_runtime_id: TEST_RUNTIME.into(),
|
||||
};
|
||||
assert!(matches!(
|
||||
open_inference(None, Some(clashing_local), Some(clashing_hosted), &["shared/x"]),
|
||||
Err(ControllerOpenError::SharedModelPrefix { prefix }) if prefix == "shared/"
|
||||
));
|
||||
}
|
||||
|
||||
/// Spec test 12.
|
||||
#[test]
|
||||
fn a_model_prefix_routes_a_lane_to_its_port() {
|
||||
let claimed = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||
let connector = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||
let routed = RoutedInferencePort::new(
|
||||
Some(Arc::clone(&connector)),
|
||||
vec![("local/".to_owned(), Arc::clone(&claimed))],
|
||||
);
|
||||
assert!(Arc::ptr_eq(
|
||||
routed.route("local/llama-8b").unwrap(),
|
||||
&claimed
|
||||
));
|
||||
assert!(Arc::ptr_eq(
|
||||
routed.route("claude-opus-5-5").unwrap(),
|
||||
&connector
|
||||
));
|
||||
assert!(Arc::ptr_eq(
|
||||
routed.route("gpt-5.6-terra").unwrap(),
|
||||
&connector
|
||||
));
|
||||
}
|
||||
|
||||
/// Spec test 13.
|
||||
#[test]
|
||||
fn an_unroutable_model_fails_at_open() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("controller.key");
|
||||
std::fs::write(&key, "routed-port-test-key").unwrap();
|
||||
let connector = || ConnectorBinding {
|
||||
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||
key_path: key.clone(),
|
||||
caller_runtime_id: TEST_RUNTIME.into(),
|
||||
};
|
||||
let local = || LocalBinding {
|
||||
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||
model_prefix: DEFAULT_LOCAL_MODEL_PREFIX.into(),
|
||||
caller_runtime_id: TEST_RUNTIME.into(),
|
||||
};
|
||||
|
||||
assert!(matches!(
|
||||
open_inference(None, Some(local()), None, &models("gpt-5.6-terra").each()),
|
||||
Err(ControllerOpenError::UnroutableModel { .. })
|
||||
));
|
||||
// The connector serves any model no local or hosted prefix claims.
|
||||
assert!(
|
||||
open_inference(Some(connector()), None, None, &models("claude-haiku-5-5").each()).is_ok()
|
||||
);
|
||||
assert!(
|
||||
open_inference(Some(connector()), None, None, &models("claude-opus-5").each()).is_ok()
|
||||
);
|
||||
assert!(
|
||||
open_inference(Some(connector()), None, None, &models(TEST_MODEL).each()).is_ok(),
|
||||
"a configuration where every model routes did not open"
|
||||
);
|
||||
}
|
||||
|
||||
/// Soul: an unroutable model is refused at `infer` as well as at open.
|
||||
#[tokio::test]
|
||||
async fn soul_routing_refuses_rather_than_falling_back() {
|
||||
let connector = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||
let connector_only = RoutedInferencePort::new(Some(Arc::clone(&connector)), Vec::new());
|
||||
assert!(Arc::ptr_eq(
|
||||
connector_only.route(TEST_MODEL).unwrap(),
|
||||
&connector
|
||||
));
|
||||
// A prefix that does not match, and no connector: the model has no
|
||||
// owner and routes nowhere.
|
||||
let unclaimed = RoutedInferencePort::new(
|
||||
None,
|
||||
vec![("hosted/".to_owned(), Arc::new(StubPort) as Arc<dyn InferencePort>)],
|
||||
);
|
||||
assert!(unclaimed.route(TEST_MODEL).is_none());
|
||||
let prepared =
|
||||
PreparedInference::prepare(TEST_RUNTIME, 4_102_444_800_000, prose_request("Say it."))
|
||||
.unwrap();
|
||||
for fault in [
|
||||
unclaimed
|
||||
.prepare(prose_request("Say it."))
|
||||
.expect_err("an unroutable model prepared"),
|
||||
unclaimed
|
||||
.infer(prepared)
|
||||
.await
|
||||
.expect_err("an unroutable model inferred"),
|
||||
] {
|
||||
assert!(fault.integrity_was_violated(), "{fault:?}");
|
||||
assert!(
|
||||
fault.to_string().contains("no configured inference backend"),
|
||||
"{fault:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
2027
crates/ghostlight/src/sdk_inference.rs
Normal file
2027
crates/ghostlight/src/sdk_inference.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -14,7 +14,7 @@
|
|||
//! Projector may call it.
|
||||
|
||||
use super::controllers::{
|
||||
self, ControllerError, InferenceEvent, InferenceOutput, InferencePurpose, InferenceRequest, TokenUsage,
|
||||
self, ControllerError, InferenceEvent, InferenceOutput, InferencePurpose, InferenceRequest,
|
||||
RequestShape, tool_request,
|
||||
};
|
||||
use super::patch::{
|
||||
|
|
@ -26,7 +26,7 @@ use super::{
|
|||
DecisionOpportunity, EntityId, KernelError, Mismatch, RefKind, Statement, SubjectId,
|
||||
SubjectKind, Target, WorldPatch, WorldSnapshot,
|
||||
};
|
||||
use model_connector::{InputItem, ToolDefinition};
|
||||
use codex_connector::{CodexInputItem, CodexToolDefinition};
|
||||
use serde_json::Value;
|
||||
use thiserror::Error;
|
||||
|
||||
|
|
@ -44,7 +44,7 @@ pub enum TableError {
|
|||
/// `PATCH_TOOLS`; which names a particular agent gets is policy, and policy
|
||||
/// belongs to the caller — `PLAY_TOOLS` is Dungeon's, pinned in Cut 8, not
|
||||
/// this module's.
|
||||
pub fn authoring_tools(names: &[&str]) -> Result<Vec<ToolDefinition>, TableError> {
|
||||
pub fn authoring_tools(names: &[&str]) -> Result<Vec<CodexToolDefinition>, TableError> {
|
||||
let catalog = patch::patch_tools();
|
||||
names
|
||||
.iter()
|
||||
|
|
@ -220,7 +220,7 @@ fn subject_opportunity<'a>(
|
|||
/// turn; that is the controller lane's own vocabulary, and
|
||||
/// `decode_actor_call` has no arm for either, so offering them here would
|
||||
/// hand the play agent a tool `decode_actor_call` always refuses (PA.f55).
|
||||
pub fn actor_tools(prefix: &str, snapshot: &WorldSnapshot, subject: SubjectId) -> Vec<ToolDefinition> {
|
||||
pub fn actor_tools(prefix: &str, snapshot: &WorldSnapshot, subject: SubjectId) -> Vec<CodexToolDefinition> {
|
||||
match subject_opportunity(snapshot, subject) {
|
||||
Some((_, granted)) => controllers::affordance_tools(prefix, &granted),
|
||||
None => Vec::new(),
|
||||
|
|
@ -983,100 +983,6 @@ fn render_dependency_target(snapshot: &WorldSnapshot, target: &DependencyTarget)
|
|||
}
|
||||
}
|
||||
|
||||
/// The wrongs the world holds against a subject and what has answered them,
|
||||
/// read off state and stored nowhere: whom the doer wronged (a grievance in the
|
||||
/// victim's regard), who saw the doer's acts (`Seen` knowledge), which forums
|
||||
/// cover the doer, who presses the doer, and who has sworn a reckoning with the
|
||||
/// doer as counterparty. A grievance nothing answers is named as unanswered:
|
||||
/// the table's own judgement sends the watch, so what it needs is to see that
|
||||
/// no one has been sent.
|
||||
fn render_open_grievances(snapshot: &WorldSnapshot) -> String {
|
||||
use crate::attitude::AttitudeCause;
|
||||
use crate::patch::KnowledgeSource;
|
||||
let name = |id: SubjectId| {
|
||||
label_for_any_id(snapshot, &id_text(id)).unwrap_or_else(|| format!("[{}]", id_text(id)))
|
||||
};
|
||||
let mut out = String::from("\n Open grievances (derived: who was wronged, who saw it, what answers it):");
|
||||
let mut any = false;
|
||||
for doer in &snapshot.subjects {
|
||||
let wronged: Vec<String> = snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.flat_map(|holder| {
|
||||
holder
|
||||
.opinions
|
||||
.iter()
|
||||
.filter(|held| held.toward == doer.id)
|
||||
.filter(|held| {
|
||||
held.causes
|
||||
.iter()
|
||||
.any(|cause| matches!(cause.cause, AttitudeCause::Grievance { .. }) && cause.delta < 0)
|
||||
})
|
||||
.map(|held| format!("{} ({:+})", name(holder.id), held.total))
|
||||
})
|
||||
.collect();
|
||||
if wronged.is_empty() {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
let mut seen_by = Vec::new();
|
||||
let mut acts = std::collections::BTreeSet::new();
|
||||
for witness in snapshot.subjects.iter().filter(|witness| witness.id != doer.id) {
|
||||
for row in &witness.knowledge {
|
||||
if row.source == (KnowledgeSource::Seen { by: doer.id }) {
|
||||
seen_by.push(name(witness.id));
|
||||
acts.insert(format!("\"{}\"", row.statement.as_str()));
|
||||
}
|
||||
}
|
||||
}
|
||||
seen_by.sort();
|
||||
seen_by.dedup();
|
||||
let pressing: Vec<String> = doer
|
||||
.pressures
|
||||
.iter()
|
||||
.filter_map(|pressure| match pressure.source {
|
||||
PressureSource::Subject(id) => Some(format!("{} ({})", name(id), pressure.magnitude.0)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let reckonings: Vec<String> = snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.flat_map(|holder| {
|
||||
holder
|
||||
.commitments
|
||||
.iter()
|
||||
.filter(|commitment| commitment.counterparty == Some(doer.id))
|
||||
.map(move |commitment| format!("{}: \"{}\"", name(holder.id), commitment.statement.as_str()))
|
||||
})
|
||||
.collect();
|
||||
let answered = !pressing.is_empty() || !reckonings.is_empty();
|
||||
out.push_str(&format!(
|
||||
" {} wronged {}; acts seen by: {}{}; forums covering them: {}; pressed by: {}; reckonings sworn against them: {}; {}",
|
||||
name(doer.id),
|
||||
joined_sorted(wronged),
|
||||
if seen_by.is_empty() { "no one".to_owned() } else { joined_sorted(seen_by) },
|
||||
if acts.is_empty() { String::new() } else { format!(" ({})", joined_sorted(acts.into_iter().collect())) },
|
||||
if doer.redress.is_empty() {
|
||||
"none".to_owned()
|
||||
} else {
|
||||
joined_sorted(doer.redress.iter().map(|forum| render_forum(snapshot, forum)).collect())
|
||||
},
|
||||
if pressing.is_empty() { "no one".to_owned() } else { joined_sorted(pressing) },
|
||||
if reckonings.is_empty() { "none".to_owned() } else { joined_sorted(reckonings) },
|
||||
if answered {
|
||||
"answered so far."
|
||||
} else {
|
||||
"nothing has answered it yet: no office presses them and no kin or ally has sworn anything. The office, the kin and the witnesses answer through their own people: dispatch them, or rule it with advance_pressure and create_commitment."
|
||||
},
|
||||
));
|
||||
}
|
||||
if !any {
|
||||
out.push_str(" none");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A pressure source, in the same shape `advance_pressure`/`reduce_pressure`'s
|
||||
/// `PressureSourceRef` composite takes: a commitment names the promisor
|
||||
/// subject id and the commitment key; a dependency names its target; a
|
||||
|
|
@ -1132,8 +1038,8 @@ impl InferenceRequest {
|
|||
round: usize,
|
||||
model: &str,
|
||||
instructions: &str,
|
||||
input: Vec<InputItem>,
|
||||
tools: Vec<ToolDefinition>,
|
||||
input: Vec<CodexInputItem>,
|
||||
tools: Vec<CodexToolDefinition>,
|
||||
max_output_tokens: u32,
|
||||
) -> Result<InferenceRequest, ControllerError> {
|
||||
tool_request(
|
||||
|
|
@ -1164,12 +1070,6 @@ impl InferenceOutput {
|
|||
pub fn receipt_digest(&self) -> &str {
|
||||
&self.receipt_digest
|
||||
}
|
||||
|
||||
/// The tokens the provider reported for this reply; `None` when it
|
||||
/// reported none.
|
||||
pub fn usage(&self) -> Option<TokenUsage> {
|
||||
self.usage
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical id as the patch vocabulary spells it: the bare UUID text,
|
||||
|
|
@ -1189,17 +1089,6 @@ pub fn id_text(id: impl std::fmt::Debug) -> String {
|
|||
}
|
||||
}
|
||||
|
||||
/// A subject's own short handle: the first 8 hex digits of its id. Actor tool
|
||||
/// names are `<handle>__<kind>` and a kind may run to 48 chars, so the full id
|
||||
/// text would break a common 64-char function-name limit; the Gestalt round's
|
||||
/// section headers carry the same handle, so a reply splits on a token that
|
||||
/// names exactly one subject even when two share a label. A collision between
|
||||
/// two subjects is astronomically unlikely but not impossible; each caller that
|
||||
/// keys on handles refuses it rather than addressing the wrong subject.
|
||||
pub fn handle_for(id: crate::SubjectId) -> String {
|
||||
id_text(id).chars().filter(char::is_ascii_hexdigit).take(8).collect()
|
||||
}
|
||||
|
||||
/// The parser matching `id_text` above (PA.f113): `text` names `id` only
|
||||
/// when it is exactly the bytes `id_text(id)` would print — no brackets, no
|
||||
/// padding, no case folding, because this is plain string equality against
|
||||
|
|
@ -1213,7 +1102,7 @@ pub fn id_text_matches(id: impl std::fmt::Debug, text: &str) -> bool {
|
|||
/// The world the seed session is authoring into, rendered from snapshot
|
||||
/// fields that already exist. Moved from the elaboration lane, byte-for-byte:
|
||||
/// the seed prompt calls it here now, and its text does not change with the
|
||||
/// move. Read by the seed and the Active elaboration prompts; `table_view` below is the play agent's own, richer
|
||||
/// move. Seed-only; `table_view` below is the play agent's own, richer
|
||||
/// renderer over the same snapshot and does not build on this one, so a
|
||||
/// change to one never reaches the other's bytes.
|
||||
pub(super) fn render_world_structure(snapshot: &WorldSnapshot) -> String {
|
||||
|
|
@ -1652,44 +1541,6 @@ pub fn table_view(snapshot: &WorldSnapshot) -> String {
|
|||
out.push_str(" none");
|
||||
}
|
||||
|
||||
// Derived by the kernel from sourced modifiers; the one reading the
|
||||
// Persona's own view and the narrator also draw from. A prejudice toward a
|
||||
// trait shows only once its holder knows the subject carries it.
|
||||
out.push_str("\n Regard (how each subject holds another, with what it rests on):");
|
||||
let mut any_regard = false;
|
||||
for subject in &snapshot.subjects {
|
||||
for held in &subject.opinions {
|
||||
any_regard = true;
|
||||
let toward = label_for_any_id(snapshot, &id_text(held.toward))
|
||||
.unwrap_or_else(|| format!("[{}]", id_text(held.toward)));
|
||||
out.push_str(&format!(
|
||||
" {} [{}] regards {} with {} ({:+}): {};",
|
||||
subject.label,
|
||||
id_text(subject.id),
|
||||
toward,
|
||||
crate::attitude::regard_word(held.total),
|
||||
held.total,
|
||||
joined(
|
||||
held.causes
|
||||
.iter()
|
||||
.map(|cause| crate::attitude::describe_cause(cause, |fact| {
|
||||
snapshot
|
||||
.facts
|
||||
.iter()
|
||||
.find(|entry| entry.id == fact)
|
||||
.map(|entry| entry.statement.as_str().to_owned())
|
||||
}))
|
||||
.collect()
|
||||
)
|
||||
));
|
||||
}
|
||||
}
|
||||
if !any_regard {
|
||||
out.push_str(" none");
|
||||
}
|
||||
|
||||
out.push_str(&render_open_grievances(snapshot));
|
||||
|
||||
out.push_str("\n Persona material:");
|
||||
let mut any_material = false;
|
||||
for subject in &snapshot.subjects {
|
||||
|
|
@ -1734,7 +1585,7 @@ pub fn table_view(snapshot: &WorldSnapshot) -> String {
|
|||
"\n Clock: the world reads {} fictional minutes.",
|
||||
snapshot.now.0
|
||||
));
|
||||
out.push_str(&format!("\n Guidance: {}\n", snapshot.guidance().replace('\n', " ")));
|
||||
out.push_str(&format!("\n Brief: {}\n", snapshot.brief));
|
||||
out
|
||||
}
|
||||
|
||||
|
|
@ -1749,8 +1600,7 @@ mod tests {
|
|||
// PA.f75: `communicate` was removed from `PLAY_TOOLS`; Dungeon drops it
|
||||
// from its own list too. This is now the complete 24-tool list.
|
||||
// PA.f88: this is the library's own test fixture, kept in sync by hand.
|
||||
// Dungeon's `PLAY_TOOLS` in `ghostlight-dungeon/src/play.rs` (parked at
|
||||
// `parked/ghostlight-eve-surface`) is the
|
||||
// Dungeon's `PLAY_TOOLS` in `ghostlight-dungeon/src/play.rs` is the
|
||||
// single policy owner of what the play agent may actually call; this
|
||||
// copy pins nothing there and is not read by production code.
|
||||
const PLAY_TOOLS: &[&str] = &[
|
||||
|
|
@ -2639,7 +2489,6 @@ mod tests {
|
|||
outcome_bands: Vec::new(),
|
||||
carries_speech: false,
|
||||
},
|
||||
render_path: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -3264,7 +3113,7 @@ mod tests {
|
|||
("local_inference.rs", include_str!("local_inference.rs")),
|
||||
("mailbox.rs", include_str!("mailbox.rs")),
|
||||
("patch.rs", include_str!("patch.rs")),
|
||||
("routed_inference.rs", include_str!("routed_inference.rs")),
|
||||
("sdk_inference.rs", include_str!("sdk_inference.rs")),
|
||||
("tool_schema.rs", include_str!("tool_schema.rs")),
|
||||
("vault.rs", include_str!("vault.rs")),
|
||||
];
|
||||
|
|
|
|||
|
|
@ -6,11 +6,11 @@
|
|||
//! own vocabulary. Both spell a property the same way because both spell it
|
||||
//! here. Nothing in this module reads world state, a snapshot, or a config.
|
||||
|
||||
use model_connector::ToolDefinition;
|
||||
use codex_connector::CodexToolDefinition;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub(super) fn tool(name: &str, description: &str, schema: Value) -> ToolDefinition {
|
||||
ToolDefinition {
|
||||
pub(super) fn tool(name: &str, description: &str, schema: Value) -> CodexToolDefinition {
|
||||
CodexToolDefinition {
|
||||
name: name.into(),
|
||||
description: description.into(),
|
||||
parameters_json: serde_json::to_string(&schema)
|
||||
|
|
@ -43,29 +43,10 @@ pub(super) fn canonical_string(description: &str) -> Value {
|
|||
json!({"type": "string", "description": description})
|
||||
}
|
||||
|
||||
/// A string the kernel will hold to its civic-name rule, `[a-z][a-z0-9_]` up to
|
||||
/// `max` characters. The rule is stated twice on purpose: as a `pattern` a
|
||||
/// strict decoder can enforce, and in the description the model reads. `max` is
|
||||
/// the kernel's own bound, passed in so the rule has one owner.
|
||||
pub(super) fn civic_name(description: &str, max: usize) -> Value {
|
||||
json!({
|
||||
"type": "string",
|
||||
"pattern": format!("^[a-z][a-z0-9_]{{0,{}}}$", max - 1),
|
||||
"description": format!(
|
||||
"{description}: lowercase snake_case, starting with a letter, at most {max} characters (e.g. toll_command)"
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn bounded_integer(min: u64, max: u64) -> Value {
|
||||
json!({"type": "integer", "minimum": min, "maximum": max})
|
||||
}
|
||||
|
||||
/// An integer that may be negative, for a regard that can fall as well as rise.
|
||||
pub(super) fn signed_integer(min: i64, max: i64) -> 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 {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,984 +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::{
|
||||
ControllerError, InferenceEvent, InferenceFault, InferenceOutput, InferencePort,
|
||||
InferencePurpose, InferenceRequest, PreparedInference, REQUEST_EXPIRY, TokenUsage,
|
||||
request_id_prefix, unix_ms,
|
||||
};
|
||||
use crate::{FrozenCell, NodeId, TickIndex, WorldId};
|
||||
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.v2";
|
||||
const RUN_LEDGER_ROW: &str = "verse_run_ledger.v2";
|
||||
/// The run ledger document's schema.
|
||||
const RUN_LEDGER_SCHEMA: &str = "ghostlight.verse_run_ledger.v2";
|
||||
/// 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.v2";
|
||||
|
||||
#[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 call could pass its lane's allowance")]
|
||||
OverAllowance,
|
||||
#[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 lane allowances the run was opened with.
|
||||
Allowances,
|
||||
/// 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::Allowances => "lane allowances",
|
||||
Self::WorldId => "world id",
|
||||
Self::StateDigest => "world state digest",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The background lane a metered call spends in. The room lane, the DM's play
|
||||
/// turn, is in no window: it is never reserved here.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub enum Lane {
|
||||
/// A node turn of a Gestalt wave.
|
||||
Wave,
|
||||
/// An elaborator session.
|
||||
Elaboration,
|
||||
}
|
||||
|
||||
impl Lane {
|
||||
/// The lane a call of this purpose spends in; the play agent has none.
|
||||
pub fn of(purpose: InferencePurpose) -> Option<Self> {
|
||||
match purpose {
|
||||
InferencePurpose::Play => None,
|
||||
InferencePurpose::Elaboration => Some(Self::Elaboration),
|
||||
_ => Some(Self::Wave),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tokens by lane: a window's allowances, or what its lanes have reserved or
|
||||
/// been charged.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LaneTokens {
|
||||
pub wave: u64,
|
||||
pub elaboration: u64,
|
||||
}
|
||||
|
||||
impl LaneTokens {
|
||||
pub fn of(&self, lane: Lane) -> u64 {
|
||||
match lane {
|
||||
Lane::Wave => self.wave,
|
||||
Lane::Elaboration => self.elaboration,
|
||||
}
|
||||
}
|
||||
|
||||
fn set(&mut self, lane: Lane, tokens: u64) {
|
||||
match lane {
|
||||
Lane::Wave => self.wave = tokens,
|
||||
Lane::Elaboration => self.elaboration = tokens,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every lane together.
|
||||
pub fn total(&self) -> u64 {
|
||||
self.wave.saturating_add(self.elaboration)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
lane: Lane,
|
||||
request_id: String,
|
||||
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
|
||||
}
|
||||
|
||||
/// The lane this call spent in.
|
||||
pub fn lane(&self) -> Lane {
|
||||
self.lane
|
||||
}
|
||||
|
||||
/// The provider request id, which carries the command id it ran under: the
|
||||
/// join from a call to the wave cell that made it.
|
||||
pub fn request_id(&self) -> &str {
|
||||
&self.request_id
|
||||
}
|
||||
|
||||
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,
|
||||
allowances: LaneTokens,
|
||||
start: RunStart,
|
||||
/// Tokens reserved or charged, by lane. The run's spend is their sum.
|
||||
spent: LaneTokens,
|
||||
}
|
||||
|
||||
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, LaneTokens> = 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.set(record.lane, total.of(record.lane).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_default();
|
||||
let covered = tally.ledger.as_ref().is_some_and(|ledger| {
|
||||
ledger.spent.wave >= recorded.wave && ledger.spent.elaboration >= recorded.elaboration
|
||||
});
|
||||
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.total()))
|
||||
}
|
||||
|
||||
/// What each lane of this run has reserved or been charged.
|
||||
pub fn lane_spent(&self, run: &RunId) -> Result<LaneTokens, CallRecordError> {
|
||||
Ok(self
|
||||
.lock()?
|
||||
.runs
|
||||
.get(run.as_str())
|
||||
.and_then(|tally| tally.ledger.as_ref())
|
||||
.map_or_else(LaneTokens::default, |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
|
||||
/// the lane allowances, and the world it starts from. A later claim must name
|
||||
/// the same cap and allowances; the start is not compared, because a resumed world has moved on.
|
||||
/// With `follow`, a ledger already begun takes the cap and allowances named
|
||||
/// here in place of its own, its spend kept: a caller whose limits change
|
||||
/// while a run is open (the Dungeon's tuned allowances) owns them, and a
|
||||
/// limit below what is already held only exhausts the lane.
|
||||
fn claim(
|
||||
&self,
|
||||
run: &RunId,
|
||||
cap: u64,
|
||||
allowances: LaneTokens,
|
||||
start: &RunStart,
|
||||
follow: bool,
|
||||
) -> 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.clone()) {
|
||||
Some(ledger) if follow && (ledger.cap != cap || ledger.allowances != allowances) => {
|
||||
Self::write_ledger(&mut state, RunLedger { cap, allowances, ..ledger })
|
||||
}
|
||||
Some(ledger) if ledger.cap != cap => Err(CallRecordError::RunMismatch(RunField::Cap)),
|
||||
Some(ledger) if ledger.allowances != allowances => {
|
||||
Err(CallRecordError::RunMismatch(RunField::Allowances))
|
||||
}
|
||||
Some(_) => Ok(()),
|
||||
None => Self::write_ledger(
|
||||
&mut state,
|
||||
RunLedger {
|
||||
run_id: run.as_str().to_owned(),
|
||||
cap,
|
||||
allowances,
|
||||
start: start.clone(),
|
||||
spent: LaneTokens::default(),
|
||||
},
|
||||
),
|
||||
};
|
||||
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 what the run's lanes hold; the run must have been
|
||||
/// claimed.
|
||||
fn write_spent(
|
||||
state: &mut StoreState,
|
||||
run: &str,
|
||||
spent: LaneTokens,
|
||||
) -> 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) -> LaneTokens {
|
||||
state
|
||||
.runs
|
||||
.get(run.as_str())
|
||||
.and_then(|tally| tally.ledger.as_ref())
|
||||
.map_or_else(LaneTokens::default, |ledger| ledger.spent)
|
||||
}
|
||||
|
||||
/// Charges `bound` to the run's persisted ledger under `lane`, or refuses
|
||||
/// with `OverCap` when the run would pass `cap`, or `OverAllowance` when
|
||||
/// the lane would pass its allowance. The check and the write hold one
|
||||
/// lock, so calls on the wire hold their bounds.
|
||||
fn reserve(
|
||||
&self,
|
||||
run: &RunId,
|
||||
lane: Lane,
|
||||
bound: u64,
|
||||
cap: u64,
|
||||
allowance: u64,
|
||||
) -> Result<(), CallRecordError> {
|
||||
let mut state = self.lock()?;
|
||||
let mut held = Self::held(&state, run);
|
||||
let after = held.of(lane).saturating_add(bound);
|
||||
if held.total().saturating_add(bound) > cap {
|
||||
return Err(CallRecordError::OverCap);
|
||||
}
|
||||
if after > allowance {
|
||||
return Err(CallRecordError::OverAllowance);
|
||||
}
|
||||
held.set(lane, after);
|
||||
Self::write_spent(&mut state, run.as_str(), held)
|
||||
}
|
||||
|
||||
/// 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,
|
||||
lane: Lane,
|
||||
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 mut held = Self::held(&state, run);
|
||||
held.set(lane, held.of(lane).saturating_sub(bound).saturating_add(charged));
|
||||
Self::write_spent(&mut state, run.as_str(), held)
|
||||
}
|
||||
|
||||
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,
|
||||
allowances: LaneTokens,
|
||||
}
|
||||
|
||||
impl RecordingInferencePort {
|
||||
/// Takes ownership of the run's ledger, which resumes from the store. The
|
||||
/// first open of a run records its cap, its lane allowances and the world it
|
||||
/// starts from; a reopen with another cap or allowances is refused with
|
||||
/// `RunMismatch`. 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,
|
||||
allowances: LaneTokens,
|
||||
start: &RunStart,
|
||||
) -> Result<Self, CallRecordError> {
|
||||
store.claim(&run, cap_tokens, allowances, start, false)?;
|
||||
Ok(Self { inner, store, run, cap: cap_tokens, allowances })
|
||||
}
|
||||
|
||||
/// `open`, except that a run already begun follows the cap and allowances
|
||||
/// given here instead of refusing them: its ledger takes them, the spend
|
||||
/// already held stays, and a lane whose allowance now sits below its spend
|
||||
/// refuses further calls as exhausted.
|
||||
pub fn open_following(
|
||||
inner: Arc<dyn InferencePort>,
|
||||
store: Arc<CallRecordStore>,
|
||||
run: RunId,
|
||||
cap_tokens: u64,
|
||||
allowances: LaneTokens,
|
||||
start: &RunStart,
|
||||
) -> Result<Self, CallRecordError> {
|
||||
store.claim(&run, cap_tokens, allowances, start, true)?;
|
||||
Ok(Self { inner, store, run, cap: cap_tokens, allowances })
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// Tokens reserved or charged so far, by lane.
|
||||
pub fn lane_spent(&self) -> LaneTokens {
|
||||
self.store.lane_spent(&self.run).unwrap_or(LaneTokens {
|
||||
wave: u64::MAX,
|
||||
elaboration: u64::MAX,
|
||||
})
|
||||
}
|
||||
|
||||
/// The run's call records in sequence.
|
||||
pub fn records(&self) -> Result<Vec<ProviderCallRecord>, CallRecordError> {
|
||||
self.store.records(&self.run)
|
||||
}
|
||||
|
||||
/// 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,
|
||||
lane: Lane,
|
||||
bound: u64,
|
||||
identity: Identity,
|
||||
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, lane, bound, charged, None)
|
||||
.map_err(unrecorded)?;
|
||||
return Err(InferenceFault::budget_exhausted());
|
||||
}
|
||||
let Identity {
|
||||
purpose,
|
||||
model,
|
||||
content_sha256,
|
||||
request_id,
|
||||
} = identity;
|
||||
let record = ProviderCallRecord {
|
||||
run_id: self.run.as_str().to_owned(),
|
||||
sequence: self.store.next_sequence(&self.run).map_err(unrecorded)?,
|
||||
purpose,
|
||||
lane,
|
||||
request_id,
|
||||
model,
|
||||
content_sha256,
|
||||
events: output.events.clone(),
|
||||
receipt_digest: output.receipt_digest.clone(),
|
||||
usage: output.usage,
|
||||
charged,
|
||||
};
|
||||
self.store
|
||||
.settle(&self.run, lane, bound, charged, Some(&record))
|
||||
.map_err(unrecorded)?;
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a call is recorded as, known before the provider is called.
|
||||
struct Identity {
|
||||
purpose: InferencePurpose,
|
||||
model: String,
|
||||
content_sha256: String,
|
||||
request_id: String,
|
||||
}
|
||||
|
||||
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)?;
|
||||
// The room lane is no window's: a play call that reached this port
|
||||
// would spend background budget.
|
||||
let Some(lane) = Lane::of(request.purpose) else {
|
||||
return Err(InferenceFault::integrity_violation(
|
||||
"the room lane is not metered by a background window",
|
||||
));
|
||||
};
|
||||
let identity = Identity {
|
||||
purpose: request.purpose,
|
||||
model: request.invocation.request.model.clone(),
|
||||
content_sha256: content_digest(&request.invocation.request)?,
|
||||
request_id: request.invocation.request.request_id.clone(),
|
||||
};
|
||||
self.store
|
||||
.reserve(&self.run, lane, bound, self.cap, self.allowances.of(lane))
|
||||
.map_err(|error| match error {
|
||||
CallRecordError::OverCap | CallRecordError::OverAllowance => {
|
||||
InferenceFault::budget_exhausted()
|
||||
}
|
||||
_ => unrecorded(error),
|
||||
})?;
|
||||
let result = self.inner.infer(request).await;
|
||||
self.settle(lane, bound, identity, result)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the calls of one wave cost, by lane and by node. The port never learns
|
||||
/// which node a call served: a record's request id begins with the command id
|
||||
/// it ran under, and the frozen wave names the command ids of each node's
|
||||
/// cells, so attribution is this join and nothing the port keeps. Only settled
|
||||
/// calls have records; a call that faulted left its reservation in the ledger
|
||||
/// and no record here.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct WaveSpend {
|
||||
/// Tokens charged by the wave's joined calls, by lane.
|
||||
pub lanes: LaneTokens,
|
||||
/// Per node, in the order the frozen cells first name them. A node whose
|
||||
/// cells made no recorded call is listed with zero.
|
||||
pub nodes: Vec<NodeSpend>,
|
||||
}
|
||||
|
||||
/// One node's settled calls in a wave.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct NodeSpend {
|
||||
pub node: NodeId,
|
||||
/// The node's hierarchy distance from the focus when it was planned.
|
||||
pub distance: u8,
|
||||
pub calls: u32,
|
||||
pub charged: u64,
|
||||
}
|
||||
|
||||
impl WaveSpend {
|
||||
/// The records of wave `ordinal` of `world`: every record whose request id
|
||||
/// begins with a command id of one of `frozen`'s cells. Records of other
|
||||
/// waves or lanes are not this wave's and are left out.
|
||||
pub fn of(
|
||||
records: &[ProviderCallRecord],
|
||||
world: WorldId,
|
||||
ordinal: TickIndex,
|
||||
frozen: &[FrozenCell],
|
||||
) -> Result<Self, ControllerError> {
|
||||
let mut spend = Self::default();
|
||||
let mut prefixes: Vec<(String, usize)> = Vec::new();
|
||||
for cell in frozen {
|
||||
let at = match spend.nodes.iter().position(|node| node.node == cell.node) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
spend.nodes.push(NodeSpend {
|
||||
node: cell.node,
|
||||
distance: cell.distance,
|
||||
calls: 0,
|
||||
charged: 0,
|
||||
});
|
||||
spend.nodes.len() - 1
|
||||
}
|
||||
};
|
||||
for command in cell.command_ids(world, ordinal) {
|
||||
prefixes.push((request_id_prefix(command)?, at));
|
||||
}
|
||||
}
|
||||
for record in records {
|
||||
let Some(&(_, at)) = prefixes
|
||||
.iter()
|
||||
.find(|(prefix, _)| record.request_id.starts_with(prefix))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let node = &mut spend.nodes[at];
|
||||
node.calls += 1;
|
||||
node.charged = node.charged.saturating_add(record.charged);
|
||||
let lane = spend.lanes.of(record.lane).saturating_add(record.charged);
|
||||
spend.lanes.set(record.lane, lane);
|
||||
}
|
||||
Ok(spend)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
|
@ -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;
|
||||
|
|
@ -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."));
|
||||
}
|
||||
|
|
@ -1,20 +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, Lane, LaneTokens, NodeSpend,
|
||||
ProviderCallRecord, RecordingInferencePort, ReplayInferencePort, RunField, RunId, RunStart,
|
||||
WaveSpend,
|
||||
};
|
||||
pub use run::{
|
||||
RUN_RECORD_SCHEMA, RecordedKnobs, RunClaim, RunOutcome, RunStatus,
|
||||
TickCheckpoint, TickReport, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore,
|
||||
call_run_id, run_manual,
|
||||
};
|
||||
|
|
@ -1,922 +0,0 @@
|
|||
//! The manual verse run: the tick driver and its record.
|
||||
//!
|
||||
//! One invocation advances the world tick by tick. A tick reads the world,
|
||||
//! opens (or finds open) its tick document, which freezes one planned wave
|
||||
//! (`plan_wave` over the derived hierarchy, with no focus), runs the frozen
|
||||
//! cells through the wave runner (`run_frozen_cells`), advances the clock once
|
||||
//! by the frozen span, and checkpoints. The driver owns the order of those
|
||||
//! steps and nothing else: the planner chooses nodes and cells, cells decide
|
||||
//! what factions do, the recording port owns spend, the kernel owns time.
|
||||
//!
|
||||
//! A tick is named by the world's clock-advance count, never by `now`. The
|
||||
//! resume point is the open tick document (world, ordinal), written before the
|
||||
//! tick's first cell and read by any later run: it froze the span, the knobs
|
||||
//! and the cells (each with its node and distance) when the tick opened, so a
|
||||
//! run under another span or knobs finishes the open tick as it was opened and
|
||||
//! applies its own config from the next tick it opens. A tick whose cells did not all finish never
|
||||
//! advances the clock, so the same ordinal, cells and command ids come back,
|
||||
//! the controller-work rows pick up where they stopped, and the kernel answers
|
||||
//! every re-submission with the original receipt. A run record reports a run
|
||||
//! and is never read to resume one.
|
||||
//!
|
||||
//! A run starts only when it is invoked: nothing here waits, schedules or
|
||||
//! repeats.
|
||||
|
||||
use super::calls::{RecordingInferencePort, WaveSpend, canonical};
|
||||
use crate::cover::TickIndex;
|
||||
use crate::wave::{
|
||||
Deferral, DeferredNode, FrozenCell, Focus, GestaltKnobs, GestaltKnobsError, NodeReport, Refusal,
|
||||
RefusalReason, UnattributedCall, WaveClock, WaveStop, act_line, acts_since,
|
||||
deferred_nodes, node_reports, plan_wave, run_frozen_cells,
|
||||
};
|
||||
use crate::{
|
||||
AgencyGraph, CommandId, ControllerRunner, DecisionOpportunity, FictionalMinutes, Hierarchy, MailboxError,
|
||||
NodeId, OperatorEvent, SubjectId, TickMinutes, WorldId, WorldMailbox,
|
||||
WorldSnapshot,
|
||||
};
|
||||
use chrono::Utc;
|
||||
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, ops::ControlFlow, path::Path, sync::Mutex};
|
||||
use thiserror::Error;
|
||||
|
||||
/// The run record document's schema.
|
||||
pub const RUN_RECORD_SCHEMA: &str = "ghostlight.verse_run.v2";
|
||||
const RUN_ROW: &str = "verse_run.v2";
|
||||
/// The tick document's schema.
|
||||
pub const TICK_RECORD_SCHEMA: &str = "ghostlight.verse_tick.v3";
|
||||
const TICK_ROW: &str = "verse_tick.v3";
|
||||
/// The schemas later ones replaced. No store holding one is read: the verse store
|
||||
/// has never held a live run, so there is no migration, and a retired row is
|
||||
/// refused by name.
|
||||
const RETIRED_SCHEMAS: [&str; 3] = [
|
||||
"ghostlight.verse_run.v1",
|
||||
"ghostlight.verse_tick.v1",
|
||||
"ghostlight.verse_tick.v2",
|
||||
];
|
||||
const CLOCK_NAMESPACE: &str = "ghostlight.verse.clock";
|
||||
|
||||
/// Why a run could not be recorded or started. Every variant names a kind of
|
||||
/// fault; none carries a value the run held.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum VerseRunError {
|
||||
#[error("the run record store could not be read or written")]
|
||||
Store,
|
||||
#[error("the run record store holds a row that is not a canonical run record")]
|
||||
Corrupt,
|
||||
#[error("a run record's sequence is not an existing run or the next in its world")]
|
||||
OutOfSequence,
|
||||
#[error("the recording port belongs to another run")]
|
||||
PortNotThisRun,
|
||||
#[error("the run's configuration is not the one its claim recorded")]
|
||||
ConfigNotThisClaim,
|
||||
#[error("the world is not at the revision its claim was made from")]
|
||||
WorldMovedSinceClaim,
|
||||
#[error("the knobs are not valid: {0}")]
|
||||
Knobs(#[from] GestaltKnobsError),
|
||||
#[error("the run store holds a row of a retired schema (v1 run or tick); it is not migrated")]
|
||||
RetiredSchema,
|
||||
#[error(transparent)]
|
||||
Mailbox(#[from] MailboxError),
|
||||
}
|
||||
|
||||
/// Where a run stands. `Running` is only ever the record of a run in flight,
|
||||
/// or of one whose process died before it could say how it ended.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum RunStatus {
|
||||
Running,
|
||||
Completed,
|
||||
/// A provider call could pass the token cap, so the run ended before the
|
||||
/// open tick's clock advance.
|
||||
BudgetExhausted,
|
||||
/// The run ended without finishing its open tick. `reason` is a fixed code
|
||||
/// naming the kind of fault, never a value.
|
||||
Failed {
|
||||
reason: String,
|
||||
},
|
||||
/// The caller asked the run to end after a finished tick.
|
||||
Stopped,
|
||||
}
|
||||
|
||||
/// A tick as the run left it. A closed tick has all its cells run and the
|
||||
/// clock advanced by the tick's frozen span. The tick a run ended inside is
|
||||
/// recorded too, unclosed, so what its cells committed is not lost; a later
|
||||
/// run finds that tick's document open and works in it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TickCheckpoint {
|
||||
/// The tick's ordinal, as its tick document names it.
|
||||
pub tick: u64,
|
||||
pub closed: bool,
|
||||
pub cells: u32,
|
||||
/// Every command the tick's cells hold a receipt for, in cell order. A
|
||||
/// decline is a commit, so it is listed.
|
||||
pub committed: Vec<CommandId>,
|
||||
pub refusals: Vec<Refusal>,
|
||||
/// The calls grouped cells received that named no handle, in cell order.
|
||||
pub unattributed: Vec<UnattributedCall>,
|
||||
/// Tokens the recording port charged during the tick.
|
||||
pub tokens: u64,
|
||||
}
|
||||
|
||||
/// The knobs as a record carries them.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RecordedKnobs {
|
||||
/// Band periods in fictional minutes, by distance.
|
||||
pub bands: Vec<u32>,
|
||||
pub depth: u8,
|
||||
pub max_node_turns: u16,
|
||||
pub cells: u16,
|
||||
pub constituent_cap: u16,
|
||||
pub urgency_slots: u16,
|
||||
}
|
||||
|
||||
impl RecordedKnobs {
|
||||
pub fn of(knobs: &GestaltKnobs) -> Self {
|
||||
Self {
|
||||
bands: knobs.bands.iter().map(|band| band.minutes()).collect(),
|
||||
depth: knobs.depth,
|
||||
max_node_turns: knobs.max_node_turns,
|
||||
cells: knobs.cover.cells,
|
||||
constituent_cap: knobs.cover.constituent_cap,
|
||||
urgency_slots: knobs.cover.urgency_slots,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What closed a tick.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum TickClose {
|
||||
/// The run with this sequence submitted the tick's clock advance.
|
||||
Clock { run: u64 },
|
||||
/// A later run found the world's ordinal past the tick with the document
|
||||
/// still open: its clock landed and the close was lost, or another clock
|
||||
/// writer moved time.
|
||||
World,
|
||||
}
|
||||
|
||||
/// What a tick decided when it opened. Document `ghostlight.verse_tick.v3`,
|
||||
/// keyed (world, ordinal). Written once before the tick's first cell, closed
|
||||
/// once, never reopened or deleted.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct VerseTick {
|
||||
pub world_id: WorldId,
|
||||
pub ordinal: u64,
|
||||
pub opened_now: u64,
|
||||
pub opened_revision: u64,
|
||||
pub span_minutes: u32,
|
||||
pub knobs: RecordedKnobs,
|
||||
pub oversubscribed: bool,
|
||||
pub cells: Vec<FrozenCell>,
|
||||
/// The nodes the plan left out, with why: not due, or past the node-turn
|
||||
/// bound. Written with the cells so a resumed tick reports what its wave
|
||||
/// left out, not what a re-plan would.
|
||||
pub deferred: Vec<(NodeId, Deferral)>,
|
||||
pub opened_by_run: u64,
|
||||
pub closed: Option<TickClose>,
|
||||
}
|
||||
|
||||
/// One invocation of the verse runner: what it was asked, what it did.
|
||||
/// Document `ghostlight.verse_run.v2`, keyed (world, run sequence).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct VerseRunRecord {
|
||||
pub world_id: WorldId,
|
||||
pub sequence: u64,
|
||||
pub token_cap: u64,
|
||||
pub ticks_requested: u32,
|
||||
pub tick_span_minutes: u32,
|
||||
pub knobs: RecordedKnobs,
|
||||
/// The world's revision when the run began.
|
||||
pub start_revision: u64,
|
||||
pub checkpoints: Vec<TickCheckpoint>,
|
||||
pub status: RunStatus,
|
||||
}
|
||||
|
||||
impl VerseRunRecord {
|
||||
/// The ticks this run finished: every cell run and the clock advanced.
|
||||
pub fn ticks_closed(&self) -> usize {
|
||||
self.checkpoints.iter().filter(|c| c.closed).count()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a caller asks of one run. The token cap is not here: the recording
|
||||
/// port owns it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VerseRunConfig {
|
||||
pub ticks: u32,
|
||||
pub tick_span: TickMinutes,
|
||||
pub knobs: GestaltKnobs,
|
||||
}
|
||||
|
||||
/// A tick as the operator reads it, including the one a run ended inside.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TickReport {
|
||||
pub checkpoint: TickCheckpoint,
|
||||
/// The tick's nodes in run order, each with its acts and refusals.
|
||||
pub nodes: Vec<NodeReport>,
|
||||
/// The labels of the subjects the checkpoint's refusals name, from the
|
||||
/// snapshot the tick opened on.
|
||||
pub labels: BTreeMap<SubjectId, String>,
|
||||
/// What this invocation's calls for the tick's cells cost, by lane and node.
|
||||
pub spend: WaveSpend,
|
||||
/// Nodes that took no turn this tick, and why: the plan left them out, or
|
||||
/// the window's allowance ran out first.
|
||||
pub deferred: Vec<DeferredNode>,
|
||||
pub spent: u64,
|
||||
pub remaining: u64,
|
||||
}
|
||||
|
||||
impl TickReport {
|
||||
/// Every act the tick committed, grouped by node in run order.
|
||||
pub fn acts(&self) -> impl Iterator<Item = &OperatorEvent> {
|
||||
self.nodes.iter().flat_map(|node| node.acts.iter())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RunStatus {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Running => f.write_str("Running"),
|
||||
Self::Completed => f.write_str("Completed"),
|
||||
Self::BudgetExhausted => f.write_str("BudgetExhausted"),
|
||||
Self::Failed { reason } => write!(f, "Failed ({reason})"),
|
||||
Self::Stopped => f.write_str("Stopped"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The tick as the operator reads it: a header, then per node its label,
|
||||
/// distance and spend, one line per committed act (who, which verb, how it
|
||||
/// renders, what its roles are bound to, what was said or shown) and one per
|
||||
/// refusal, then the spend.
|
||||
impl std::fmt::Display for TickReport {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let checkpoint = &self.checkpoint;
|
||||
writeln!(
|
||||
f,
|
||||
"tick {} {}: {} cells, {} acts, {} refused",
|
||||
checkpoint.tick,
|
||||
if checkpoint.closed { "closed" } else { "open" },
|
||||
checkpoint.cells,
|
||||
self.acts().count(),
|
||||
checkpoint.refusals.len()
|
||||
)?;
|
||||
for node in &self.nodes {
|
||||
match node.distance {
|
||||
Some(distance) => {
|
||||
writeln!(f, " node {} (distance {distance}): {} tokens", node.label, node.spent)?
|
||||
}
|
||||
None => writeln!(f, " node {}: {} tokens", node.label, node.spent)?,
|
||||
}
|
||||
for act in &node.acts {
|
||||
writeln!(f, " {}", act_line(act))?;
|
||||
}
|
||||
for refusal in &node.refusals {
|
||||
let reason = match refusal.reason {
|
||||
RefusalReason::Interrupted => "interrupted",
|
||||
RefusalReason::WorldRejected => "world_rejected",
|
||||
RefusalReason::OpportunityGone => "opportunity_gone",
|
||||
RefusalReason::ScopeMoved => "scope_moved",
|
||||
RefusalReason::ProposalUndecodable => "proposal_undecodable",
|
||||
RefusalReason::RowDisagreesWithCell => "row_disagrees_with_cell",
|
||||
RefusalReason::CallUnattributed => "call_unattributed",
|
||||
};
|
||||
let label = self.labels.get(&refusal.subject).map_or("-", String::as_str);
|
||||
writeln!(f, " refused: cell {} {label} {reason}", refusal.cell)?;
|
||||
}
|
||||
}
|
||||
for call in &checkpoint.unattributed {
|
||||
writeln!(f, " note: cell {} call names no handle: tool {:?}", call.cell, call.tool)?;
|
||||
}
|
||||
for (reason, name) in [
|
||||
(Deferral::NotDue, "not due"),
|
||||
(Deferral::OverBound, "over the node-turn bound"),
|
||||
(Deferral::Allowance, "past the allowance"),
|
||||
] {
|
||||
let labels: Vec<&str> = self
|
||||
.deferred
|
||||
.iter()
|
||||
.filter(|node| node.reason == reason)
|
||||
.map(|node| node.label.as_str())
|
||||
.collect();
|
||||
if !labels.is_empty() {
|
||||
writeln!(f, " deferred ({name}): {}", labels.join(", "))?;
|
||||
}
|
||||
}
|
||||
writeln!(
|
||||
f,
|
||||
" tokens: {} this tick, {} spent, {} remaining",
|
||||
checkpoint.tokens, self.spent, self.remaining
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RunOutcome {
|
||||
pub record: VerseRunRecord,
|
||||
}
|
||||
|
||||
fn row_key(world: WorldId, sequence: u64) -> String {
|
||||
format!("{}/{sequence:020}", world.key())
|
||||
}
|
||||
|
||||
fn tick_key(world: WorldId, ordinal: u64) -> String {
|
||||
format!("{}/{ordinal:020}", world.key())
|
||||
}
|
||||
|
||||
fn tick_row(tick: &VerseTick) -> Result<CultCacheEnvelope, VerseRunError> {
|
||||
Ok(CultCacheEnvelope {
|
||||
key: tick_key(tick.world_id, tick.ordinal),
|
||||
r#type: TICK_ROW.into(),
|
||||
payload: rmp_serde::to_vec_named(tick).map_err(|_| VerseRunError::Store)?,
|
||||
stored_at: Utc::now().to_rfc3339(),
|
||||
schema_id: Some(TICK_RECORD_SCHEMA.into()),
|
||||
})
|
||||
}
|
||||
|
||||
fn run_row(record: &VerseRunRecord) -> Result<CultCacheEnvelope, VerseRunError> {
|
||||
Ok(CultCacheEnvelope {
|
||||
key: row_key(record.world_id, record.sequence),
|
||||
r#type: RUN_ROW.into(),
|
||||
payload: rmp_serde::to_vec_named(record).map_err(|_| VerseRunError::Store)?,
|
||||
stored_at: Utc::now().to_rfc3339(),
|
||||
schema_id: Some(RUN_RECORD_SCHEMA.into()),
|
||||
})
|
||||
}
|
||||
|
||||
/// A run's number and cap, claimed from the run store before anything of the
|
||||
/// run exists. The call ledger's run id derives from it ([`call_run_id`]), and
|
||||
/// [`run_manual`] runs only the record it names. Not `Clone`: a claim runs once
|
||||
/// or is abandoned.
|
||||
#[derive(Debug)]
|
||||
pub struct RunClaim {
|
||||
world_id: WorldId,
|
||||
sequence: u64,
|
||||
token_cap: u64,
|
||||
}
|
||||
|
||||
impl RunClaim {
|
||||
/// The run's number, the one [`call_run_id`] names.
|
||||
pub fn sequence(&self) -> u64 {
|
||||
self.sequence
|
||||
}
|
||||
}
|
||||
|
||||
/// Every row of the file, split by type.
|
||||
struct Rows {
|
||||
runs: Vec<VerseRunRecord>,
|
||||
ticks: Vec<VerseTick>,
|
||||
}
|
||||
|
||||
/// Run records and tick documents in one CultCache file. A run is claimed
|
||||
/// when it begins and saved again each time it moves, so a row is replaced by
|
||||
/// its own later state. A tick is opened once and closed once, and only by the tick
|
||||
/// driver: the writers are private to this module.
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// fn wedge(store: &ghostlight::VerseRunStore, world: ghostlight::WorldId) {
|
||||
/// store.close_ticks_before(world, 1).unwrap();
|
||||
/// }
|
||||
/// ```
|
||||
pub struct VerseRunStore {
|
||||
store: Mutex<OwnedRedbMessagePackBackingStore>,
|
||||
}
|
||||
|
||||
impl VerseRunStore {
|
||||
/// Opens the file, creating it empty when absent. Every row must be a
|
||||
/// canonical run record of this schema under its own key.
|
||||
pub fn open(path: impl AsRef<Path>) -> Result<Self, VerseRunError> {
|
||||
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())
|
||||
.map_err(|_| VerseRunError::Store)?;
|
||||
store
|
||||
.validate_path_identity()
|
||||
.map_err(|_| VerseRunError::Store)?;
|
||||
let opened = Self {
|
||||
store: Mutex::new(store),
|
||||
};
|
||||
opened.records()?;
|
||||
Ok(opened)
|
||||
}
|
||||
|
||||
fn records(&self) -> Result<Rows, VerseRunError> {
|
||||
let rows = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|_| VerseRunError::Store)?
|
||||
.pull_all()
|
||||
.map_err(|_| VerseRunError::Store)?;
|
||||
let mut runs = Vec::new();
|
||||
let mut ticks = Vec::new();
|
||||
for row in &rows {
|
||||
match (row.r#type.as_str(), row.schema_id.as_deref()) {
|
||||
(RUN_ROW, Some(RUN_RECORD_SCHEMA)) => {
|
||||
let record: VerseRunRecord =
|
||||
canonical(row).map_err(|_| VerseRunError::Corrupt)?;
|
||||
if row.key != row_key(record.world_id, record.sequence)
|
||||
|| record.sequence == 0
|
||||
{
|
||||
return Err(VerseRunError::Corrupt);
|
||||
}
|
||||
runs.push(record);
|
||||
}
|
||||
(TICK_ROW, Some(TICK_RECORD_SCHEMA)) => {
|
||||
let tick: VerseTick = canonical(row).map_err(|_| VerseRunError::Corrupt)?;
|
||||
if row.key != tick_key(tick.world_id, tick.ordinal) {
|
||||
return Err(VerseRunError::Corrupt);
|
||||
}
|
||||
ticks.push(tick);
|
||||
}
|
||||
(_, Some(schema)) if RETIRED_SCHEMAS.contains(&schema) => {
|
||||
return Err(VerseRunError::RetiredSchema);
|
||||
}
|
||||
_ => return Err(VerseRunError::Corrupt),
|
||||
}
|
||||
}
|
||||
runs.sort_by_key(|record| (record.world_id.key(), record.sequence));
|
||||
ticks.sort_by_key(|tick| (tick.world_id.key(), tick.ordinal));
|
||||
Ok(Rows { runs, ticks })
|
||||
}
|
||||
|
||||
/// The sequence the next claim of this world takes. Sequences count from
|
||||
/// one. Private: a caller never chooses a run's number, `claim` does.
|
||||
fn next_sequence(&self, world: WorldId) -> Result<u64, VerseRunError> {
|
||||
Ok(self
|
||||
.records()?
|
||||
.runs
|
||||
.iter()
|
||||
.filter(|record| record.world_id == world)
|
||||
.map(|record| record.sequence)
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
+ 1)
|
||||
}
|
||||
|
||||
/// Every run of the world, in sequence.
|
||||
pub fn runs(&self, world: WorldId) -> Result<Vec<VerseRunRecord>, VerseRunError> {
|
||||
Ok(self
|
||||
.records()?
|
||||
.runs
|
||||
.into_iter()
|
||||
.filter(|record| record.world_id == world)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The tick document of (world, ordinal), when one was opened.
|
||||
pub fn tick(&self, world: WorldId, ordinal: u64) -> Result<Option<VerseTick>, VerseRunError> {
|
||||
Ok(self
|
||||
.records()?
|
||||
.ticks
|
||||
.into_iter()
|
||||
.find(|tick| tick.world_id == world && tick.ordinal == ordinal))
|
||||
}
|
||||
|
||||
/// Writes a tick document that does not exist yet, open. The store's own
|
||||
/// insert-if-absent decides, so two opens of one ordinal cannot both win.
|
||||
/// Private: the tick driver is the only writer of tick rows.
|
||||
fn open_tick(&self, tick: &VerseTick) -> Result<(), VerseRunError> {
|
||||
if tick.closed.is_some() {
|
||||
return Err(VerseRunError::OutOfSequence);
|
||||
}
|
||||
let row = tick_row(tick)?;
|
||||
let inserted = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|_| VerseRunError::Store)?
|
||||
.insert_entry_if_absent(row)
|
||||
.map_err(|_| VerseRunError::Store)?;
|
||||
if inserted {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(VerseRunError::OutOfSequence)
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes an open tick document. Private, like every tick writer.
|
||||
fn close_tick(
|
||||
&self,
|
||||
world: WorldId,
|
||||
ordinal: u64,
|
||||
close: TickClose,
|
||||
) -> Result<(), VerseRunError> {
|
||||
let Some(mut tick) = self.tick(world, ordinal)? else {
|
||||
return Err(VerseRunError::OutOfSequence);
|
||||
};
|
||||
if tick.closed.is_some() {
|
||||
return Err(VerseRunError::OutOfSequence);
|
||||
}
|
||||
tick.closed = Some(close);
|
||||
self.put_tick(&tick)
|
||||
}
|
||||
|
||||
/// Closes, as the world's, every open tick of the world below `ordinal`.
|
||||
fn close_ticks_before(&self, world: WorldId, ordinal: u64) -> Result<(), VerseRunError> {
|
||||
for mut tick in self.records()?.ticks {
|
||||
if tick.world_id == world && tick.ordinal < ordinal && tick.closed.is_none() {
|
||||
tick.closed = Some(TickClose::World);
|
||||
self.put_tick(&tick)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn put_tick(&self, tick: &VerseTick) -> Result<(), VerseRunError> {
|
||||
let row = tick_row(tick)?;
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| VerseRunError::Store)?
|
||||
.push(&row)
|
||||
.map_err(|_| VerseRunError::Store)
|
||||
}
|
||||
|
||||
/// Claims the next run of the snapshot's world: writes its `Running`
|
||||
/// record, with the cap and config it was claimed under, in one insert that
|
||||
/// cannot overwrite a record. The returned claim is the only way to run it;
|
||||
/// a claim that never runs stays `Running` (a process that died) or is
|
||||
/// ended by [`abandon`](Self::abandon), and its number is never issued
|
||||
/// again.
|
||||
pub fn claim(
|
||||
&self,
|
||||
snapshot: &WorldSnapshot,
|
||||
token_cap: u64,
|
||||
config: &VerseRunConfig,
|
||||
) -> Result<RunClaim, VerseRunError> {
|
||||
config.knobs.validate()?;
|
||||
let record = VerseRunRecord {
|
||||
world_id: snapshot.world_id,
|
||||
sequence: self.next_sequence(snapshot.world_id)?,
|
||||
token_cap,
|
||||
ticks_requested: config.ticks,
|
||||
tick_span_minutes: config.tick_span.minutes(),
|
||||
knobs: RecordedKnobs::of(&config.knobs),
|
||||
start_revision: snapshot.revision,
|
||||
checkpoints: Vec::new(),
|
||||
status: RunStatus::Running,
|
||||
};
|
||||
self.insert_run(&record)?;
|
||||
Ok(RunClaim {
|
||||
world_id: record.world_id,
|
||||
sequence: record.sequence,
|
||||
token_cap,
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes a run record that does not exist yet. The store's own
|
||||
/// insert-if-absent decides, so two claims of one sequence cannot both win.
|
||||
fn insert_run(&self, record: &VerseRunRecord) -> Result<(), VerseRunError> {
|
||||
let inserted = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|_| VerseRunError::Store)?
|
||||
.insert_entry_if_absent(run_row(record)?)
|
||||
.map_err(|_| VerseRunError::Store)?;
|
||||
if inserted {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(VerseRunError::OutOfSequence)
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends a claim that never ran: its record becomes `Failed { reason }`.
|
||||
pub fn abandon(&self, claim: RunClaim, reason: &'static str) -> Result<(), VerseRunError> {
|
||||
let mut record = self.claimed(&claim)?;
|
||||
record.status = failed(reason);
|
||||
self.save(&record)
|
||||
}
|
||||
|
||||
/// The record a claim names.
|
||||
fn claimed(&self, claim: &RunClaim) -> Result<VerseRunRecord, VerseRunError> {
|
||||
self.records()?
|
||||
.runs
|
||||
.into_iter()
|
||||
.find(|record| record.world_id == claim.world_id && record.sequence == claim.sequence)
|
||||
.ok_or(VerseRunError::OutOfSequence)
|
||||
}
|
||||
|
||||
/// Replaces a claimed record with its later state. A sequence with no
|
||||
/// record is refused: only `claim` creates one.
|
||||
fn save(&self, record: &VerseRunRecord) -> Result<(), VerseRunError> {
|
||||
self.claimed(&RunClaim {
|
||||
world_id: record.world_id,
|
||||
sequence: record.sequence,
|
||||
token_cap: record.token_cap,
|
||||
})?;
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| VerseRunError::Store)?
|
||||
.push(&run_row(record)?)
|
||||
.map_err(|_| VerseRunError::Store)
|
||||
}
|
||||
}
|
||||
|
||||
enum TickEnd {
|
||||
/// Every cell finished and the clock advanced.
|
||||
Closed,
|
||||
/// The run ends inside this tick with this status.
|
||||
Open(RunStatus),
|
||||
}
|
||||
|
||||
/// The run status a wave's stop ends the run with.
|
||||
fn status_of(stop: WaveStop) -> RunStatus {
|
||||
match stop {
|
||||
WaveStop::Budget => RunStatus::BudgetExhausted,
|
||||
WaveStop::Fault(code) => failed(code),
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(reason: &str) -> RunStatus {
|
||||
RunStatus::Failed {
|
||||
reason: reason.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `config.ticks` ticks from the world's present clock under the cap the
|
||||
/// recording port was opened with. `observe` sees each tick as it ends,
|
||||
/// including the one a run ends inside, and may stop the run after a finished
|
||||
/// tick by breaking. `claim` is the run's number from
|
||||
/// [`VerseRunStore::claim`]; the port must have been opened for it
|
||||
/// ([`call_run_id`]) under the cap the claim recorded, and `config` is the one
|
||||
/// the claim was made with. A claim this refuses is abandoned, so a refused
|
||||
/// start binds nothing.
|
||||
pub async fn run_manual(
|
||||
mailbox: &WorldMailbox,
|
||||
runner: &ControllerRunner,
|
||||
port: &RecordingInferencePort,
|
||||
store: &VerseRunStore,
|
||||
claim: RunClaim,
|
||||
config: &VerseRunConfig,
|
||||
mut observe: impl FnMut(&TickReport) -> ControlFlow<()>,
|
||||
) -> Result<RunOutcome, VerseRunError> {
|
||||
let begun = match mailbox.snapshot().await {
|
||||
Ok(begun) => begun,
|
||||
Err(error) => {
|
||||
store.abandon(claim, "world_unavailable")?;
|
||||
return Err(error.into());
|
||||
}
|
||||
};
|
||||
if port.run_id() != &call_run_id(claim.sequence)
|
||||
|| port.cap() != claim.token_cap
|
||||
|| begun.world_id != claim.world_id
|
||||
{
|
||||
store.abandon(claim, "port_not_this_run")?;
|
||||
return Err(VerseRunError::PortNotThisRun);
|
||||
}
|
||||
let sequence = claim.sequence;
|
||||
let mut record = store.claimed(&claim)?;
|
||||
if config.knobs.validate().is_err() || !record_matches(&record, config) {
|
||||
store.abandon(claim, "config_not_this_claim")?;
|
||||
return Err(VerseRunError::ConfigNotThisClaim);
|
||||
}
|
||||
// The record names the revision the run started from, so the run starts
|
||||
// from it.
|
||||
if record.start_revision != begun.revision {
|
||||
store.abandon(claim, "world_moved_since_claim")?;
|
||||
return Err(VerseRunError::WorldMovedSinceClaim);
|
||||
}
|
||||
|
||||
let mut spent_before = port.spent();
|
||||
for completed in 0..config.ticks {
|
||||
let (end, report) = run_tick(
|
||||
mailbox,
|
||||
runner,
|
||||
port,
|
||||
store,
|
||||
sequence,
|
||||
config,
|
||||
spent_before,
|
||||
|| mailbox.operator_log(),
|
||||
)
|
||||
.await;
|
||||
spent_before = port.spent();
|
||||
match end {
|
||||
TickEnd::Open(status) => {
|
||||
record.status = status;
|
||||
if let Some(report) = report {
|
||||
record.checkpoints.push(report.checkpoint.clone());
|
||||
store.save(&record)?;
|
||||
let _ = observe(&report);
|
||||
} else {
|
||||
store.save(&record)?;
|
||||
}
|
||||
return Ok(RunOutcome { record });
|
||||
}
|
||||
TickEnd::Closed => {
|
||||
let report = report.expect("a closed tick has its report");
|
||||
record.checkpoints.push(report.checkpoint.clone());
|
||||
store.save(&record)?;
|
||||
if observe(&report).is_break() && completed + 1 < config.ticks {
|
||||
record.status = RunStatus::Stopped;
|
||||
store.save(&record)?;
|
||||
return Ok(RunOutcome { record });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
record.status = RunStatus::Completed;
|
||||
store.save(&record)?;
|
||||
Ok(RunOutcome { record })
|
||||
}
|
||||
|
||||
/// Whether the record a claim wrote was made under this config.
|
||||
fn record_matches(record: &VerseRunRecord, config: &VerseRunConfig) -> bool {
|
||||
record.ticks_requested == config.ticks
|
||||
&& record.tick_span_minutes == config.tick_span.minutes()
|
||||
&& record.knobs == RecordedKnobs::of(&config.knobs)
|
||||
}
|
||||
|
||||
/// The key a run's provider calls are recorded under: the run's sequence, so a
|
||||
/// run record and its call records name each other.
|
||||
pub fn call_run_id(sequence: u64) -> super::RunId {
|
||||
super::RunId::new(&format!("run-{sequence}"))
|
||||
.expect("a decimal sequence is a canonical run id")
|
||||
}
|
||||
|
||||
/// The id of a tick's clock advance: the world and the ordinal, nothing the
|
||||
/// run holds. A retry in the same tick has the same body and is answered
|
||||
/// `AlreadyApplied`.
|
||||
pub(crate) fn clock_command_id(world: WorldId, ordinal: u64) -> CommandId {
|
||||
CommandId::derived(CLOCK_NAMESPACE, &[&world.text(), &ordinal.to_string()])
|
||||
}
|
||||
|
||||
/// One tick. The report is absent only when the world or the tick document
|
||||
/// could not be read at all.
|
||||
async fn run_tick<ReadLog, Log>(
|
||||
mailbox: &WorldMailbox,
|
||||
runner: &ControllerRunner,
|
||||
port: &RecordingInferencePort,
|
||||
store: &VerseRunStore,
|
||||
sequence: u64,
|
||||
config: &VerseRunConfig,
|
||||
spent_before: u64,
|
||||
read_log: ReadLog,
|
||||
) -> (TickEnd, Option<TickReport>)
|
||||
where
|
||||
ReadLog: FnOnce() -> Log,
|
||||
Log: Future<Output = Result<Vec<OperatorEvent>, MailboxError>>,
|
||||
{
|
||||
let read = async {
|
||||
let snapshot = mailbox.snapshot().await?;
|
||||
let ordinal = mailbox.clock_advances().await?;
|
||||
let opportunities = mailbox.opportunities().await?;
|
||||
let graph = mailbox.agency_graph().await?;
|
||||
let hierarchy = mailbox.hierarchy().await?;
|
||||
Ok::<_, MailboxError>((snapshot, ordinal, opportunities, graph, hierarchy))
|
||||
}
|
||||
.await;
|
||||
let Ok((snapshot, ordinal, opportunities, graph, hierarchy)) = read else {
|
||||
return (TickEnd::Open(failed("world_unavailable")), None);
|
||||
};
|
||||
let world = snapshot.world_id;
|
||||
let Ok(tick) = open_or_find(
|
||||
store,
|
||||
ordinal,
|
||||
sequence,
|
||||
config,
|
||||
&snapshot,
|
||||
&opportunities,
|
||||
&graph,
|
||||
&hierarchy,
|
||||
) else {
|
||||
return (TickEnd::Open(failed("run_store")), None);
|
||||
};
|
||||
let index = TickIndex(ordinal);
|
||||
let Some(span) = TickMinutes::new(tick.span_minutes) else {
|
||||
return (TickEnd::Open(failed("run_store")), None);
|
||||
};
|
||||
|
||||
let outcome = run_frozen_cells(mailbox, runner, index, &tick.cells).await;
|
||||
let mut open = outcome.stop.map(status_of);
|
||||
|
||||
// The act listing is the tick's report to the operator: a tick whose log
|
||||
// cannot be read is not closed, and the run ends there.
|
||||
let acts = match acts_since(read_log().await, snapshot.revision) {
|
||||
Some(acts) => acts,
|
||||
None => {
|
||||
open = Some(failed("operator_log_unavailable"));
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
|
||||
// So is a tick whose calls cannot be read back: its nodes' spend is the
|
||||
// report's, and the ledger and the world must agree before time moves.
|
||||
let spend = match port
|
||||
.records()
|
||||
.ok()
|
||||
.and_then(|records| WaveSpend::of(&records, world, index, &tick.cells).ok())
|
||||
{
|
||||
Some(spend) => spend,
|
||||
None => {
|
||||
open = Some(failed("call_records_unavailable"));
|
||||
WaveSpend::default()
|
||||
}
|
||||
};
|
||||
|
||||
if open.is_none() {
|
||||
if mailbox
|
||||
.submit_clock(clock_command_id(world, ordinal), span)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
open = Some(failed("clock_refused"));
|
||||
} else if store
|
||||
.close_tick(world, ordinal, TickClose::Clock { run: sequence })
|
||||
.is_err()
|
||||
{
|
||||
open = Some(failed("run_store"));
|
||||
}
|
||||
}
|
||||
|
||||
let spent = port.spent();
|
||||
let checkpoint_closed = open.is_none();
|
||||
let mut checkpoint = TickCheckpoint {
|
||||
tick: ordinal,
|
||||
closed: checkpoint_closed,
|
||||
cells: tick.cells.len() as u32,
|
||||
committed: Vec::new(),
|
||||
refusals: Vec::new(),
|
||||
unattributed: Vec::new(),
|
||||
tokens: spent.saturating_sub(spent_before),
|
||||
};
|
||||
for node in &outcome.nodes {
|
||||
checkpoint.committed.extend(node.committed.iter().copied());
|
||||
checkpoint.refusals.extend(node.refusals.iter().copied());
|
||||
checkpoint.unattributed.extend(node.unattributed.iter().cloned());
|
||||
}
|
||||
let labels = checkpoint
|
||||
.refusals
|
||||
.iter()
|
||||
.filter_map(|refusal| {
|
||||
snapshot
|
||||
.subjects
|
||||
.iter()
|
||||
.find(|subject| subject.id == refusal.subject)
|
||||
.map(|subject| (refusal.subject, subject.label.clone()))
|
||||
})
|
||||
.collect();
|
||||
let report = TickReport {
|
||||
nodes: node_reports(&tick.cells, &outcome, acts, &spend, &snapshot, &hierarchy),
|
||||
deferred: deferred_nodes(&tick.deferred, &tick.cells, &outcome, &snapshot, &hierarchy),
|
||||
spend,
|
||||
checkpoint,
|
||||
labels,
|
||||
spent,
|
||||
remaining: port.cap().saturating_sub(spent),
|
||||
};
|
||||
(open.map_or(TickEnd::Closed, TickEnd::Open), Some(report))
|
||||
}
|
||||
|
||||
/// The tick document for `ordinal`: the open one a run left, or a new one
|
||||
/// frozen from a wave planned now over the derived hierarchy with no focus. An
|
||||
/// open tick the world has moved past is closed as the world's first. A
|
||||
/// document already closed at the world's current ordinal is a store that
|
||||
/// disagrees with the world.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn open_or_find(
|
||||
store: &VerseRunStore,
|
||||
ordinal: u64,
|
||||
sequence: u64,
|
||||
config: &VerseRunConfig,
|
||||
snapshot: &WorldSnapshot,
|
||||
opportunities: &[DecisionOpportunity],
|
||||
graph: &AgencyGraph,
|
||||
hierarchy: &Hierarchy,
|
||||
) -> Result<VerseTick, VerseRunError> {
|
||||
let world = snapshot.world_id;
|
||||
store.close_ticks_before(world, ordinal)?;
|
||||
if let Some(tick) = store.tick(world, ordinal)? {
|
||||
return if tick.closed.is_none() {
|
||||
Ok(tick)
|
||||
} else {
|
||||
Err(VerseRunError::OutOfSequence)
|
||||
};
|
||||
}
|
||||
let wave = plan_wave(
|
||||
WaveClock {
|
||||
world,
|
||||
ordinal: TickIndex(ordinal),
|
||||
now: FictionalMinutes(snapshot.now.0),
|
||||
},
|
||||
hierarchy,
|
||||
opportunities,
|
||||
graph,
|
||||
&Focus::default(),
|
||||
&[],
|
||||
&config.knobs,
|
||||
)?;
|
||||
let tick = VerseTick {
|
||||
world_id: world,
|
||||
ordinal,
|
||||
opened_now: snapshot.now.0,
|
||||
opened_revision: snapshot.revision,
|
||||
span_minutes: config.tick_span.minutes(),
|
||||
knobs: RecordedKnobs::of(&config.knobs),
|
||||
oversubscribed: wave.turns.iter().any(|turn| turn.oversubscribed),
|
||||
cells: wave.frozen(),
|
||||
deferred: wave.deferred,
|
||||
opened_by_run: sequence,
|
||||
closed: None,
|
||||
};
|
||||
store.open_tick(&tick)?;
|
||||
Ok(tick)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -57,7 +57,6 @@ impl World {
|
|||
// 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,
|
||||
)
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -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.
|
||||
BIN
crates/ghostlight/tests/fixtures/base_world.cc
vendored
BIN
crates/ghostlight/tests/fixtures/base_world.cc
vendored
Binary file not shown.
|
|
@ -1,3 +0,0 @@
|
|||
3
|
||||
sha256:b706f57cb417603366a1f47a5dd099fbf68bfecc5b2e8d61d281630791d1d76d
|
||||
sha256:2039956a26c3d5b073d101e5898ac5a60a9eb63a3b93f447b2d8f78ef4caf979
|
||||
|
|
@ -1 +0,0 @@
|
|||
"a534b32a-4d00-429c-bf6c-ce1d55385380"
|
||||
|
|
@ -1,12 +1,21 @@
|
|||
schema = "gamecult.idunn.target_declaration.v1"
|
||||
target = "ghostlight"
|
||||
source_stamp_environment = "GHOSTLIGHT_BUILD_COMMIT"
|
||||
required_gitlinks = ["vendor/eve"]
|
||||
|
||||
# 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-persona-boundary"
|
||||
phase = "test"
|
||||
runner = "rust-build"
|
||||
required_environment = ["CARGO_HOME", "HOME"]
|
||||
argv = ["cargo", "test", "--locked", "-p", "ghostlight-persona-projection"]
|
||||
|
||||
[[steps]]
|
||||
id = "test-world-library"
|
||||
phase = "test"
|
||||
runner = "rust-build"
|
||||
required_environment = ["CARGO_HOME", "HOME"]
|
||||
argv = ["cargo", "test", "--locked", "-p", "ghostlight"]
|
||||
|
||||
[[steps]]
|
||||
id = "test-dungeon"
|
||||
|
|
@ -22,6 +31,56 @@ runner = "rust-build"
|
|||
required_environment = ["CARGO_HOME", "HOME"]
|
||||
argv = ["cargo", "build", "--locked", "--release", "-p", "ghostlight-dungeon", "--bin", "ghostlight-dungeon"]
|
||||
|
||||
[[steps]]
|
||||
id = "install-web-dependencies"
|
||||
phase = "prepare"
|
||||
runner = "web-build"
|
||||
required_environment = ["HOME", "NPM_CONFIG_CACHE"]
|
||||
argv = ["npm", "--prefix", "web", "ci"]
|
||||
|
||||
[[steps]]
|
||||
id = "test-web"
|
||||
phase = "test"
|
||||
runner = "web-build"
|
||||
required_environment = ["HOME", "NPM_CONFIG_CACHE"]
|
||||
argv = ["npm", "--prefix", "web", "test"]
|
||||
|
||||
[[steps]]
|
||||
id = "build-web"
|
||||
phase = "build"
|
||||
runner = "web-build"
|
||||
required_environment = ["HOME", "NPM_CONFIG_CACHE"]
|
||||
argv = ["npm", "--prefix", "web", "run", "build"]
|
||||
|
||||
[[steps]]
|
||||
id = "accept-real-persona-membrane"
|
||||
phase = "acceptance"
|
||||
runner = "rust-acceptance"
|
||||
argv = [
|
||||
"cargo",
|
||||
"test",
|
||||
"--locked",
|
||||
"-p",
|
||||
"ghostlight",
|
||||
"--lib",
|
||||
"controllers::tests::real_local_model_cognition_modes_commit_speech",
|
||||
"--",
|
||||
"--ignored",
|
||||
"--exact",
|
||||
]
|
||||
required_environment = [
|
||||
"CARGO_HOME",
|
||||
"GHOSTLIGHT_ACCEPTANCE_PERSONA_PROSE_LOG",
|
||||
"GHOSTLIGHT_ACCEPTANCE_RUNTIME_ID",
|
||||
"GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_PERSONA_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL",
|
||||
"HOME",
|
||||
"GHOSTLIGHT_LOCAL_ENDPOINT",
|
||||
]
|
||||
|
||||
[[artifacts]]
|
||||
id = "ghostlight-dungeon"
|
||||
source_kind = "runner-output"
|
||||
|
|
@ -30,8 +89,16 @@ source = "target/release/ghostlight-dungeon"
|
|||
destination = "ghostlight-dungeon"
|
||||
executable = true
|
||||
|
||||
[[artifacts]]
|
||||
id = "web"
|
||||
source_kind = "runner-output"
|
||||
runner = "web-build"
|
||||
source = "web/dist"
|
||||
destination = "web"
|
||||
|
||||
[service]
|
||||
executable_artifact = "ghostlight-dungeon"
|
||||
required_adjacent_artifacts = ["web"]
|
||||
arguments = [
|
||||
{ kind = "literal", value = "--state-root" },
|
||||
{ kind = "binding", name = "state_root" },
|
||||
|
|
@ -42,40 +109,36 @@ required_environment = [
|
|||
"GAMECULT_IDUNN_CANDIDATE_BIND",
|
||||
"GAMECULT_IDUNN_PROCESS_WRITE_LEASE",
|
||||
"GAMECULT_IDUNN_RUNTIME_BUNDLE",
|
||||
"GHOSTLIGHT_CONNECTOR_ADDR",
|
||||
"GHOSTLIGHT_CONNECTOR_KEY_FILE",
|
||||
"GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_PERSONA_MODEL",
|
||||
"GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL",
|
||||
"GHOSTLIGHT_DISCORD_GUILD_ID",
|
||||
"GHOSTLIGHT_DISCORD_ROLE_ID",
|
||||
"GHOSTLIGHT_HEIMDALL_APP_SECRET_FILE",
|
||||
"GHOSTLIGHT_HEIMDALL_BASE_URL",
|
||||
"GHOSTLIGHT_LOCAL_ENDPOINT",
|
||||
"GHOSTLIGHT_LOCATED_SERVICE",
|
||||
"GHOSTLIGHT_ODIN_RUDP",
|
||||
"GHOSTLIGHT_PLAY_MODEL",
|
||||
"GHOSTLIGHT_PUBLIC_APP_URL",
|
||||
"GHOSTLIGHT_SERVICE_ID",
|
||||
"GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE",
|
||||
]
|
||||
optional_environment = [
|
||||
"GHOSTLIGHT_AUTH_PROVIDERS",
|
||||
"GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT",
|
||||
"RUST_LOG",
|
||||
]
|
||||
optional_environment = ["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"
|
||||
schema_generation = "world-v3"
|
||||
|
||||
[[state.slots]]
|
||||
id = "catalog"
|
||||
relative_path = "catalog.cc"
|
||||
id = "world"
|
||||
relative_path = "world.cc"
|
||||
kind = "cultcache-file"
|
||||
schema = "ghostlight.dungeon_catalog.v1"
|
||||
schema = "ghostlight.world_state.consumer.v6"
|
||||
writer = "process-bound-single-writer"
|
||||
recovery = "preserve"
|
||||
startup = "create-or-open-after-write-lease"
|
||||
|
|
@ -90,21 +153,21 @@ recovery = "preserve"
|
|||
startup = "create-or-open-after-write-lease"
|
||||
|
||||
[[state.slots]]
|
||||
id = "snapshots"
|
||||
relative_path = "snapshots"
|
||||
kind = "external-file"
|
||||
schema = "ghostlight.vault_snapshot.v1"
|
||||
id = "controller-work"
|
||||
relative_path = "service/controller-work.cc"
|
||||
kind = "cultcache-file"
|
||||
schema = "ghostlight.controller_work.v17"
|
||||
writer = "process-bound-single-writer"
|
||||
recovery = "rebuildable"
|
||||
recovery = "preserve"
|
||||
startup = "create-or-open-after-write-lease"
|
||||
|
||||
[[state.slots]]
|
||||
id = "timelines"
|
||||
relative_path = "timelines"
|
||||
kind = "external-file"
|
||||
schema = "ghostlight.world_state.consumer.v6"
|
||||
id = "mesh-projection"
|
||||
relative_path = "service/mesh-v2.cc"
|
||||
kind = "cultcache-file"
|
||||
schema = "gamecult.eve.surface.v1"
|
||||
writer = "process-bound-single-writer"
|
||||
recovery = "preserve"
|
||||
recovery = "rebuildable"
|
||||
startup = "create-or-open-after-write-lease"
|
||||
|
||||
[[provides]]
|
||||
|
|
@ -112,7 +175,11 @@ 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.
|
||||
[[provides]]
|
||||
capability = "gamecult.eve.surface-provider"
|
||||
schema = "gamecult.eve.surface.v1"
|
||||
compatibility = "v1"
|
||||
|
||||
[[dependencies]]
|
||||
kind = "shared-infrastructure"
|
||||
capability = "odin.verse-rendezvous"
|
||||
|
|
|
|||
169
docs/aetheria/call-of-the-void-brainstorm.md
Normal file
169
docs/aetheria/call-of-the-void-brainstorm.md
Normal 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.
|
||||
386
docs/architecture/aetheria-agent-population-model.md
Normal file
386
docs/architecture/aetheria-agent-population-model.md
Normal 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.
|
||||
206
docs/architecture/aetheria-content-generation-targets.md
Normal file
206
docs/architecture/aetheria-content-generation-targets.md
Normal 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.
|
||||
386
docs/architecture/aetheria-lore-grounding-architecture.md
Normal file
386
docs/architecture/aetheria-lore-grounding-architecture.md
Normal 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.
|
||||
586
docs/architecture/aetheria-persistent-agent-architecture.md
Normal file
586
docs/architecture/aetheria-persistent-agent-architecture.md
Normal 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.
|
||||
|
|
@ -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.
|
||||
273
docs/architecture/agent-state-variable-glossary.md
Normal file
273
docs/architecture/agent-state-variable-glossary.md
Normal 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.
|
||||
244
docs/architecture/canonical-agent-state-schema.md
Normal file
244
docs/architecture/canonical-agent-state-schema.md
Normal 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.
|
||||
81
docs/architecture/corpus-coverage-ledger.md
Normal file
81
docs/architecture/corpus-coverage-ledger.md
Normal 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.
|
||||
98
docs/architecture/cultnet-shared-agent-state-contract.md
Normal file
98
docs/architecture/cultnet-shared-agent-state-contract.md
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
# CultNet Shared Agent-State Contract
|
||||
|
||||
Ghostlight owns the first cross-runtime agent-state payload contract.
|
||||
|
||||
That contract is not a new ontology. It is the existing Ghostlight state shape
|
||||
moving over a wire without turning into bespoke JSON fog in every other repo.
|
||||
|
||||
## Canonical Payload
|
||||
|
||||
The first shared payload contract is:
|
||||
|
||||
- schema id:
|
||||
`https://github.com/GameCult/Ghostlight/schemas/agent-state.schema.json`
|
||||
- schema version:
|
||||
`ghostlight.agent_state.v0`
|
||||
- canonical file:
|
||||
`schemas/agent-state.schema.json`
|
||||
|
||||
This is the same state shape already used for Ghostlight fixtures and the same
|
||||
top-level shape Epiphany role dossiers adopted. The contract is:
|
||||
|
||||
- `world`
|
||||
- `agents`
|
||||
- `relationships`
|
||||
- `events`
|
||||
- `scenes`
|
||||
|
||||
If another runtime wants to carry socially persistent agent state without
|
||||
inventing its own private folk religion, this is the first house shape.
|
||||
|
||||
## Wire Envelope
|
||||
|
||||
CultNet should carry the Ghostlight payload as a typed document replication
|
||||
message, not as a one-off ad hoc blob.
|
||||
|
||||
Current expected document envelope:
|
||||
|
||||
- `documentType`: `ghostlight.agent-state`
|
||||
- `documentKey`: runtime-defined stable key
|
||||
- `payloadSchemaVersion`: `ghostlight.agent_state.v0`
|
||||
- `payload`: exact Ghostlight state document
|
||||
|
||||
The current TypeScript client library is:
|
||||
|
||||
- package: `cultnet-ts`, in `GameCult/CultLib` under `packages/cultnet-ts`
|
||||
|
||||
Its job is not merely to make pipes pretty. It owns:
|
||||
|
||||
- direct-pipe MessagePack framing
|
||||
- typed message contracts
|
||||
- authentication/session semantics compatible with CultLib's `GameCult.Networking`
|
||||
- typed replication into CultCache-compatible stores
|
||||
|
||||
## Authentication Story
|
||||
|
||||
CultNet inherits the useful security shape from CultLib:
|
||||
|
||||
- a shared connection key known to client and server/runtime peers
|
||||
- AES-GCM encrypted auth/session payloads derived from that key
|
||||
- a server-side session-signing secret
|
||||
- signed session tokens used for verify/reconnect flows
|
||||
|
||||
This matters because "shared agent state" is not only a serialization problem.
|
||||
It is also a trust boundary problem. We want one family resemblance across C#,
|
||||
TypeScript, Rust, and Python instead of four mutually unintelligible little
|
||||
shrines to local convenience.
|
||||
|
||||
## Contract Discipline
|
||||
|
||||
Ghostlight remains the source of truth for the payload shape.
|
||||
|
||||
That means:
|
||||
|
||||
- if `schemas/agent-state.schema.json` changes, CultNet mirrors must update in
|
||||
lockstep
|
||||
- consumers may add local document metadata around the payload, but should not
|
||||
silently mutate the payload contract itself
|
||||
- if a runtime needs a narrower projection or local working view, that is a
|
||||
derivative contract, not a revision of `ghostlight.agent_state.v0`
|
||||
|
||||
The rule is simple:
|
||||
|
||||
- prompt projection may differ
|
||||
- storage engines may differ
|
||||
- language bindings may differ
|
||||
- the shared payload contract does not drift just because another repo got
|
||||
lonely
|
||||
|
||||
## Immediate Consumers
|
||||
|
||||
The first intended consumers are:
|
||||
|
||||
- Ghostlight fixture/state tooling
|
||||
- EpiphanyAgent role dossiers and heartbeat-adjacent agent state
|
||||
- VoidBot companion-state and social memory machinery where the full Ghostlight
|
||||
payload is useful
|
||||
|
||||
More bindings can come later. They do not get to invent a prettier truth.
|
||||
141
docs/architecture/ghostlight-dungeon-multiplayer-intention.md
Normal file
141
docs/architecture/ghostlight-dungeon-multiplayer-intention.md
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
# Ghostlight Dungeon Multiplayer Intention
|
||||
|
||||
## Status
|
||||
|
||||
Bounded cooperative multiplayer is implemented in the current MVP: one to
|
||||
eight authenticated players create and seed a world (`world.create` v2,
|
||||
`world.seed`) and begin in one shared scene with sequential public actions,
|
||||
actor-filtered surfaces, pooled Persona-cell entitlements, and unanimous time,
|
||||
travel, and budget governance.
|
||||
The broader model in this document remains the direction for split parties,
|
||||
private play actions, simultaneous declarations, delegation, and PvP.
|
||||
|
||||
The existing simulation is already shaped around multiple bounded actors. The
|
||||
extension should expose that anatomy to multiple human controllers without
|
||||
creating a second world authority or a special multiplayer simulation loop.
|
||||
|
||||
## Objective
|
||||
|
||||
Let several human-controlled characters inhabit one persistent campaign while
|
||||
preserving the same spatial, epistemic, causal, and commit invariants as solo
|
||||
play. The implemented milestone keeps the party together. Split locations,
|
||||
late joining, and private in-play actions remain future governance work.
|
||||
|
||||
## Authority map
|
||||
|
||||
- **Owner:** one per-campaign `WorldKernel` continues to own canonical state,
|
||||
fictional time, revisions, rolls, events, and commits.
|
||||
- **Inputs:** authenticated commands attributed to one campaign member and one
|
||||
exact human-controlled actor; NPC and Gestalt proposals; scheduler commands;
|
||||
current campaign and resolution revisions.
|
||||
- **Outputs:** one atomic world transition plus actor-specific perceived events,
|
||||
narrative projections, news access, and command receipts.
|
||||
- **Derived state:** party rosters, shared transcript views, presence indicators,
|
||||
ready state, and client notifications are projections of campaign membership,
|
||||
occupancy, perception, and committed events.
|
||||
- **Forbidden writers:** browsers, sessions, party leaders, Personas,
|
||||
Interpreters, narrators, initiative, and realtime transports cannot commit or
|
||||
repair campaign state.
|
||||
- **Shared path:** solo commands, bounded multiplayer commands, unanimous waits
|
||||
and travel, NPC reactions, scheduler ticks, and reconnects use the same
|
||||
`WorldCommand → validate → atomic commit` primitive. Future simultaneous
|
||||
windows must join this path too.
|
||||
- **Cut line:** do not add a parallel room-state store, party prompt, shared
|
||||
narrator memory, or multiplayer-only mutation path.
|
||||
|
||||
## Intended model
|
||||
|
||||
```text
|
||||
Player A session ──> actor A command ─┐
|
||||
Player B session ──> actor B command ─┼─> campaign mailbox
|
||||
NPC / Gestalt proposals ──────────────┘ │
|
||||
v
|
||||
WorldKernel
|
||||
│
|
||||
one committed event + revision
|
||||
│ │
|
||||
A-perceived projection B-perceived projection
|
||||
│ │
|
||||
A's surface B's surface
|
||||
```
|
||||
|
||||
A human-controlled actor differs from a Persona-controlled actor only in the
|
||||
source of its candidate action. Human text still describes an attempt. It does
|
||||
not bypass capability, location, custody, knowledge, opposition, assessment,
|
||||
initiative, or commit validation.
|
||||
|
||||
## Invariants
|
||||
|
||||
- Every active canonical subject is represented exactly once in the resolution
|
||||
cover regardless of how many humans are connected.
|
||||
- One authenticated campaign member controls one or more explicitly assigned
|
||||
actors according to campaign policy. Control is never inferred from scene
|
||||
presence.
|
||||
- An absent or disconnected player's character is not puppeted. Delegation or
|
||||
Persona proxying requires an explicit, revocable campaign permission.
|
||||
- Perception and knowledge remain actor-local. A shared party transcript may
|
||||
contain only events all included viewers are permitted to perceive.
|
||||
- Private speech, hidden action, secret evidence, and character-local news are
|
||||
projected only to entitled sessions.
|
||||
- Players in different locations receive different narrative streams derived
|
||||
from the same committed world.
|
||||
- A player cannot make another player's action, reaction, injury, belief, or
|
||||
relationship true by describing it.
|
||||
- Simultaneously submitted incompatible attempts resolve from one snapshot and
|
||||
one deterministic initiative/conflict pass. Arrival order at HTTP or CultNet
|
||||
transport is not fictional initiative.
|
||||
- Each active member contributes the allowance returned by the entitlement
|
||||
port. The campaign pool is capped by the operator ceiling of 240. Human
|
||||
actors occupy mandatory cells without Persona inference; provider request
|
||||
concurrency remains independent of the chosen cover.
|
||||
- Reconnect and replay derive the player's view from committed receipts and
|
||||
perception rules. A client cache cannot repair or override the kernel.
|
||||
- One malformed, stale, or unauthorized participant proposal cannot partially
|
||||
mutate the shared world.
|
||||
|
||||
## Social policy still to design
|
||||
|
||||
The architecture makes shared worlds straightforward. A usable multiplayer
|
||||
game still needs explicit answers for:
|
||||
|
||||
- exclusive character control, temporary delegation, and permanent departure;
|
||||
- host powers over invitation, removal, reset, fork, export, and campaign policy;
|
||||
- asynchronous pacing and how much fictional time one active player may advance;
|
||||
- simultaneous declaration windows for conflict, stealth, and split scenes;
|
||||
- consent for player-versus-player persuasion, deception, theft, restraint,
|
||||
injury, extraordinary influence, and character death;
|
||||
- disclosure of hidden rolls, private messages, secrets, and retrospective logs;
|
||||
- moderation, blocking, reporting, and campaign-data deletion;
|
||||
- mixed privacy/provider lanes and whether one campaign may contain them;
|
||||
- campaign billing, seats, guests, and ownership transfer.
|
||||
|
||||
These are campaign-governance decisions, not browser affordances. They must be
|
||||
typed, persisted, inspectable, and enforced at command admission.
|
||||
|
||||
## Product sequence
|
||||
|
||||
1. Prove the solo loop and multiresolution setting agency. **Complete.**
|
||||
2. Add campaign membership and exact actor-control assignments. **Complete.**
|
||||
3. Support up to eight cooperative players in one scene with actor-specific
|
||||
output and unanimous group governance. **Complete in this milestone.**
|
||||
4. Support split locations, private communication, departure, and late joining.
|
||||
5. Add snapshot-bound simultaneous declaration windows.
|
||||
6. Admit adversarial actions only after consent and governance policy is typed
|
||||
and tested.
|
||||
|
||||
The first multiplayer acceptance target should be cooperative and small. The
|
||||
runtime should earn social complexity one invariant at a time.
|
||||
|
||||
## Acceptance direction
|
||||
|
||||
- Two players in one scene see one committed event and their own permitted
|
||||
interpretations.
|
||||
- A private fact learned by one player never appears in the other's projection.
|
||||
- Split players can act in different locations without duplicating geometry,
|
||||
actors, clocks, or institutions.
|
||||
- Concurrent incompatible attempts resolve once from the same revision.
|
||||
- A disconnected player remains unpuppeted while world clocks and remote agency
|
||||
continue under campaign policy.
|
||||
- Rejoining reconstructs the player's permitted continuity from exact receipts.
|
||||
- Gestalt merge, split, migration, and named-member rematerialisation remain
|
||||
correct while several human actors create simultaneous foreground pressure.
|
||||
|
|
@ -1,14 +1,10 @@
|
|||
# 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).
|
||||
the authority map for implementation work. The pre-rebuild body remains
|
||||
described in `notes/ghostlight-current-system-map.md` only as teardown evidence.
|
||||
|
||||
Ghostlight is a persistent, source-grounded narrative world. Its job is to
|
||||
preserve people, institutions, places, knowledge, material consequence, and
|
||||
|
|
@ -17,8 +13,8 @@ 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
|
||||
Build one sparse, open-world causal machine that supports solo and bounded
|
||||
co-op play, 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
|
||||
|
|
@ -65,14 +61,11 @@ 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;
|
||||
- lifecycle phase and revision;
|
||||
- membership, contract, boundaries, and approvals;
|
||||
- the typed world ontology;
|
||||
- committed events and fictional time;
|
||||
- fictional time, commitments, and pressures;
|
||||
- command idempotency and the commit digest chain.
|
||||
|
||||
There is no separate Session Zero owner, component-world owner, aggregate
|
||||
|
|
@ -82,14 +75,11 @@ campaign owner, elaboration committer, scheduler writer, or recovery writer.
|
|||
|
||||
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.
|
||||
- a stable command ID;
|
||||
- the exact world ID and expected revision;
|
||||
- an authenticated principal or internal system capability;
|
||||
- one closed command body;
|
||||
- exact evidence references where the command depends on source material.
|
||||
|
||||
The caller supplies identity evidence, not an authority verdict. For a patch
|
||||
command the kernel derives the caller's authority itself:
|
||||
|
|
@ -107,17 +97,15 @@ controller receives a privileged mutation path.
|
|||
|
||||
### Outputs
|
||||
|
||||
An accepted command produces one `WorldCommit` (`crates/ghostlight/src/lib.rs`)
|
||||
whose fields are:
|
||||
An accepted command produces one `WorldCommit` containing:
|
||||
|
||||
- `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`.
|
||||
- previous and resulting revision;
|
||||
- previous and resulting state digest;
|
||||
- command ID and derived authority digest;
|
||||
- the exact admitted mutation batch;
|
||||
- committed events;
|
||||
- evidence references;
|
||||
- commit time and previous commit digest.
|
||||
|
||||
The next `WorldState` and `WorldCommit` are persisted atomically. A rejection
|
||||
returns typed invariant failures and changes nothing.
|
||||
|
|
@ -163,40 +151,28 @@ command.
|
|||
`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
|
||||
WorldState
|
||||
identity: world_id, revision, phase, state_digest, last_commit_digest
|
||||
governance: members, actor bindings, contract, boundaries, 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)
|
||||
places and directed routes
|
||||
subjects and typed components
|
||||
relations
|
||||
pressures and commitments
|
||||
facts, knowledge grants, and provenance
|
||||
external-owner grants
|
||||
time: fictional clock
|
||||
events: committed factual and speech events
|
||||
applied_commands: bounded idempotency ledger
|
||||
```
|
||||
|
||||
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.
|
||||
- `draft`: membership, negotiation, private/shared speech, character creation,
|
||||
evidence admission, and ontology construction are allowed by draft authority;
|
||||
- `active`: player and autonomous decisions, time, causal expansion, and
|
||||
contract amendments are allowed by active authority;
|
||||
- `archived`: only read/export operations are allowed.
|
||||
|
||||
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
|
||||
|
|
@ -257,20 +233,19 @@ 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:
|
||||
Relations have typed endpoints and kind-specific constraints. The vocabulary
|
||||
covers:
|
||||
|
||||
- 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.
|
||||
- containment and occupancy;
|
||||
- membership and lineage;
|
||||
- jurisdiction and representation;
|
||||
- custody and dependency;
|
||||
- authority and control;
|
||||
- supply and service;
|
||||
- alliance, opposition, and obligation;
|
||||
- knowledge and communication;
|
||||
- topology and access;
|
||||
- causal pressure and exposure.
|
||||
|
||||
Civic order is a typed subgraph of authority, selection or succession,
|
||||
resource access, representation, and redress relations. It is not a prose
|
||||
|
|
@ -313,22 +288,15 @@ authenticated intent or model tool call
|
|||
-> 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
|
||||
The closed command vocabulary includes lifecycle and membership changes,
|
||||
contract and boundary changes, speech, ontology construction, subject
|
||||
decisions, time advance, external snapshots, evidence admission, and archive.
|
||||
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
|
||||
Ghostlight supports two first-class decision interfaces. 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
|
||||
|
|
@ -466,9 +434,8 @@ 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
|
||||
to either of two transports chosen by the lane's configured model name: the
|
||||
CodexConnector daemon peer, unchanged, 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
|
||||
|
|
@ -511,9 +478,7 @@ 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`, and `GHOSTLIGHT_PLAY_MODEL` for the play table), each
|
||||
required: the deployment names the exact model id and an unset lane refuses
|
||||
startup.
|
||||
`_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
|
||||
|
|
@ -556,13 +521,11 @@ author proposal; they do not become a hidden admission tribunal.
|
|||
|
||||
## Persistence and recovery
|
||||
|
||||
One world `.cc` store (`crates/ghostlight/src/journal.rs`) contains:
|
||||
One world `.cc` store 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.
|
||||
- one current `world_state.v1` row;
|
||||
- immutable `world_commit.v1` rows forming a digest chain;
|
||||
- immutable exact evidence receipts referenced by commits.
|
||||
|
||||
Service authentication and model telemetry use separate service-owned stores.
|
||||
They cannot participate in world authority.
|
||||
|
|
@ -623,16 +586,11 @@ 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
|
||||
lane still uses. Exercising the road against a real controller again is the
|
||||
play agent's own gate (`ghostlight-play-agent.md`), not this contract.
|
||||
`world.create`'s current payload is `world_create.v4`: title, brief, targets,
|
||||
jurisdiction roots and lens weights are required, and Dungeon's create surface
|
||||
offers uniform weights as its editable default. `world.seed` runs one
|
||||
`SeedRunner` session per invocation against a `VaultEvidenceSource`.
|
||||
|
||||
Focused tests must prove:
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue