diff --git a/.gitignore b/.gitignore
index 1bfbf95..e90c6ba 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,6 @@
node_modules/
+web/dist/
+sidecar/claude-sdk/dist/
target/
# Disposable local scaffolding. These accumulated to ~87MB of untracked debris
@@ -11,6 +13,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
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..578af4b
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "vendor/eve"]
+ path = vendor/eve
+ url = https://github.com/GameCult/Eve.git
diff --git a/AGENTS.md b/AGENTS.md
index fb6393d..d258e9c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -5,17 +5,14 @@
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.
+well as Ghostlight Dungeon, the single-player DM-led client. `README.md` says
+what exists today and what does not.
## Where State Lives
- 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`).
+ is `ghostlight-verse`; query it through the `eureka-state` tools.
- `notes/ghostlight-verse-target.md` and `notes/ghostlight-verse-map.md` are the
campaign's prose target and map. Read the map for probed body facts.
- This repo has no state directory, no state CLI, and no evidence ledger. Do not
@@ -58,23 +55,28 @@ says what exists today and what does not.
- 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`).
+- Dungeon daemon: `crates/ghostlight-dungeon/src/` (`runtime.rs` for routes and
+ commands, `play.rs` for the play table, `eve.rs` for the surface).
+ Interface authority: `docs/architecture/ghostlight-eve-native-interface.md`.
- Persona membrane: `crates/ghostlight-persona-projection/src/lib.rs`.
-- Architecture rationale (earlier Dungeon / parked Eve surface design record):
- `docs/architecture/ghostlight-dungeon-mvp.md`.
+- Browser host: `web/`. Claude SDK sidecar: `sidecar/claude-sdk/`.
+- Architecture rationale: `docs/architecture/ghostlight-dungeon-mvp.md`.
`notes/ghostlight-implementation-plan.md` is the historical plan of the 2026-09
rebuild, not the current plan.
## Build, Verify, Deploy
-`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.
+Ghostlight Dungeon ships to Linux on Yggdrasil. Idunn freezes an exact commit,
+runs the locked native Linux tests, builds the daemon and web projection in
+pinned containers, and seals the release. The steps are
+`deployment/idunn/recipe.toml`; the owning runbook is
+`gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`.
+
+You are probably reading this on a Windows workstation. That is where the shell
+is, not where the artifact runs. A Windows compile is not evidence about the
+Linux release; build for the target, or let the deploy path's builder do it, and
+say which one you used. Heavy builds and test runs go to Yggdrasil, not the
+workstation. Deploy only through Idunn (`idunn up ghostlight`).
For infrastructure, SSH, Idunn, Odin, or Heimdall work, consult
`F:\Projects\gamecult-ops` before acting.
diff --git a/Cargo.lock b/Cargo.lock
index 2895d58..892fe21 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -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",
diff --git a/Cargo.toml b/Cargo.toml
index 0f5ed13..7bfeb7e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -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"
diff --git a/README.md b/README.md
index f573484..ad0d20c 100644
--- a/README.md
+++ b/README.md
@@ -1,123 +1,148 @@
# 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 is a Rust library that keeps a simulated world honest, and a play
+daemon built on it. A language model proposes; the library's kernel checks each
+proposal against typed world state and admits or refuses it. Places, people,
+knowledge, commitments, and time live in the kernel's journal, not in a model's
+context window, so they survive restarts and long stories.
-**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.
+## What is here
-**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.
+| Part | Path | What it is |
+|---|---|---|
+| World kernel | `crates/ghostlight/` | The sealed `ghostlight` library: world state, the closed operation set and reducer, the CultCache journal, the mailbox that is its only door, controllers, elaboration, lenses, the consumer ingress, and the inference ports. |
+| Persona projection | `crates/ghostlight-persona-projection/` | The membrane between structured state and a prose-only Persona: projection, Persona turn receipts, and the controller descriptors the kernel consumes. |
+| Dungeon | `crates/ghostlight-dungeon/` | The `ghostlight-dungeon` daemon: single-player, DM-led play over one world. HTTP and Eve routes, Heimdall sign-in, app sessions, the play table, CultMesh publication, and Idunn health. |
+| Browser | `web/` | A thin Eve browser host and the Heimdall access adapter. It renders the server's surface and owns no product state. |
+| Claude SDK sidecar | `sidecar/claude-sdk/` | A Node process that serves `claude`-prefixed models to the kernel through the Claude Agent SDK. It is a stopgap for a direct Messages API port. |
+| Deploy recipe | `deployment/idunn/recipe.toml` | The steps Idunn runs to test, build, and seal a release. |
+| Eve | `vendor/eve/` | A git submodule (`.gitmodules`) supplying the Eve browser lowering and contracts. |
-- `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`).
+## How it works
-Start with those two documents, then `cargo doc -p ghostlight --open`.
-
-**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.
-
-## Elaborators
-
-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.
-
-## Direction (planned, not built)
-
-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`.
+- The kernel is sealed. A consumer reaches it through create/open, immutable
+ snapshots, command submission, typed receipts, and the runner and port entry
+ points. There is no public mutable state, ID issuer, reducer, or journal
+ writer, and the crate declares no cargo features. The seal is proven by
+ `compile_fail` doc-tests in `crates/ghostlight/src/lib.rs` and by
+ `crates/ghostlight/tests/external_admission.rs`, which forges IDs, digests,
+ and opportunities and asserts that each is refused with nothing committed.
+- Every change enters one mailbox (`crates/ghostlight/src/mailbox.rs`) as a
+ command, is decided by one reducer, and commits atomically to a
+ digest-chained journal (`crates/ghostlight/src/journal.rs`, CultCache on redb).
+- Models author through typed tools and a repair loop
+ (`crates/ghostlight/src/elaboration.rs`, `tool_schema.rs`, `patch.rs`). A
+ refused proposal returns its mismatches to the model; it never edits state.
+- A Persona speaks only prose. A Projector builds its view, and an Interpreter
+ lowers its words into typed proposals with exact source quotes
+ (`crates/ghostlight/src/controllers.rs`).
+- Vault evidence for seeding comes from a read-only markdown directory reader
+ (`crates/ghostlight/src/vault.rs`). The Dungeon's seed lane reads the
+ directory named by `GHOSTLIGHT_SEED_VAULT_ROOT`
+ (`crates/ghostlight-dungeon/src/runtime.rs`).
+- Other programs can propose changes to the characters they control through
+ `POST /cultnet/world-patch` (`crates/ghostlight-dungeon/src/runtime.rs`,
+ `crates/ghostlight/src/consumer.rs`). The contract is
+ `docs/architecture/ghostlight-world-consumer-api.md`.
## Ghostlight Dungeon
-`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.
+Dungeon is the single-player, DM-led client. A player signs in with Heimdall,
+creates a world, seeds it from a vault, approves and activates it, and plays in
+free text. The play table (`crates/ghostlight-dungeon/src/play.rs`) owns the
+turn lifecycle; the interface is one Eve surface, `ghostlight.play`
+(`crates/ghostlight-dungeon/src/eve.rs`, described in
+`docs/architecture/ghostlight-eve-native-interface.md`). Because its player is
+not a developer, Dungeon is judged by whether someone can sit down and play.
-## Repo map
+Where it runs:
-| 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. |
+- **Yggdrasil**, under Idunn, built from `main` by `deployment/idunn/recipe.toml`.
+ Idunn owns the daemon's lifecycle and the write lease. Odin supplies discovery
+ and Heimdall's command-boundary record. The operating runbook is
+ `gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`.
+- **Inference** is routed by model name: a `local/` prefix goes to an
+ OpenAI-compatible loopback endpoint
+ (`GHOSTLIGHT_LOCAL_ENDPOINT`, `crates/ghostlight/src/local_inference.rs`),
+ which in production is Bonsai on Raven's GPU reached through a loopback
+ tunnel; a `claude` prefix goes to the SDK sidecar
+ (`GHOSTLIGHT_SDK_SIDECAR`, `crates/ghostlight/src/sdk_inference.rs`).
+ Ghostlight never reads, stores, or forwards a model credential.
+- **Sign-in** is Heimdall's. Ghostlight keeps a hashed HttpOnly session and
+ derives authority from the world's owner and approvers.
-`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.
+## Direction
+
+The next work makes Ghostlight the simulation behind Aetheria's public story.
+The operator's rulings (campaign `ghostlight-verse` in the Eureka mind) ask for:
+
+- a world loaded from the Aetheria verse, with factions and a cast;
+- storylets for Aetheria;
+- a persistent cast whose characters keep identity, memory, and commitments
+ across sessions, so serialized episodes can follow them;
+- episodes a cheap pipeline can turn into a video stream, and channel
+ characters who later appear in the game.
+
+None of this exists yet. Nothing under `crates/` loads Aetheria lore, models
+storylets, or produces an episode. Every event the kernel admits is meant to
+have exactly one render path: ship action filmed in Aetheria, or a social verb
+staged as an Aetheria conversation. Today a world can declare any affordance
+kind, and the kernel does not enforce that restriction.
## Build and test
-Dungeon deploys to Yggdrasil through Idunn from `deployment/idunn/recipe.toml`.
-Linux verification runs on Yggdrasil, not on a workstation:
+The release target is Linux on Yggdrasil; a Windows build says nothing about
+it. Idunn runs the steps in `deployment/idunn/recipe.toml`, which are the
+verification:
```sh
-cargo build --locked --workspace
+git submodule update --init vendor/eve
cargo test --locked -p ghostlight-persona-projection
cargo test --locked -p ghostlight
-cargo test --locked -p ghostlight-dungeon
-cargo test --locked -p ghostlight-verse
+cargo test --locked -p ghostlight-dungeon --bin ghostlight-dungeon
+cargo build --locked --release -p ghostlight-dungeon --bin ghostlight-dungeon
+npm --prefix web ci
+npm --prefix web test
+npm --prefix web run build
```
-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.
+The sidecar has its own `npm --prefix sidecar/claude-sdk run build` and `test`
+(also the root scripts `sdk:build` and `sdk:test`). Four Dungeon tests are
+`#[ignore]`d because they drive the vendored browser lowering through
+`tools/eve_client_bridge.mjs` and need Node beside cargo. The release
+acceptance step runs `controllers::tests::real_local_model_cognition_modes_commit_speech`
+(ignored by default) against 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.
+To run Dungeon locally: `npm run dungeon:run`, or
+`cargo run -p ghostlight-dungeon -- --state-root PATH`. Configuration is by
+`GHOSTLIGHT_*` environment variables; the recipe's `required_environment`
+lists the ones a deployment sets.
-Runtime documents are MessagePack-backed CultCache. JSON appears only at schema
-publication, model-provider and diagnostic boundaries.
+## Documents
+
+- `AGENTS.md`: repository doctrine for agents.
+- `docs/architecture/ghostlight-dungeon-mvp.md`: the authority architecture
+ of the world machine.
+- `docs/architecture/ghostlight-world-ontology.md`: the vocabulary and the
+ kernel's current mechanism.
+- `docs/architecture/ghostlight-world-consumer-api.md`: the consumer contract.
+- `docs/architecture/ghostlight-eve-native-interface.md`: the Eve surface.
+- `docs/architecture/ghostlight-library-extraction.md`,
+ `ghostlight-stock-lenses.md`: closed records of landed work. Pages ending in
+ `-cut.md` and `-postmortem.md` are dated history.
+- `docs/architecture/ghostlight-play-agent.md`: historical. Its status line
+ predates the play-agent cuts; read it with `-cut.md` beside it, not as the
+ current play surface (`crates/ghostlight-dungeon/src/play.rs` is).
+- `docs/architecture/ghostlight-session-zero.md`: unbuilt design, superseded by
+ the play agent. Nothing in `crates/` implements it.
+- `notes/fresh-workspace-handoff.md`: where things run and where open work is
+ recorded.
+- `docs/public-architecture/`, `docs/articles/`: unbuilt design and essays
+ written before the rebuild. They describe campaigns, co-op, Nemesis
+ and strategic resolvers as organs; none of that exists in `crates/`. They do not
+ describe the running machine.
+- `docs/product/lore-vault-entitlements.md`: a product proposal for hosted
+ vaults; nothing in `crates/` implements it.
+
+Runtime documents use MessagePack-backed CultCache. JSON appears only at schema
+publication, browser, model-provider, and diagnostic boundaries.
diff --git a/crates/ghostlight-dungeon/Cargo.toml b/crates/ghostlight-dungeon/Cargo.toml
index 39babbb..ff99b00 100644
--- a/crates/ghostlight-dungeon/Cargo.toml
+++ b/crates/ghostlight-dungeon/Cargo.toml
@@ -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"] }
diff --git a/crates/ghostlight-dungeon/page/index.html b/crates/ghostlight-dungeon/page/index.html
deleted file mode 100644
index 4284902..0000000
--- a/crates/ghostlight-dungeon/page/index.html
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
-
-
-Ghostlight Dungeon
-
-
-
-
-
-
-
-
-
-
-
-
-
Loading…
-
-
-
-
diff --git a/crates/ghostlight-dungeon/page/page.css b/crates/ghostlight-dungeon/page/page.css
deleted file mode 100644
index 3e098d5..0000000
--- a/crates/ghostlight-dungeon/page/page.css
+++ /dev/null
@@ -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; }
diff --git a/crates/ghostlight-dungeon/page/page.js b/crates/ghostlight-dungeon/page/page.js
deleted file mode 100644
index 964b08f..0000000
--- a/crates/ghostlight-dungeon/page/page.js
+++ /dev/null
@@ -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();
diff --git a/crates/ghostlight-dungeon/playtest/plan.json b/crates/ghostlight-dungeon/playtest/plan.json
deleted file mode 100644
index 53d26d9..0000000
--- a/crates/ghostlight-dungeon/playtest/plan.json
+++ /dev/null
@@ -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 }
- }
- ]
-}
diff --git a/crates/ghostlight-dungeon/src/api.rs b/crates/ghostlight-dungeon/src/api.rs
deleted file mode 100644
index 83ee34b..0000000
--- a/crates/ghostlight-dungeon/src/api.rs
+++ /dev/null
@@ -1,2246 +0,0 @@
-//! The Deru API: JSON over HTTPS behind the Heimdall session cookie.
-//!
-//! Handlers hold no game state and call no model. They read the catalog and
-//! the turn record, and every command goes through `begin` or
-//! `PlayTable::admit`/`execute`, the only writers.
-
-use crate::{
- auth_guard::{BEGIN_COOKIE, BEGIN_TTL_SECONDS},
- heimdall::AuthBeginReceipt,
- begin::{BeginRequest, begin},
- catalog::SeedStatus,
- run_ahead::{evidence_of, run_ahead},
- waves::run_waves,
- play::{Admission, OpenQuestion, PlayError, PlayRequest, PlayTurnState, PlayTurnView},
- runtime::AppState,
-};
-use axum::{
- Json, Router,
- extract::{DefaultBodyLimit, Path, Query, State},
- http::{HeaderMap, HeaderValue, StatusCode, header},
- response::{
- IntoResponse, Response,
- sse::{Event as SseEvent, KeepAlive, Sse},
- },
- routing::{get, post},
-};
-use chrono::{DateTime, Utc};
-use ghostlight::{CommandId, Lens, VerifiedPrincipalEvidence, WorldPhase};
-use serde::Deserialize;
-use serde_json::{Value, json};
-use std::{convert::Infallible, time::Duration};
-use tokio::sync::broadcast;
-
-pub(crate) const COOKIE_NAME: &str = "ghostlight_session";
-const BODY_LIMIT: usize = 64 * 1024;
-
-/// What a player sees of a turn that died on its model: one fixed line. The
-/// fault's own detail stays in the store and the log.
-pub(crate) const PLAY_FAULT_LINE: &str =
- "The storyteller lost the thread and your turn ended. Write again to start a new turn.";
-
-const CONTINUE_HINT: &str =
- "Your last turn did not finish. If nothing arrives, submit an empty message to continue it.";
-
-pub(crate) fn router() -> Router {
- Router::new()
- .route("/api/me", get(me))
- .route("/api/timelines", get(timelines))
- .route("/api/vaults", get(vaults))
- .route("/api/begin", post(begin_world))
- .route("/api/play", post(play))
- .route("/api/turn/{timeline}", get(turn))
- .route("/api/turn/{timeline}/stream", get(turn_stream))
- .route("/api/history/{timeline}", get(history))
- .route("/api/auth/begin", post(auth_begin))
- .route("/api/auth/complete", post(auth_complete))
- .route("/api/auth/logout", post(auth_logout))
- .layer(DefaultBodyLimit::max(BODY_LIMIT))
-}
-
-fn reply(status: StatusCode, body: Value) -> Response {
- (status, Json(body)).into_response()
-}
-
-fn refuse(status: StatusCode, message: impl std::fmt::Display) -> Response {
- reply(status, json!({"error": message.to_string()}))
-}
-
-fn unauthorized() -> Response {
- refuse(StatusCode::UNAUTHORIZED, "sign in first")
-}
-
-/// The refusal of a play on a world that is not Active: 409 with the status
-/// the page shows (`seeding`, `failed` with its reason, or `draft`).
-fn unplayable(status: &str, reason: Option<&str>) -> Response {
- let error = match status {
- "seeding" => "this world is still being seeded",
- "failed" => "this world's seed did not finish",
- _ => "this world is not active yet",
- };
- reply(StatusCode::CONFLICT, json!({"error": error, "status": status, "reason": reason}))
-}
-
-/// The turn as the player sees it: narration, the open question, the refusal
-/// of their own act and the fault line. It is derived from the turn record
-/// and is display-only; nothing reads it back.
-pub(crate) fn turn_view_json(timeline: &str, view: Option<&PlayTurnView>) -> Value {
- let Some(view) = view else {
- return json!({"timeline": timeline, "turn": null});
- };
- let question = view.question.as_ref().map(|question: &OpenQuestion| {
- json!({"text": question.text, "token": question.token})
- });
- json!({
- "timeline": timeline,
- "turn": {
- "id": view.turn_id,
- "state": match view.state {
- PlayTurnState::Running => "running",
- PlayTurnState::AwaitingPlayer => "awaiting_player",
- PlayTurnState::Closed => "closed",
- },
- "revision": view.revision,
- "narration": view.narration,
- "question": question,
- "refusal": view.refusal,
- "fault": view.fault.then_some(PLAY_FAULT_LINE),
- "text": view.player_text,
- "resolving": view.run_in_progress,
- "continue_hint": (view.state == PlayTurnState::Running && !view.run_in_progress)
- .then_some(CONTINUE_HINT),
- }
- })
-}
-
-/// The one door an answer's token is judged by: admits only when both sides
-/// are present and equal. An unminted token never matches anything.
-fn answer_token_admits(given: Option<&str>, expected: Option<&str>) -> bool {
- matches!((given, expected), (Some(given), Some(expected)) if given == expected)
-}
-
-pub(crate) fn cookie_value(headers: &HeaderMap) -> Option<&str> {
- named_cookie(headers, COOKIE_NAME)
-}
-
-fn named_cookie<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
- let prefix = format!("{name}=");
- headers
- .get(header::COOKIE)?
- .to_str()
- .ok()?
- .split(';')
- .map(str::trim)
- .find_map(|cookie| cookie.strip_prefix(&prefix))
-}
-
-fn session_cookie(raw: &str, expires_at: DateTime, now: DateTime) -> HeaderValue {
- HeaderValue::from_str(&format!(
- "{COOKIE_NAME}={raw}; Max-Age={}; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/",
- (expires_at - now).num_seconds().max(0)
- ))
- .expect("generated session cookie must be valid")
-}
-
-pub(crate) fn signal_fatal(state: &AppState, organ: &str, error: &impl std::fmt::Display) {
- let detail = format!("{organ}: {error}");
- tracing::error!(%detail, "runtime owner can no longer uphold its invariant");
- let _ = state.fatal.send(detail);
-}
-
-async fn authenticated_principal(
- headers: &HeaderMap,
- state: &AppState,
-) -> Option {
- let raw = cookie_value(headers)?;
- match state
- .sessions
- .lock()
- .await
- .account_for_cookie(raw, Utc::now())
- {
- Ok(account) => account,
- Err(error) => {
- signal_fatal(state, "app-session custody", &error);
- None
- }
- }
-}
-
-/// The sign-in providers this daemon offers, for the page's buttons.
-fn offered_providers(state: &AppState) -> Vec<&'static str> {
- ["discord", "google", "twitch"]
- .into_iter()
- .filter(|name| state.heimdall.offered(name).is_some())
- .collect()
-}
-
-async fn me(headers: HeaderMap, State(state): State) -> Response {
- let providers = offered_providers(&state);
- let Some(principal) = authenticated_principal(&headers, &state).await else {
- return reply(StatusCode::OK, json!({"signedIn": false, "providers": providers}));
- };
- let catalog = state.catalog.lock().await;
- let player = catalog.player(principal.account_subject_hash());
- reply(
- StatusCode::OK,
- json!({
- "signedIn": true,
- "providers": providers,
- "currentTimeline": player.and_then(|player| player.timeline.as_deref()),
- "destination": player.and_then(|player| player.destination.as_deref()),
- }),
- )
-}
-
-async fn timelines(headers: HeaderMap, State(state): State) -> Response {
- let Some(principal) = authenticated_principal(&headers, &state).await else {
- return unauthorized();
- };
- let account = principal.account_subject_hash();
- let catalog = state.catalog.lock().await;
- let current = catalog.player(account).and_then(|player| player.timeline.clone());
- let rows: Vec = catalog
- .timelines_of(account)
- .into_iter()
- .map(|(timeline, world)| {
- let (status, reason) = match catalog.seed_status(&timeline.id) {
- None => ("ready", None),
- Some(SeedStatus::Seeding) => ("seeding", None),
- Some(SeedStatus::Failed(reason)) => ("failed", Some(reason.as_str())),
- };
- json!({
- "timeline": timeline.id,
- "status": status,
- "reason": reason,
- "worldId": world.world_id,
- "title": world.title,
- "parent": timeline.parent,
- "snapshotId": world.snapshot_id,
- "createdAt": world.created_at,
- "current": current.as_deref() == Some(timeline.id.as_str()),
- })
- })
- .collect();
- reply(StatusCode::OK, json!({"timelines": rows}))
-}
-
-async fn vaults(headers: HeaderMap, State(state): State) -> Response {
- if authenticated_principal(&headers, &state).await.is_none() {
- return unauthorized();
- }
- let vaults: Vec<_> = state
- .vaults
- .offers()
- .into_iter()
- .map(|offer| json!({"name": offer.name, "default_era": offer.default_era, "eras": offer.eras.iter().map(|era| json!({"id": era.id, "label": era.label, "description": era.description})).collect::>()}))
- .collect();
- let lenses: Vec<_> = Lens::ALL
- .into_iter()
- .map(|lens| json!({"id": lens, "name": lens.name(), "reaches_for": lens.reaches_for()}))
- .collect();
- reply(StatusCode::OK, json!({"vaults": vaults, "lenses": lenses}))
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(deny_unknown_fields)]
-struct BeginBody {
- key: String,
- title: String,
- name: String,
- #[serde(default)]
- brief: Option,
- #[serde(default)]
- vault: Option,
- #[serde(default)]
- era: Option,
- /// Lens id (snake_case) to weight; omitted is every lens at one.
- #[serde(default)]
- lenses: Option>,
-}
-
-async fn begin_world(
- headers: HeaderMap,
- State(state): State,
- Json(body): Json,
-) -> Response {
- let Some(principal) = authenticated_principal(&headers, &state).await else {
- return unauthorized();
- };
- let outcome = begin(
- &state.catalog,
- &state.timelines,
- state.vaults.as_ref(),
- &state.scale,
- &principal,
- BeginRequest {
- key: body.key,
- title: body.title,
- name: body.name,
- brief: body.brief,
- vault: body.vault,
- era: body.era,
- lenses: body.lenses,
- },
- )
- .await;
- match outcome {
- Ok(begun) => reply(
- StatusCode::OK,
- json!({"timeline": begun.timeline, "reached": begun.reached}),
- ),
- Err(error) if error.unknown => reply(
- StatusCode::INTERNAL_SERVER_ERROR,
- json!({"error": error.to_string(), "outcome": "unknown"}),
- ),
- Err(error) => reply(
- StatusCode::CONFLICT,
- json!({"error": error.to_string(), "step": error.step}),
- ),
- }
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(deny_unknown_fields)]
-struct PlayBody {
- timeline: String,
- key: String,
- text: String,
- /// The token of the question this text answers, as the turn view showed it.
- #[serde(default)]
- answers: Option,
- /// The log entry (`seq`) this text retries. The new entry names it; the
- /// old one stays.
- #[serde(default)]
- retry_of: Option,
-}
-
-async fn play(
- headers: HeaderMap,
- State(state): State,
- Json(body): Json,
-) -> Response {
- let Some(principal) = authenticated_principal(&headers, &state).await else {
- return unauthorized();
- };
- if CommandId::parse_uuid(&body.key).is_err() {
- return refuse(StatusCode::BAD_REQUEST, "the play key is not a uuid");
- }
- let account = principal.account_subject_hash().to_owned();
- {
- let mut catalog = state.catalog.lock().await;
- if catalog.owned_timeline(&account, &body.timeline).is_none() {
- return refuse(StatusCode::NOT_FOUND, "no such timeline");
- }
- match catalog.seed_status(&body.timeline) {
- Some(SeedStatus::Seeding) => return unplayable("seeding", None),
- Some(SeedStatus::Failed(reason)) => return unplayable("failed", Some(reason.as_str())),
- None => {}
- }
- let current = catalog.player(&account).and_then(|player| player.timeline.as_deref());
- if current != Some(body.timeline.as_str())
- && let Err(error) = catalog.set_current(&account, &body.timeline)
- {
- tracing::warn!(%error, "the player's pointer could not move");
- }
- }
- let timeline = body.timeline.clone();
- let host = match state.timelines.host(&body.timeline).await {
- Ok(host) => host,
- Err(error) => {
- tracing::error!(%error, timeline = %body.timeline, "the timeline could not open");
- return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the timeline could not open");
- }
- };
- // The seed's status explains a refusal; the world's phase is what decides
- // it, so a Draft with no recorded seed is not playable either.
- match host.world.snapshot().await {
- Ok(world) if world.phase == WorldPhase::Active => {}
- Ok(_) => return unplayable("draft", None),
- Err(error) => {
- tracing::error!(%error, timeline = %body.timeline, "the world could not be read");
- return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the timeline could not open");
- }
- }
- // The server resolves the open question itself; the client proves it saw
- // it by its token. A token with no open question, or not that question's,
- // is stale and never reaches the table.
- let view = host.play.current_turn_view().await;
- let awaiting = view
- .as_ref()
- .is_some_and(|view| view.state == PlayTurnState::AwaitingPlayer);
- if body.answers.is_some() && !awaiting {
- return refuse(StatusCode::CONFLICT, "that question is closed");
- }
- let answers = match view
- .as_ref()
- .and_then(|view| view.question.as_ref())
- .filter(|_| awaiting)
- {
- None => None,
- Some(question) => {
- if !answer_token_admits(body.answers.as_deref(), question.token.as_deref()) {
- return refuse(
- StatusCode::CONFLICT,
- format!(
- "the answer is stale: its token does not name the question \"{}\" currently open",
- question.text
- ),
- );
- }
- Some(question.id.clone())
- }
- };
- if let Some(seq) = body.retry_of
- && !host.play.logged(seq).await
- {
- return refuse(StatusCode::CONFLICT, "that turn is not in the history");
- }
- let retry_of = body.retry_of;
- let admission = match host
- .play
- .admit(body.key, PlayRequest { text: body.text, answers })
- .await
- {
- Ok(admission) => admission,
- Err(
- error @ (PlayError::Poisoned
- | PlayError::World(_)
- | PlayError::Controller(_)
- | PlayError::Store(_)),
- ) => {
- tracing::error!(%error, "a play turn could not be admitted");
- return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the storyteller could not take that turn");
- }
- Err(error) => return refuse(StatusCode::CONFLICT, error),
- };
- let admitted = match admission {
- Admission::Replayed { .. } => return reply(StatusCode::OK, json!({"outcome": "replayed"})),
- Admission::Spawn(admitted) => admitted,
- };
- if let Some(seq) = retry_of {
- host.play.note_retry(&admitted, seq);
- }
- let _ = host.changes.send(());
- let spawned = host.clone();
- let state = state.clone();
- tokio::spawn(async move {
- let ran = spawned.play.execute(admitted, &principal).await;
- if let Err(error) = &ran {
- let turn_id = spawned.play.current_turn_view().await.map(|view| view.turn_id);
- tracing::warn!(%error, ?turn_id, "a play turn ended in error");
- }
- let _ = spawned.changes.send(());
- // The turn is closed: the world moves on what the clock made due, and
- // then answers some of its deficit ahead of play.
- let closed = ran.is_ok()
- && spawned
- .play
- .current_turn_view()
- .await
- .is_some_and(|view| view.state == PlayTurnState::Closed);
- if closed {
- run_waves(&spawned, spawned.play.last_logged().await).await;
- if let Some(evidence) = evidence_of(&state.catalog, state.vaults.as_ref(), &spawned, &timeline).await {
- run_ahead(&spawned, evidence, &state.scale).await;
- }
- }
- });
- reply(StatusCode::ACCEPTED, json!({"outcome": "accepted"}))
-}
-
-/// The host of a timeline the caller owns, or the refusal to send.
-async fn owned_host(
- headers: &HeaderMap,
- state: &AppState,
- timeline: &str,
-) -> Result, Response> {
- let Some(principal) = authenticated_principal(headers, state).await else {
- return Err(unauthorized());
- };
- if state
- .catalog
- .lock()
- .await
- .owned_timeline(principal.account_subject_hash(), timeline)
- .is_none()
- {
- return Err(refuse(StatusCode::NOT_FOUND, "no such timeline"));
- }
- state.timelines.host(timeline).await.map_err(|error| {
- tracing::error!(%error, timeline, "the timeline could not open");
- refuse(StatusCode::INTERNAL_SERVER_ERROR, "the timeline could not open")
- })
-}
-
-async fn turn(
- Path(timeline): Path,
- headers: HeaderMap,
- State(state): State,
-) -> Response {
- match owned_host(&headers, &state, &timeline).await {
- Ok(host) => {
- let view = host.play.current_turn_view().await;
- reply(StatusCode::OK, turn_view_json(&timeline, view.as_ref()))
- }
- Err(response) => response,
- }
-}
-
-
-#[derive(Debug, Deserialize)]
-struct HistoryQuery {
- /// Read the entries older than this `seq`; the newest page when absent.
- before: Option,
- limit: Option,
-}
-
-const HISTORY_PAGE: usize = 30;
-const HISTORY_PAGE_MAX: usize = 100;
-
-/// The signed-in account's own turn log for one timeline, a page at a time,
-/// oldest first so the newest entry is last. `owned_host` refuses any
-/// timeline the account does not own, so another account's log is unreachable.
-async fn history(
- Path(timeline): Path,
- Query(query): Query,
- headers: HeaderMap,
- State(state): State,
-) -> Response {
- let host = match owned_host(&headers, &state, &timeline).await {
- Ok(host) => host,
- Err(response) => return response,
- };
- let limit = query.limit.unwrap_or(HISTORY_PAGE).clamp(1, HISTORY_PAGE_MAX);
- let page = match host.play.history(query.before, limit).await {
- Ok(page) => page,
- Err(error) => {
- tracing::error!(%error, %timeline, "the turn log could not be read");
- return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the turn history could not be read");
- }
- };
- let entries: Vec = page
- .entries
- .into_iter()
- .map(|(entry, superseded_by)| {
- let mut value = serde_json::to_value(entry).expect("a log entry is plain data");
- value["superseded_by"] = json!(superseded_by);
- value
- })
- .collect();
- reply(StatusCode::OK, json!({"timeline": timeline, "entries": entries, "older": page.older}))
-}
-
-async fn turn_stream(
- Path(timeline): Path,
- headers: HeaderMap,
- State(state): State,
-) -> Response {
- let host = match owned_host(&headers, &state, &timeline).await {
- Ok(host) => host,
- Err(response) => return response,
- };
- // Subscribe before the first read so a change between the two is not lost.
- let mut changes = host.changes.subscribe();
- let stream = async_stream::stream! {
- let mut last: Option = None;
- loop {
- let view = host.play.current_turn_view().await;
- let json = turn_view_json(&timeline, view.as_ref()).to_string();
- if last.as_deref() != Some(json.as_str()) {
- yield Ok::(SseEvent::default().event("turn").data(json.clone()));
- last = Some(json);
- }
- tokio::select! {
- woke = changes.recv() => match woke {
- Ok(()) | Err(broadcast::error::RecvError::Lagged(_)) => {}
- Err(broadcast::error::RecvError::Closed) => break,
- },
- // A wake can be missed across a restart of the browser's own
- // connection; re-reading is cheap.
- _ = tokio::time::sleep(Duration::from_secs(15)) => {}
- }
- }
- };
- Sse::new(stream).keep_alive(KeepAlive::default()).into_response()
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(deny_unknown_fields)]
-struct AuthBeginBody {
- key: String,
- /// One of the providers the daemon offers (`GHOSTLIGHT_AUTH_PROVIDERS`).
- provider: String,
- /// The invite the browser presents for a first sign-in, if any. Checked
- /// against the catalog now, bound to this attempt, spent at complete.
- #[serde(default)]
- invite: Option,
-}
-
-/// The throttle's key: the address nginx sets in `X-Real-IP`. Behind the proxy
-/// the TCP peer is always loopback, so it names no one.
-fn client_key(headers: &HeaderMap) -> &str {
- headers
- .get("x-real-ip")
- .and_then(|value| value.to_str().ok())
- .map(str::trim)
- .filter(|value| !value.is_empty())
- .unwrap_or("direct")
-}
-
-fn throttled() -> Response {
- refuse(StatusCode::TOO_MANY_REQUESTS, "too many sign-in requests; wait a minute")
-}
-
-fn begin_cookie(secret: &str, max_age: i64) -> HeaderValue {
- HeaderValue::from_str(&format!(
- "{BEGIN_COOKIE}={secret}; Max-Age={max_age}; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/"
- ))
- .expect("generated begin cookie must be valid")
-}
-
-/// A pending Heimdall attempt's expiry, or `None` for a receipt that is not a
-/// live pending attempt.
-fn pending_expiry(receipt: &AuthBeginReceipt, now: DateTime) -> Option> {
- let expiry = receipt.expires_at.parse::>().ok()?;
- (receipt.status == "pending" && !receipt.handle.is_empty() && expiry > now).then_some(expiry)
-}
-
-async fn auth_begin(
- headers: HeaderMap,
- State(state): State,
- Json(body): Json,
-) -> Response {
- let now = Utc::now();
- if !state.auth.allow(client_key(&headers), now) {
- return throttled();
- }
- let Some(provider) = state.heimdall.offered(&body.provider) else {
- return refuse(StatusCode::BAD_REQUEST, "that sign-in provider is not offered");
- };
- let invite = body.invite.map(|token| token.trim().to_owned()).filter(|token| !token.is_empty());
- if let Some(token) = &invite
- && !state.catalog.lock().await.invite_is_live(token, now)
- {
- return refuse(StatusCode::FORBIDDEN, "that invite is spent or expired");
- }
- let receipt = match state.heimdall.begin(provider, invite.is_some(), &body.key).await {
- Ok(receipt) => receipt,
- Err(error) => {
- tracing::warn!(%error, "Heimdall refused to begin a sign-in");
- return refuse(StatusCode::BAD_GATEWAY, "Heimdall could not begin the sign-in.");
- }
- };
- let Some(expiry) = pending_expiry(&receipt, now) else {
- return refuse(StatusCode::BAD_GATEWAY, "Heimdall returned an invalid authentication attempt.");
- };
- let expiry = expiry.min(now + chrono::Duration::seconds(BEGIN_TTL_SECONDS));
- let Some(secret) = state.auth.start(&receipt.handle, invite, expiry, now) else {
- return refuse(StatusCode::SERVICE_UNAVAILABLE, "too many sign-ins are open; try again shortly");
- };
- let mut response = reply(
- StatusCode::OK,
- json!({
- "handle": receipt.handle,
- "url": receipt.navigation.url,
- "allowedOrigins": receipt.navigation.allowed_origins,
- }),
- );
- response.headers_mut().insert(
- header::SET_COOKIE,
- begin_cookie(&secret, (expiry - now).num_seconds().max(0)),
- );
- response
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(deny_unknown_fields)]
-struct AuthCompleteBody {
- handle: String,
- key: String,
-}
-
-async fn auth_complete(
- headers: HeaderMap,
- State(state): State,
- Json(body): Json,
-) -> Response {
- let now = Utc::now();
- if !state.auth.allow(client_key(&headers), now) {
- return throttled();
- }
- if body.handle.is_empty() {
- return refuse(StatusCode::BAD_REQUEST, "Authentication completion omitted its opaque handle.");
- }
- // Only the browser that began the attempt may complete it.
- let Some(secret) = named_cookie(&headers, BEGIN_COOKIE)
- .filter(|secret| state.auth.matches(&body.handle, secret, now))
- else {
- return refuse(StatusCode::FORBIDDEN, "this browser did not begin that sign-in");
- };
- let completion = match state.heimdall.complete(&body.handle, &body.key).await {
- Ok(value) => value,
- Err(error) => {
- tracing::warn!(%error, "Heimdall refused to complete a sign-in");
- return refuse(StatusCode::FORBIDDEN, "Heimdall could not complete the sign-in.");
- }
- };
- if completion.status == "pending" {
- return reply(StatusCode::ACCEPTED, json!({"status": "pending"}));
- }
- // Any other outcome ends the attempt: the binding is spent here, once.
- let Some(invite) = state.auth.consume(&body.handle, secret, now) else {
- return refuse(StatusCode::FORBIDDEN, "this browser did not begin that sign-in");
- };
- let spent = |mut response: Response| {
- response.headers_mut().append(header::SET_COOKIE, begin_cookie("", 0));
- response
- };
- if completion.status != "authenticated" || completion.handle.as_deref() != Some(body.handle.as_str()) {
- let message = completion
- .error
- .clone()
- .unwrap_or_else(|| "Heimdall denied access.".into());
- return spent(reply(StatusCode::FORBIDDEN, json!({"status": "denied", "error": message})));
- }
- let admission = match state.heimdall.verify_completion(completion).await {
- Ok(admission) => admission,
- Err(error) => {
- tracing::warn!(%error, "a Heimdall completion failed verification");
- return spent(reply(
- StatusCode::FORBIDDEN,
- json!({"status": "denied", "error": "Heimdall's answer could not be verified."}),
- ));
- }
- };
- // No account and no live invite: refused, never enrolled. The invite is
- // consumed only with the account it creates.
- let principal = match state
- .catalog
- .lock()
- .await
- .sign_in(admission.account_id(), invite.as_deref(), Utc::now())
- {
- Ok(Ok(principal)) => principal,
- Ok(Err(refusal)) => {
- return spent(reply(
- StatusCode::FORBIDDEN,
- json!({"status": "refused", "error": refusal.to_string()}),
- ));
- }
- Err(error) => {
- tracing::error!(%error, "the account catalog could not record a sign-in");
- return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the sign-in could not be recorded");
- }
- };
- // The session plays as the account's principal, which is the identity the
- // account was first made from. A session minted as another identity would
- // split one account across two worlds sets, so it is refused until a
- // second-identity link decides the principal (ruling
- // dungeon-account-principal-answer).
- if principal != admission.account_id() {
- return spent(reply(
- StatusCode::FORBIDDEN,
- json!({"status": "refused", "error": "this identity is linked to an account whose principal it does not carry"}),
- ));
- }
- let expires_at = admission.refresh_expires_at();
- let token = {
- let mut sessions = state.sessions.lock().await;
- let result = sessions.create_session(admission);
- if let Err(error) = &result
- && !sessions.is_healthy()
- {
- signal_fatal(&state, "app-session authentication adoption", error);
- }
- match result {
- Ok(token) => token,
- Err(error) => {
- tracing::warn!(%error, "an authenticated sign-in could not become a session");
- return spent(reply(
- StatusCode::FORBIDDEN,
- json!({"status": "denied", "error": "the session could not be created"}),
- ));
- }
- }
- };
- let mut response = spent(reply(StatusCode::OK, json!({"status": "authenticated"})));
- response
- .headers_mut()
- .append(header::SET_COOKIE, session_cookie(&token, expires_at, Utc::now()));
- response
-}
-
-async fn auth_logout(headers: HeaderMap, State(state): State) -> Response {
- let raw_cookie = cookie_value(&headers).unwrap_or_default();
- let local = {
- let mut sessions = state.sessions.lock().await;
- sessions
- .session_for_logout(raw_cookie)
- .and_then(|remote| sessions.revoke_cookie(raw_cookie).map(|_| remote))
- };
- let remote = match local {
- Ok(remote) => remote,
- Err(error) => {
- signal_fatal(&state, "app-session logout", &error);
- return reply(
- StatusCode::INTERNAL_SERVER_ERROR,
- json!({"status": "unknown", "error": "Local session revocation was not confirmed."}),
- );
- }
- };
- if let Some(session) = remote {
- let heimdall = state.heimdall.clone();
- tokio::spawn(async move {
- let idempotency = format!(
- "logout:{}:{}",
- session.heimdall_session_id, session.access_revision
- );
- if let Err(error) = heimdall.logout(&session.refresh_claim, &idempotency).await {
- tracing::warn!(%error, "local logout succeeded but Heimdall logout was unavailable");
- }
- });
- }
- let mut response = reply(StatusCode::OK, json!({"status": "anonymous"}));
- response.headers_mut().insert(
- header::SET_COOKIE,
- HeaderValue::from_static(
- "ghostlight_session=; Max-Age=0; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/",
- ),
- );
- response
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::{
- begin::tests::{Rig, author, deferred_rig, eventually, one_vault, principal, rig},
- heimdall::{
- AccountSummary, AuthBeginReceipt, AuthCompletionReceipt, AuthNavigation, AuthProvider,
- HeimdallPort, SessionRefresher, VerifiedSessionAdmission, VerifiedSessionRefresh,
- },
- play::{
- ASK_PLAYER_TOOL, END_TURN_TOOL,
- tests::{call_event, output, text_event},
- },
- runtime::service_router,
- };
- use axum::{
- body::{Body, to_bytes},
- http::{Method, Request},
- };
- use std::sync::Arc;
- use tokio::sync::Mutex;
- use tower::ServiceExt;
- use uuid::Uuid;
-
- /// A scripted Heimdall: it offers google and discord, hands out numbered
- /// handles, answers `complete` from what the test authenticated, and
- /// counts every call.
- #[derive(Default)]
- struct FakeHeimdall {
- begun: std::sync::Mutex>,
- /// Whether each begin carried the first-login grant, in order.
- grants: std::sync::Mutex>,
- completed: std::sync::Mutex,
- authenticated: std::sync::Mutex>,
- /// Overrides the next begin: an invalid receipt or a failure.
- begin_override: std::sync::Mutex